rdbms: Avoid selectDB() call in LoadMonitor new connections
[mediawiki.git] / includes / OutputPage.php
blob2a3a7cd147d71af382de576bba9a01f34422a210
1 <?php
2 /**
3 * Preparation for the final page rendering.
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.
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.
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
20 * @file
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Session\SessionManager;
26 use WrappedString\WrappedString;
27 use WrappedString\WrappedStringList;
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.
34 * This class is used to prepare the final rendering. A skin is then
35 * applied to the output parameters (links, javascript, html, categories ...).
37 * @todo FIXME: Another class handles sending the whole page to the client.
39 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
40 * in November 2010.
42 * @todo document
44 class OutputPage extends ContextSource {
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
48 /** @var array */
49 protected $mLinktags = [];
51 /** @var bool */
52 protected $mCanonicalUrl = false;
54 /**
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
58 protected $mExtStyles = [];
60 /**
61 * @var string Should be private - has getter and setter. Contains
62 * the HTML title */
63 public $mPagetitle = '';
65 /**
66 * @var string Contains all of the "<body>" content. Should be private we
67 * got set/get accessors and the append() method.
69 public $mBodytext = '';
71 /** @var string Stores contents of "<title>" tag */
72 private $mHTMLtitle = '';
74 /**
75 * @var bool Is the displayed content related to the source of the
76 * corresponding wiki article.
78 private $mIsarticle = false;
80 /** @var bool Stores "article flag" toggle. */
81 private $mIsArticleRelated = true;
83 /**
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
87 private $mPrintable = false;
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.
93 private $mSubtitle = [];
95 /** @var string */
96 public $mRedirect = '';
98 /** @var int */
99 protected $mStatusCode;
102 * @var string Used for sending cache control.
103 * The whole caching system should probably be moved into its own class.
105 protected $mLastModified = '';
107 /** @var array */
108 protected $mCategoryLinks = [];
110 /** @var array */
111 protected $mCategories = [
112 'hidden' => [],
113 'normal' => [],
116 /** @var array */
117 protected $mIndicators = [];
119 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
120 private $mLanguageLinks = [];
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.
128 private $mScripts = '';
130 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
131 protected $mInlineStyles = '';
134 * @var string Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 public $mPageLinkTitle = '';
139 /** @var array Array of elements in "<head>". Parser might add its own headers! */
140 protected $mHeadItems = [];
142 /** @var array */
143 protected $mModules = [];
145 /** @var array */
146 protected $mModuleScripts = [];
148 /** @var array */
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
155 private $rlClient;
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
160 /** @var string */
161 private $rlUserModuleState;
163 /** @var array */
164 private $rlExemptStyleModules;
166 /** @var array */
167 protected $mJsConfigVars = [];
169 /** @var array */
170 protected $mTemplateIds = [];
172 /** @var array */
173 protected $mImageTimeKeys = [];
175 /** @var string */
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
180 /** @var array
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = [
186 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
192 // Parser related.
194 /** @var int */
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
199 * @var ParserOptions
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = [];
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
216 /** @var bool */
217 protected $mNewSectionLink = false;
219 /** @var bool */
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
229 /** @var string */
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
247 /** @var string */
248 private $mRevisionTimestamp = null;
250 /** @var array */
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = [];
263 private $mIndexPolicy = 'index';
264 private $mFollowPolicy = 'follow';
265 private $mVaryHeader = [
266 'Accept-Encoding' => [ 'match=gzip' ],
270 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
271 * of the redirect.
273 * @var Title
275 private $mRedirectedFrom = null;
278 * Additional key => value data
280 private $mProperties = [];
283 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
285 private $mTarget = null;
288 * @var bool Whether parser output contains a table of contents
290 private $mEnableTOC = false;
293 * @var bool Whether parser output should contain section edit links
295 private $mEnableSectionEditLinks = true;
298 * @var string|null The URL to send in a <link> element with rel=license
300 private $copyrightUrl;
302 /** @var array Profiling data */
303 private $limitReportJSData = [];
306 * Link: header contents
308 private $mLinkHeader = [];
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
314 * @param IContextSource|null $context
316 function __construct( IContextSource $context = null ) {
317 if ( $context === null ) {
318 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
319 wfDeprecated( __METHOD__, '1.18' );
320 } else {
321 $this->setContext( $context );
326 * Redirect to $url rather than displaying the normal page
328 * @param string $url URL
329 * @param string $responsecode HTTP status code
331 public function redirect( $url, $responsecode = '302' ) {
332 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
333 $this->mRedirect = str_replace( "\n", '', $url );
334 $this->mRedirectCode = $responsecode;
338 * Get the URL to redirect to, or an empty string if not redirect URL set
340 * @return string
342 public function getRedirect() {
343 return $this->mRedirect;
347 * Set the copyright URL to send with the output.
348 * Empty string to omit, null to reset.
350 * @since 1.26
352 * @param string|null $url
354 public function setCopyrightUrl( $url ) {
355 $this->copyrightUrl = $url;
359 * Set the HTTP status code to send with the output.
361 * @param int $statusCode
363 public function setStatusCode( $statusCode ) {
364 $this->mStatusCode = $statusCode;
368 * Add a new "<meta>" tag
369 * To add an http-equiv meta tag, precede the name with "http:"
371 * @param string $name Tag name
372 * @param string $val Tag value
374 function addMeta( $name, $val ) {
375 array_push( $this->mMetatags, [ $name, $val ] );
379 * Returns the current <meta> tags
381 * @since 1.25
382 * @return array
384 public function getMetaTags() {
385 return $this->mMetatags;
389 * Add a new \<link\> tag to the page header.
391 * Note: use setCanonicalUrl() for rel=canonical.
393 * @param array $linkarr Associative array of attributes.
395 function addLink( array $linkarr ) {
396 array_push( $this->mLinktags, $linkarr );
400 * Returns the current <link> tags
402 * @since 1.25
403 * @return array
405 public function getLinkTags() {
406 return $this->mLinktags;
410 * Add a new \<link\> with "rel" attribute set to "meta"
412 * @param array $linkarr Associative array mapping attribute names to their
413 * values, both keys and values will be escaped, and the
414 * "rel" attribute will be automatically added
416 function addMetadataLink( array $linkarr ) {
417 $linkarr['rel'] = $this->getMetadataAttribute();
418 $this->addLink( $linkarr );
422 * Set the URL to be used for the <link rel=canonical>. This should be used
423 * in preference to addLink(), to avoid duplicate link tags.
424 * @param string $url
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl = $url;
431 * Returns the URL to be used for the <link rel=canonical> if
432 * one is set.
434 * @since 1.25
435 * @return bool|string
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl;
442 * Get the value of the "rel" attribute for metadata links
444 * @return string
446 public function getMetadataAttribute() {
447 # note: buggy CC software only reads first "meta" link
448 static $haveMeta = false;
449 if ( $haveMeta ) {
450 return 'alternate meta';
451 } else {
452 $haveMeta = true;
453 return 'meta';
458 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
459 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
460 * if possible.
462 * @param string $script Raw HTML
464 function addScript( $script ) {
465 $this->mScripts .= $script;
469 * Register and add a stylesheet from an extension directory.
471 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
472 * @param string $url Path to sheet. Provide either a full url (beginning
473 * with 'http', etc) or a relative path from the document root
474 * (beginning with '/'). Otherwise it behaves identically to
475 * addStyle() and draws from the /skins folder.
477 public function addExtensionStyle( $url ) {
478 wfDeprecated( __METHOD__, '1.27' );
479 array_push( $this->mExtStyles, $url );
483 * Get all styles added by extensions
485 * @deprecated since 1.27
486 * @return array
488 function getExtStyle() {
489 wfDeprecated( __METHOD__, '1.27' );
490 return $this->mExtStyles;
494 * Add a JavaScript file out of skins/common, or a given relative path.
495 * Internal use only. Use OutputPage::addModules() if possible.
497 * @param string $file Filename in skins/common or complete on-server path
498 * (/foo/bar.js)
499 * @param string $version Style version of the file. Defaults to $wgStyleVersion
501 public function addScriptFile( $file, $version = null ) {
502 // See if $file parameter is an absolute URL or begins with a slash
503 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
504 $path = $file;
505 } else {
506 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
508 if ( is_null( $version ) ) {
509 $version = $this->getConfig()->get( 'StyleVersion' );
511 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
515 * Add a self-contained script tag with the given contents
516 * Internal use only. Use OutputPage::addModules() if possible.
518 * @param string $script JavaScript text, no script tags
520 public function addInlineScript( $script ) {
521 $this->mScripts .= Html::inlineScript( $script );
525 * Filter an array of modules to remove insufficiently trustworthy members, and modules
526 * which are no longer registered (eg a page is cached before an extension is disabled)
527 * @param array $modules
528 * @param string|null $position If not null, only return modules with this position
529 * @param string $type
530 * @return array
532 protected function filterModules( array $modules, $position = null,
533 $type = ResourceLoaderModule::TYPE_COMBINED
535 $resourceLoader = $this->getResourceLoader();
536 $filteredModules = [];
537 foreach ( $modules as $val ) {
538 $module = $resourceLoader->getModule( $val );
539 if ( $module instanceof ResourceLoaderModule
540 && $module->getOrigin() <= $this->getAllowedModules( $type )
541 && ( is_null( $position ) || $module->getPosition() == $position )
543 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
544 $this->warnModuleTargetFilter( $module->getName() );
545 continue;
547 $filteredModules[] = $val;
550 return $filteredModules;
553 private function warnModuleTargetFilter( $moduleName ) {
554 static $warnings = [];
555 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
556 return;
558 $warnings[$this->mTarget][$moduleName] = true;
559 $this->getResourceLoader()->getLogger()->debug(
560 'Module "{module}" not loadable on target "{target}".',
562 'module' => $moduleName,
563 'target' => $this->mTarget,
569 * Get the list of modules to include on this page
571 * @param bool $filter Whether to filter out insufficiently trustworthy modules
572 * @param string|null $position If not null, only return modules with this position
573 * @param string $param
574 * @param string $type
575 * @return array Array of module names
577 public function getModules( $filter = false, $position = null, $param = 'mModules',
578 $type = ResourceLoaderModule::TYPE_COMBINED
580 $modules = array_values( array_unique( $this->$param ) );
581 return $filter
582 ? $this->filterModules( $modules, $position, $type )
583 : $modules;
587 * Add one or more modules recognized by ResourceLoader. Modules added
588 * through this function will be loaded by ResourceLoader when the
589 * page loads.
591 * @param string|array $modules Module name (string) or array of module names
593 public function addModules( $modules ) {
594 $this->mModules = array_merge( $this->mModules, (array)$modules );
598 * Get the list of module JS to include on this page
600 * @param bool $filter
601 * @param string|null $position
602 * @return array Array of module names
604 public function getModuleScripts( $filter = false, $position = null ) {
605 return $this->getModules( $filter, $position, 'mModuleScripts',
606 ResourceLoaderModule::TYPE_SCRIPTS
611 * Add only JS of one or more modules recognized by ResourceLoader. Module
612 * scripts added through this function will be loaded by ResourceLoader when
613 * the page loads.
615 * @param string|array $modules Module name (string) or array of module names
617 public function addModuleScripts( $modules ) {
618 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
622 * Get the list of module CSS to include on this page
624 * @param bool $filter
625 * @param string|null $position
626 * @return array Array of module names
628 public function getModuleStyles( $filter = false, $position = null ) {
629 return $this->getModules( $filter, $position, 'mModuleStyles',
630 ResourceLoaderModule::TYPE_STYLES
635 * Add only CSS of one or more modules recognized by ResourceLoader.
637 * Module styles added through this function will be added using standard link CSS
638 * tags, rather than as a combined Javascript and CSS package. Thus, they will
639 * load when JavaScript is disabled (unless CSS also happens to be disabled).
641 * @param string|array $modules Module name (string) or array of module names
643 public function addModuleStyles( $modules ) {
644 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
648 * @return null|string ResourceLoader target
650 public function getTarget() {
651 return $this->mTarget;
655 * Sets ResourceLoader target for load.php links. If null, will be omitted
657 * @param string|null $target
659 public function setTarget( $target ) {
660 $this->mTarget = $target;
664 * Get an array of head items
666 * @return array
668 function getHeadItemsArray() {
669 return $this->mHeadItems;
673 * Add or replace a head item to the output
675 * Whenever possible, use more specific options like ResourceLoader modules,
676 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
677 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
678 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
679 * This would be your very LAST fallback.
681 * @param string $name Item name
682 * @param string $value Raw HTML
684 public function addHeadItem( $name, $value ) {
685 $this->mHeadItems[$name] = $value;
689 * Add one or more head items to the output
691 * @since 1.28
692 * @param string|string[] $values Raw HTML
694 public function addHeadItems( $values ) {
695 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
699 * Check if the header item $name is already set
701 * @param string $name Item name
702 * @return bool
704 public function hasHeadItem( $name ) {
705 return isset( $this->mHeadItems[$name] );
709 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
710 * @param string $tag
712 public function setETag( $tag ) {
716 * Set whether the output should only contain the body of the article,
717 * without any skin, sidebar, etc.
718 * Used e.g. when calling with "action=render".
720 * @param bool $only Whether to output only the body of the article
722 public function setArticleBodyOnly( $only ) {
723 $this->mArticleBodyOnly = $only;
727 * Return whether the output will contain only the body of the article
729 * @return bool
731 public function getArticleBodyOnly() {
732 return $this->mArticleBodyOnly;
736 * Set an additional output property
737 * @since 1.21
739 * @param string $name
740 * @param mixed $value
742 public function setProperty( $name, $value ) {
743 $this->mProperties[$name] = $value;
747 * Get an additional output property
748 * @since 1.21
750 * @param string $name
751 * @return mixed Property value or null if not found
753 public function getProperty( $name ) {
754 if ( isset( $this->mProperties[$name] ) ) {
755 return $this->mProperties[$name];
756 } else {
757 return null;
762 * checkLastModified tells the client to use the client-cached page if
763 * possible. If successful, the OutputPage is disabled so that
764 * any future call to OutputPage->output() have no effect.
766 * Side effect: sets mLastModified for Last-Modified header
768 * @param string $timestamp
770 * @return bool True if cache-ok headers was sent.
772 public function checkLastModified( $timestamp ) {
773 if ( !$timestamp || $timestamp == '19700101000000' ) {
774 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
775 return false;
777 $config = $this->getConfig();
778 if ( !$config->get( 'CachePages' ) ) {
779 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
780 return false;
783 $timestamp = wfTimestamp( TS_MW, $timestamp );
784 $modifiedTimes = [
785 'page' => $timestamp,
786 'user' => $this->getUser()->getTouched(),
787 'epoch' => $config->get( 'CacheEpoch' )
789 if ( $config->get( 'UseSquid' ) ) {
790 // T46570: the core page itself may not change, but resources might
791 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
793 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
795 $maxModified = max( $modifiedTimes );
796 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
798 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
799 if ( $clientHeader === false ) {
800 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
801 return false;
804 # IE sends sizes after the date like this:
805 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
806 # this breaks strtotime().
807 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
809 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
810 $clientHeaderTime = strtotime( $clientHeader );
811 MediaWiki\restoreWarnings();
812 if ( !$clientHeaderTime ) {
813 wfDebug( __METHOD__
814 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
815 return false;
817 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
819 # Make debug info
820 $info = '';
821 foreach ( $modifiedTimes as $name => $value ) {
822 if ( $info !== '' ) {
823 $info .= ', ';
825 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
828 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
829 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
830 wfDebug( __METHOD__ . ": effective Last-Modified: " .
831 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
832 if ( $clientHeaderTime < $maxModified ) {
833 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
834 return false;
837 # Not modified
838 # Give a 304 Not Modified response code and disable body output
839 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
840 ini_set( 'zlib.output_compression', 0 );
841 $this->getRequest()->response()->statusHeader( 304 );
842 $this->sendCacheControl();
843 $this->disable();
845 // Don't output a compressed blob when using ob_gzhandler;
846 // it's technically against HTTP spec and seems to confuse
847 // Firefox when the response gets split over two packets.
848 wfClearOutputBuffers();
850 return true;
854 * Override the last modified timestamp
856 * @param string $timestamp New timestamp, in a format readable by
857 * wfTimestamp()
859 public function setLastModified( $timestamp ) {
860 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
864 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
866 * @param string $policy The literal string to output as the contents of
867 * the meta tag. Will be parsed according to the spec and output in
868 * standardized form.
869 * @return null
871 public function setRobotPolicy( $policy ) {
872 $policy = Article::formatRobotPolicy( $policy );
874 if ( isset( $policy['index'] ) ) {
875 $this->setIndexPolicy( $policy['index'] );
877 if ( isset( $policy['follow'] ) ) {
878 $this->setFollowPolicy( $policy['follow'] );
883 * Set the index policy for the page, but leave the follow policy un-
884 * touched.
886 * @param string $policy Either 'index' or 'noindex'.
887 * @return null
889 public function setIndexPolicy( $policy ) {
890 $policy = trim( $policy );
891 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
892 $this->mIndexPolicy = $policy;
897 * Set the follow policy for the page, but leave the index policy un-
898 * touched.
900 * @param string $policy Either 'follow' or 'nofollow'.
901 * @return null
903 public function setFollowPolicy( $policy ) {
904 $policy = trim( $policy );
905 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
906 $this->mFollowPolicy = $policy;
911 * Set the new value of the "action text", this will be added to the
912 * "HTML title", separated from it with " - ".
914 * @param string $text New value of the "action text"
916 public function setPageTitleActionText( $text ) {
917 $this->mPageTitleActionText = $text;
921 * Get the value of the "action text"
923 * @return string
925 public function getPageTitleActionText() {
926 return $this->mPageTitleActionText;
930 * "HTML title" means the contents of "<title>".
931 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
933 * @param string|Message $name
935 public function setHTMLTitle( $name ) {
936 if ( $name instanceof Message ) {
937 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
938 } else {
939 $this->mHTMLtitle = $name;
944 * Return the "HTML title", i.e. the content of the "<title>" tag.
946 * @return string
948 public function getHTMLTitle() {
949 return $this->mHTMLtitle;
953 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
955 * @param Title $t
957 public function setRedirectedFrom( $t ) {
958 $this->mRedirectedFrom = $t;
962 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
963 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
964 * but not bad tags like \<script\>. This function automatically sets
965 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
966 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
967 * good tags like \<i\> will be dropped entirely.
969 * @param string|Message $name
971 public function setPageTitle( $name ) {
972 if ( $name instanceof Message ) {
973 $name = $name->setContext( $this->getContext() )->text();
976 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
977 # but leave "<i>foobar</i>" alone
978 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
979 $this->mPagetitle = $nameWithTags;
981 # change "<i>foo&amp;bar</i>" to "foo&bar"
982 $this->setHTMLTitle(
983 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
984 ->inContentLanguage()
989 * Return the "page title", i.e. the content of the \<h1\> tag.
991 * @return string
993 public function getPageTitle() {
994 return $this->mPagetitle;
998 * Set the Title object to use
1000 * @param Title $t
1002 public function setTitle( Title $t ) {
1003 $this->getContext()->setTitle( $t );
1007 * Replace the subtitle with $str
1009 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1011 public function setSubtitle( $str ) {
1012 $this->clearSubtitle();
1013 $this->addSubtitle( $str );
1017 * Add $str to the subtitle
1019 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1021 public function addSubtitle( $str ) {
1022 if ( $str instanceof Message ) {
1023 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1024 } else {
1025 $this->mSubtitle[] = $str;
1030 * Build message object for a subtitle containing a backlink to a page
1032 * @param Title $title Title to link to
1033 * @param array $query Array of additional parameters to include in the link
1034 * @return Message
1035 * @since 1.25
1037 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1038 if ( $title->isRedirect() ) {
1039 $query['redirect'] = 'no';
1041 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1042 return wfMessage( 'backlinksubtitle' )
1043 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1047 * Add a subtitle containing a backlink to a page
1049 * @param Title $title Title to link to
1050 * @param array $query Array of additional parameters to include in the link
1052 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1053 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1057 * Clear the subtitles
1059 public function clearSubtitle() {
1060 $this->mSubtitle = [];
1064 * Get the subtitle
1066 * @return string
1068 public function getSubtitle() {
1069 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1073 * Set the page as printable, i.e. it'll be displayed with all
1074 * print styles included
1076 public function setPrintable() {
1077 $this->mPrintable = true;
1081 * Return whether the page is "printable"
1083 * @return bool
1085 public function isPrintable() {
1086 return $this->mPrintable;
1090 * Disable output completely, i.e. calling output() will have no effect
1092 public function disable() {
1093 $this->mDoNothing = true;
1097 * Return whether the output will be completely disabled
1099 * @return bool
1101 public function isDisabled() {
1102 return $this->mDoNothing;
1106 * Show an "add new section" link?
1108 * @return bool
1110 public function showNewSectionLink() {
1111 return $this->mNewSectionLink;
1115 * Forcibly hide the new section link?
1117 * @return bool
1119 public function forceHideNewSectionLink() {
1120 return $this->mHideNewSectionLink;
1124 * Add or remove feed links in the page header
1125 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1126 * for the new version
1127 * @see addFeedLink()
1129 * @param bool $show True: add default feeds, false: remove all feeds
1131 public function setSyndicated( $show = true ) {
1132 if ( $show ) {
1133 $this->setFeedAppendQuery( false );
1134 } else {
1135 $this->mFeedLinks = [];
1140 * Add default feeds to the page header
1141 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1142 * for the new version
1143 * @see addFeedLink()
1145 * @param string $val Query to append to feed links or false to output
1146 * default links
1148 public function setFeedAppendQuery( $val ) {
1149 $this->mFeedLinks = [];
1151 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1152 $query = "feed=$type";
1153 if ( is_string( $val ) ) {
1154 $query .= '&' . $val;
1156 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1161 * Add a feed link to the page header
1163 * @param string $format Feed type, should be a key of $wgFeedClasses
1164 * @param string $href URL
1166 public function addFeedLink( $format, $href ) {
1167 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1168 $this->mFeedLinks[$format] = $href;
1173 * Should we output feed links for this page?
1174 * @return bool
1176 public function isSyndicated() {
1177 return count( $this->mFeedLinks ) > 0;
1181 * Return URLs for each supported syndication format for this page.
1182 * @return array Associating format keys with URLs
1184 public function getSyndicationLinks() {
1185 return $this->mFeedLinks;
1189 * Will currently always return null
1191 * @return null
1193 public function getFeedAppendQuery() {
1194 return $this->mFeedLinksAppendQuery;
1198 * Set whether the displayed content is related to the source of the
1199 * corresponding article on the wiki
1200 * Setting true will cause the change "article related" toggle to true
1202 * @param bool $v
1204 public function setArticleFlag( $v ) {
1205 $this->mIsarticle = $v;
1206 if ( $v ) {
1207 $this->mIsArticleRelated = $v;
1212 * Return whether the content displayed page is related to the source of
1213 * the corresponding article on the wiki
1215 * @return bool
1217 public function isArticle() {
1218 return $this->mIsarticle;
1222 * Set whether this page is related an article on the wiki
1223 * Setting false will cause the change of "article flag" toggle to false
1225 * @param bool $v
1227 public function setArticleRelated( $v ) {
1228 $this->mIsArticleRelated = $v;
1229 if ( !$v ) {
1230 $this->mIsarticle = false;
1235 * Return whether this page is related an article on the wiki
1237 * @return bool
1239 public function isArticleRelated() {
1240 return $this->mIsArticleRelated;
1244 * Add new language links
1246 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1247 * (e.g. 'fr:Test page')
1249 public function addLanguageLinks( array $newLinkArray ) {
1250 $this->mLanguageLinks += $newLinkArray;
1254 * Reset the language links and add new language links
1256 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1257 * (e.g. 'fr:Test page')
1259 public function setLanguageLinks( array $newLinkArray ) {
1260 $this->mLanguageLinks = $newLinkArray;
1264 * Get the list of language links
1266 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1268 public function getLanguageLinks() {
1269 return $this->mLanguageLinks;
1273 * Add an array of categories, with names in the keys
1275 * @param array $categories Mapping category name => sort key
1277 public function addCategoryLinks( array $categories ) {
1278 global $wgContLang;
1280 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1281 return;
1284 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1286 # Set all the values to 'normal'.
1287 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1289 # Mark hidden categories
1290 foreach ( $res as $row ) {
1291 if ( isset( $row->pp_value ) ) {
1292 $categories[$row->page_title] = 'hidden';
1296 // Avoid PHP 7.1 warning of passing $this by reference
1297 $outputPage = $this;
1298 # Add the remaining categories to the skin
1299 if ( Hooks::run(
1300 'OutputPageMakeCategoryLinks',
1301 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1303 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1304 foreach ( $categories as $category => $type ) {
1305 // array keys will cast numeric category names to ints, so cast back to string
1306 $category = (string)$category;
1307 $origcategory = $category;
1308 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1309 if ( !$title ) {
1310 continue;
1312 $wgContLang->findVariantLink( $category, $title, true );
1313 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1314 continue;
1316 $text = $wgContLang->convertHtml( $title->getText() );
1317 $this->mCategories[$type][] = $title->getText();
1318 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1324 * @param array $categories
1325 * @return bool|ResultWrapper
1327 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1328 # Add the links to a LinkBatch
1329 $arr = [ NS_CATEGORY => $categories ];
1330 $lb = new LinkBatch;
1331 $lb->setArray( $arr );
1333 # Fetch existence plus the hiddencat property
1334 $dbr = wfGetDB( DB_REPLICA );
1335 $fields = array_merge(
1336 LinkCache::getSelectFields(),
1337 [ 'page_namespace', 'page_title', 'pp_value' ]
1340 $res = $dbr->select( [ 'page', 'page_props' ],
1341 $fields,
1342 $lb->constructSet( 'page', $dbr ),
1343 __METHOD__,
1345 [ 'page_props' => [ 'LEFT JOIN', [
1346 'pp_propname' => 'hiddencat',
1347 'pp_page = page_id'
1348 ] ] ]
1351 # Add the results to the link cache
1352 $lb->addResultToCache( LinkCache::singleton(), $res );
1354 return $res;
1358 * Reset the category links (but not the category list) and add $categories
1360 * @param array $categories Mapping category name => sort key
1362 public function setCategoryLinks( array $categories ) {
1363 $this->mCategoryLinks = [];
1364 $this->addCategoryLinks( $categories );
1368 * Get the list of category links, in a 2-D array with the following format:
1369 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1370 * hidden categories) and $link a HTML fragment with a link to the category
1371 * page
1373 * @return array
1375 public function getCategoryLinks() {
1376 return $this->mCategoryLinks;
1380 * Get the list of category names this page belongs to.
1382 * @param string $type The type of categories which should be returned. Possible values:
1383 * * all: all categories of all types
1384 * * hidden: only the hidden categories
1385 * * normal: all categories, except hidden categories
1386 * @return array Array of strings
1388 public function getCategories( $type = 'all' ) {
1389 if ( $type === 'all' ) {
1390 $allCategories = [];
1391 foreach ( $this->mCategories as $categories ) {
1392 $allCategories = array_merge( $allCategories, $categories );
1394 return $allCategories;
1396 if ( !isset( $this->mCategories[$type] ) ) {
1397 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1399 return $this->mCategories[$type];
1403 * Add an array of indicators, with their identifiers as array
1404 * keys and HTML contents as values.
1406 * In case of duplicate keys, existing values are overwritten.
1408 * @param array $indicators
1409 * @since 1.25
1411 public function setIndicators( array $indicators ) {
1412 $this->mIndicators = $indicators + $this->mIndicators;
1413 // Keep ordered by key
1414 ksort( $this->mIndicators );
1418 * Get the indicators associated with this page.
1420 * The array will be internally ordered by item keys.
1422 * @return array Keys: identifiers, values: HTML contents
1423 * @since 1.25
1425 public function getIndicators() {
1426 return $this->mIndicators;
1430 * Adds help link with an icon via page indicators.
1431 * Link target can be overridden by a local message containing a wikilink:
1432 * the message key is: lowercase action or special page name + '-helppage'.
1433 * @param string $to Target MediaWiki.org page title or encoded URL.
1434 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1435 * @since 1.25
1437 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1438 $this->addModuleStyles( 'mediawiki.helplink' );
1439 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1441 if ( $overrideBaseUrl ) {
1442 $helpUrl = $to;
1443 } else {
1444 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1445 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1448 $link = Html::rawElement(
1449 'a',
1451 'href' => $helpUrl,
1452 'target' => '_blank',
1453 'class' => 'mw-helplink',
1455 $text
1458 $this->setIndicators( [ 'mw-helplink' => $link ] );
1462 * Do not allow scripts which can be modified by wiki users to load on this page;
1463 * only allow scripts bundled with, or generated by, the software.
1464 * Site-wide styles are controlled by a config setting, since they can be
1465 * used to create a custom skin/theme, but not user-specific ones.
1467 * @todo this should be given a more accurate name
1469 public function disallowUserJs() {
1470 $this->reduceAllowedModules(
1471 ResourceLoaderModule::TYPE_SCRIPTS,
1472 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1475 // Site-wide styles are controlled by a config setting, see T73621
1476 // for background on why. User styles are never allowed.
1477 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1478 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1479 } else {
1480 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1482 $this->reduceAllowedModules(
1483 ResourceLoaderModule::TYPE_STYLES,
1484 $styleOrigin
1489 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1490 * @see ResourceLoaderModule::$origin
1491 * @param string $type ResourceLoaderModule TYPE_ constant
1492 * @return int ResourceLoaderModule ORIGIN_ class constant
1494 public function getAllowedModules( $type ) {
1495 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1496 return min( array_values( $this->mAllowedModules ) );
1497 } else {
1498 return isset( $this->mAllowedModules[$type] )
1499 ? $this->mAllowedModules[$type]
1500 : ResourceLoaderModule::ORIGIN_ALL;
1505 * Limit the highest level of CSS/JS untrustworthiness allowed.
1507 * If passed the same or a higher level than the current level of untrustworthiness set, the
1508 * level will remain unchanged.
1510 * @param string $type
1511 * @param int $level ResourceLoaderModule class constant
1513 public function reduceAllowedModules( $type, $level ) {
1514 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1518 * Prepend $text to the body HTML
1520 * @param string $text HTML
1522 public function prependHTML( $text ) {
1523 $this->mBodytext = $text . $this->mBodytext;
1527 * Append $text to the body HTML
1529 * @param string $text HTML
1531 public function addHTML( $text ) {
1532 $this->mBodytext .= $text;
1536 * Shortcut for adding an Html::element via addHTML.
1538 * @since 1.19
1540 * @param string $element
1541 * @param array $attribs
1542 * @param string $contents
1544 public function addElement( $element, array $attribs = [], $contents = '' ) {
1545 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1549 * Clear the body HTML
1551 public function clearHTML() {
1552 $this->mBodytext = '';
1556 * Get the body HTML
1558 * @return string HTML
1560 public function getHTML() {
1561 return $this->mBodytext;
1565 * Get/set the ParserOptions object to use for wikitext parsing
1567 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1568 * current ParserOption object
1569 * @return ParserOptions
1571 public function parserOptions( $options = null ) {
1572 if ( $options !== null && !empty( $options->isBogus ) ) {
1573 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1574 // been changed somehow, and keep it if so.
1575 $anonPO = ParserOptions::newFromAnon();
1576 $anonPO->setEditSection( false );
1577 $anonPO->setAllowUnsafeRawHtml( false );
1578 if ( !$options->matches( $anonPO ) ) {
1579 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1580 $options->isBogus = false;
1584 if ( !$this->mParserOptions ) {
1585 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1586 // $wgUser isn't unstubbable yet, so don't try to get a
1587 // ParserOptions for it. And don't cache this ParserOptions
1588 // either.
1589 $po = ParserOptions::newFromAnon();
1590 $po->setEditSection( false );
1591 $po->setAllowUnsafeRawHtml( false );
1592 $po->isBogus = true;
1593 if ( $options !== null ) {
1594 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1596 return $po;
1599 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1600 $this->mParserOptions->setEditSection( false );
1601 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1604 if ( $options !== null && !empty( $options->isBogus ) ) {
1605 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1606 // thing.
1607 return wfSetVar( $this->mParserOptions, null, true );
1608 } else {
1609 return wfSetVar( $this->mParserOptions, $options );
1614 * Set the revision ID which will be seen by the wiki text parser
1615 * for things such as embedded {{REVISIONID}} variable use.
1617 * @param int|null $revid An positive integer, or null
1618 * @return mixed Previous value
1620 public function setRevisionId( $revid ) {
1621 $val = is_null( $revid ) ? null : intval( $revid );
1622 return wfSetVar( $this->mRevisionId, $val );
1626 * Get the displayed revision ID
1628 * @return int
1630 public function getRevisionId() {
1631 return $this->mRevisionId;
1635 * Set the timestamp of the revision which will be displayed. This is used
1636 * to avoid a extra DB call in Skin::lastModified().
1638 * @param string|null $timestamp
1639 * @return mixed Previous value
1641 public function setRevisionTimestamp( $timestamp ) {
1642 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1646 * Get the timestamp of displayed revision.
1647 * This will be null if not filled by setRevisionTimestamp().
1649 * @return string|null
1651 public function getRevisionTimestamp() {
1652 return $this->mRevisionTimestamp;
1656 * Set the displayed file version
1658 * @param File|bool $file
1659 * @return mixed Previous value
1661 public function setFileVersion( $file ) {
1662 $val = null;
1663 if ( $file instanceof File && $file->exists() ) {
1664 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1666 return wfSetVar( $this->mFileVersion, $val, true );
1670 * Get the displayed file version
1672 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1674 public function getFileVersion() {
1675 return $this->mFileVersion;
1679 * Get the templates used on this page
1681 * @return array (namespace => dbKey => revId)
1682 * @since 1.18
1684 public function getTemplateIds() {
1685 return $this->mTemplateIds;
1689 * Get the files used on this page
1691 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1692 * @since 1.18
1694 public function getFileSearchOptions() {
1695 return $this->mImageTimeKeys;
1699 * Convert wikitext to HTML and add it to the buffer
1700 * Default assumes that the current page title will be used.
1702 * @param string $text
1703 * @param bool $linestart Is this the start of a line?
1704 * @param bool $interface Is this text in the user interface language?
1705 * @throws MWException
1707 public function addWikiText( $text, $linestart = true, $interface = true ) {
1708 $title = $this->getTitle(); // Work around E_STRICT
1709 if ( !$title ) {
1710 throw new MWException( 'Title is null' );
1712 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1716 * Add wikitext with a custom Title object
1718 * @param string $text Wikitext
1719 * @param Title &$title
1720 * @param bool $linestart Is this the start of a line?
1722 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1723 $this->addWikiTextTitle( $text, $title, $linestart );
1727 * Add wikitext with a custom Title object and tidy enabled.
1729 * @param string $text Wikitext
1730 * @param Title &$title
1731 * @param bool $linestart Is this the start of a line?
1733 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1734 $this->addWikiTextTitle( $text, $title, $linestart, true );
1738 * Add wikitext with tidy enabled
1740 * @param string $text Wikitext
1741 * @param bool $linestart Is this the start of a line?
1743 public function addWikiTextTidy( $text, $linestart = true ) {
1744 $title = $this->getTitle();
1745 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1749 * Add wikitext with a custom Title object
1751 * @param string $text Wikitext
1752 * @param Title $title
1753 * @param bool $linestart Is this the start of a line?
1754 * @param bool $tidy Whether to use tidy
1755 * @param bool $interface Whether it is an interface message
1756 * (for example disables conversion)
1758 public function addWikiTextTitle( $text, Title $title, $linestart,
1759 $tidy = false, $interface = false
1761 global $wgParser;
1763 $popts = $this->parserOptions();
1764 $oldTidy = $popts->setTidy( $tidy );
1765 $popts->setInterfaceMessage( (bool)$interface );
1767 $parserOutput = $wgParser->getFreshParser()->parse(
1768 $text, $title, $popts,
1769 $linestart, true, $this->mRevisionId
1772 $popts->setTidy( $oldTidy );
1774 $this->addParserOutput( $parserOutput );
1778 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1779 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1780 * and so on.
1782 * @since 1.24
1783 * @param ParserOutput $parserOutput
1785 public function addParserOutputMetadata( $parserOutput ) {
1786 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1787 $this->addCategoryLinks( $parserOutput->getCategories() );
1788 $this->setIndicators( $parserOutput->getIndicators() );
1789 $this->mNewSectionLink = $parserOutput->getNewSection();
1790 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1792 if ( !$parserOutput->isCacheable() ) {
1793 $this->enableClientCache( false );
1795 $this->mNoGallery = $parserOutput->getNoGallery();
1796 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1797 $this->addModules( $parserOutput->getModules() );
1798 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1799 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1800 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1801 $this->mPreventClickjacking = $this->mPreventClickjacking
1802 || $parserOutput->preventClickjacking();
1804 // Template versioning...
1805 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1806 if ( isset( $this->mTemplateIds[$ns] ) ) {
1807 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1808 } else {
1809 $this->mTemplateIds[$ns] = $dbks;
1812 // File versioning...
1813 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1814 $this->mImageTimeKeys[$dbk] = $data;
1817 // Hooks registered in the object
1818 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1819 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1820 list( $hookName, $data ) = $hookInfo;
1821 if ( isset( $parserOutputHooks[$hookName] ) ) {
1822 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1826 // Enable OOUI if requested via ParserOutput
1827 if ( $parserOutput->getEnableOOUI() ) {
1828 $this->enableOOUI();
1831 // Include parser limit report
1832 if ( !$this->limitReportJSData ) {
1833 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1836 // Link flags are ignored for now, but may in the future be
1837 // used to mark individual language links.
1838 $linkFlags = [];
1839 // Avoid PHP 7.1 warning of passing $this by reference
1840 $outputPage = $this;
1841 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1842 Hooks::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1844 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1845 // so that extensions may modify ParserOutput to toggle TOC.
1846 // This cannot be moved to addParserOutputText because that is not
1847 // called by EditPage for Preview.
1848 if ( $parserOutput->getTOCEnabled() && $parserOutput->getTOCHTML() ) {
1849 $this->mEnableTOC = true;
1854 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1855 * ParserOutput object, without any other metadata.
1857 * @since 1.24
1858 * @param ParserOutput $parserOutput
1860 public function addParserOutputContent( $parserOutput ) {
1861 $this->addParserOutputText( $parserOutput );
1863 $this->addModules( $parserOutput->getModules() );
1864 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1865 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1867 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1871 * Add the HTML associated with a ParserOutput object, without any metadata.
1873 * @since 1.24
1874 * @param ParserOutput $parserOutput
1876 public function addParserOutputText( $parserOutput ) {
1877 $text = $parserOutput->getText();
1878 // Avoid PHP 7.1 warning of passing $this by reference
1879 $outputPage = $this;
1880 Hooks::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1881 $this->addHTML( $text );
1885 * Add everything from a ParserOutput object.
1887 * @param ParserOutput $parserOutput
1889 function addParserOutput( $parserOutput ) {
1890 $this->addParserOutputMetadata( $parserOutput );
1892 // Touch section edit links only if not previously disabled
1893 if ( $parserOutput->getEditSectionTokens() ) {
1894 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1897 $this->addParserOutputText( $parserOutput );
1901 * Add the output of a QuickTemplate to the output buffer
1903 * @param QuickTemplate &$template
1905 public function addTemplate( &$template ) {
1906 $this->addHTML( $template->getHTML() );
1910 * Parse wikitext and return the HTML.
1912 * @param string $text
1913 * @param bool $linestart Is this the start of a line?
1914 * @param bool $interface Use interface language ($wgLang instead of
1915 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1916 * This also disables LanguageConverter.
1917 * @param Language $language Target language object, will override $interface
1918 * @throws MWException
1919 * @return string HTML
1921 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1922 global $wgParser;
1924 if ( is_null( $this->getTitle() ) ) {
1925 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1928 $popts = $this->parserOptions();
1929 if ( $interface ) {
1930 $popts->setInterfaceMessage( true );
1932 if ( $language !== null ) {
1933 $oldLang = $popts->setTargetLanguage( $language );
1936 $parserOutput = $wgParser->getFreshParser()->parse(
1937 $text, $this->getTitle(), $popts,
1938 $linestart, true, $this->mRevisionId
1941 if ( $interface ) {
1942 $popts->setInterfaceMessage( false );
1944 if ( $language !== null ) {
1945 $popts->setTargetLanguage( $oldLang );
1948 return $parserOutput->getText();
1952 * Parse wikitext, strip paragraphs, and return the HTML.
1954 * @param string $text
1955 * @param bool $linestart Is this the start of a line?
1956 * @param bool $interface Use interface language ($wgLang instead of
1957 * $wgContLang) while parsing language sensitive magic
1958 * words like GRAMMAR and PLURAL
1959 * @return string HTML
1961 public function parseInline( $text, $linestart = true, $interface = false ) {
1962 $parsed = $this->parse( $text, $linestart, $interface );
1963 return Parser::stripOuterParagraph( $parsed );
1967 * @param int $maxage
1968 * @deprecated since 1.27 Use setCdnMaxage() instead
1970 public function setSquidMaxage( $maxage ) {
1971 $this->setCdnMaxage( $maxage );
1975 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1977 * @param int $maxage Maximum cache time on the CDN, in seconds.
1979 public function setCdnMaxage( $maxage ) {
1980 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1984 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1986 * @param int $maxage Maximum cache time on the CDN, in seconds
1987 * @since 1.27
1989 public function lowerCdnMaxage( $maxage ) {
1990 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1991 $this->setCdnMaxage( $this->mCdnMaxage );
1995 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1997 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1998 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1999 * TTL is 90% of the age of the object, subject to the min and max.
2001 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
2002 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
2003 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2004 * @return integer TTL in seconds
2005 * @since 1.28
2007 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2008 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2009 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
2011 if ( $mtime === null || $mtime === false ) {
2012 return $minTTL; // entity does not exist
2015 $age = time() - wfTimestamp( TS_UNIX, $mtime );
2016 $adaptiveTTL = max( .9 * $age, $minTTL );
2017 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2019 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2021 return $adaptiveTTL;
2025 * Use enableClientCache(false) to force it to send nocache headers
2027 * @param bool $state
2029 * @return bool
2031 public function enableClientCache( $state ) {
2032 return wfSetVar( $this->mEnableClientCache, $state );
2036 * Get the list of cookies that will influence on the cache
2038 * @return array
2040 function getCacheVaryCookies() {
2041 static $cookies;
2042 if ( $cookies === null ) {
2043 $config = $this->getConfig();
2044 $cookies = array_merge(
2045 SessionManager::singleton()->getVaryCookies(),
2047 'forceHTTPS',
2049 $config->get( 'CacheVaryCookies' )
2051 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2053 return $cookies;
2057 * Check if the request has a cache-varying cookie header
2058 * If it does, it's very important that we don't allow public caching
2060 * @return bool
2062 function haveCacheVaryCookies() {
2063 $request = $this->getRequest();
2064 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2065 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2066 wfDebug( __METHOD__ . ": found $cookieName\n" );
2067 return true;
2070 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2071 return false;
2075 * Add an HTTP header that will influence on the cache
2077 * @param string $header Header name
2078 * @param string[]|null $option Options for the Key header. See
2079 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2080 * for the list of valid options.
2082 public function addVaryHeader( $header, array $option = null ) {
2083 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2084 $this->mVaryHeader[$header] = [];
2086 if ( !is_array( $option ) ) {
2087 $option = [];
2089 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2093 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2094 * such as Accept-Encoding or Cookie
2096 * @return string
2098 public function getVaryHeader() {
2099 // If we vary on cookies, let's make sure it's always included here too.
2100 if ( $this->getCacheVaryCookies() ) {
2101 $this->addVaryHeader( 'Cookie' );
2104 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2105 $this->addVaryHeader( $header, $options );
2107 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2111 * Add an HTTP Link: header
2113 * @param string $header Header value
2115 public function addLinkHeader( $header ) {
2116 $this->mLinkHeader[] = $header;
2120 * Return a Link: header. Based on the values of $mLinkHeader.
2122 * @return string
2124 public function getLinkHeader() {
2125 if ( !$this->mLinkHeader ) {
2126 return false;
2129 return 'Link: ' . implode( ',', $this->mLinkHeader );
2133 * Get a complete Key header
2135 * @return string
2137 public function getKeyHeader() {
2138 $cvCookies = $this->getCacheVaryCookies();
2140 $cookiesOption = [];
2141 foreach ( $cvCookies as $cookieName ) {
2142 $cookiesOption[] = 'param=' . $cookieName;
2144 $this->addVaryHeader( 'Cookie', $cookiesOption );
2146 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2147 $this->addVaryHeader( $header, $options );
2150 $headers = [];
2151 foreach ( $this->mVaryHeader as $header => $option ) {
2152 $newheader = $header;
2153 if ( is_array( $option ) && count( $option ) > 0 ) {
2154 $newheader .= ';' . implode( ';', $option );
2156 $headers[] = $newheader;
2158 $key = 'Key: ' . implode( ',', $headers );
2160 return $key;
2164 * T23672: Add Accept-Language to Vary and Key headers
2165 * if there's no 'variant' parameter existed in GET.
2167 * For example:
2168 * /w/index.php?title=Main_page should always be served; but
2169 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2171 function addAcceptLanguage() {
2172 $title = $this->getTitle();
2173 if ( !$title instanceof Title ) {
2174 return;
2177 $lang = $title->getPageLanguage();
2178 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2179 $variants = $lang->getVariants();
2180 $aloption = [];
2181 foreach ( $variants as $variant ) {
2182 if ( $variant === $lang->getCode() ) {
2183 continue;
2184 } else {
2185 $aloption[] = 'substr=' . $variant;
2187 // IE and some other browsers use BCP 47 standards in
2188 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2189 // We should handle these too.
2190 $variantBCP47 = wfBCP47( $variant );
2191 if ( $variantBCP47 !== $variant ) {
2192 $aloption[] = 'substr=' . $variantBCP47;
2196 $this->addVaryHeader( 'Accept-Language', $aloption );
2201 * Set a flag which will cause an X-Frame-Options header appropriate for
2202 * edit pages to be sent. The header value is controlled by
2203 * $wgEditPageFrameOptions.
2205 * This is the default for special pages. If you display a CSRF-protected
2206 * form on an ordinary view page, then you need to call this function.
2208 * @param bool $enable
2210 public function preventClickjacking( $enable = true ) {
2211 $this->mPreventClickjacking = $enable;
2215 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2216 * This can be called from pages which do not contain any CSRF-protected
2217 * HTML form.
2219 public function allowClickjacking() {
2220 $this->mPreventClickjacking = false;
2224 * Get the prevent-clickjacking flag
2226 * @since 1.24
2227 * @return bool
2229 public function getPreventClickjacking() {
2230 return $this->mPreventClickjacking;
2234 * Get the X-Frame-Options header value (without the name part), or false
2235 * if there isn't one. This is used by Skin to determine whether to enable
2236 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2238 * @return string|false
2240 public function getFrameOptions() {
2241 $config = $this->getConfig();
2242 if ( $config->get( 'BreakFrames' ) ) {
2243 return 'DENY';
2244 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2245 return $config->get( 'EditPageFrameOptions' );
2247 return false;
2251 * Send cache control HTTP headers
2253 public function sendCacheControl() {
2254 $response = $this->getRequest()->response();
2255 $config = $this->getConfig();
2257 $this->addVaryHeader( 'Cookie' );
2258 $this->addAcceptLanguage();
2260 # don't serve compressed data to clients who can't handle it
2261 # maintain different caches for logged-in users and non-logged in ones
2262 $response->header( $this->getVaryHeader() );
2264 if ( $config->get( 'UseKeyHeader' ) ) {
2265 $response->header( $this->getKeyHeader() );
2268 if ( $this->mEnableClientCache ) {
2269 if (
2270 $config->get( 'UseSquid' ) &&
2271 !$response->hasCookies() &&
2272 !SessionManager::getGlobalSession()->isPersistent() &&
2273 !$this->isPrintable() &&
2274 $this->mCdnMaxage != 0 &&
2275 !$this->haveCacheVaryCookies()
2277 if ( $config->get( 'UseESI' ) ) {
2278 # We'll purge the proxy cache explicitly, but require end user agents
2279 # to revalidate against the proxy on each visit.
2280 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2281 wfDebug( __METHOD__ .
2282 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2283 # start with a shorter timeout for initial testing
2284 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2285 $response->header(
2286 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2287 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2289 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2290 } else {
2291 # We'll purge the proxy cache for anons explicitly, but require end user agents
2292 # to revalidate against the proxy on each visit.
2293 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2294 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2295 wfDebug( __METHOD__ .
2296 ": local proxy caching; {$this->mLastModified} **", 'private' );
2297 # start with a shorter timeout for initial testing
2298 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2299 $response->header( "Cache-Control: " .
2300 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2302 } else {
2303 # We do want clients to cache if they can, but they *must* check for updates
2304 # on revisiting the page.
2305 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2306 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2307 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2309 if ( $this->mLastModified ) {
2310 $response->header( "Last-Modified: {$this->mLastModified}" );
2312 } else {
2313 wfDebug( __METHOD__ . ": no caching **", 'private' );
2315 # In general, the absence of a last modified header should be enough to prevent
2316 # the client from using its cache. We send a few other things just to make sure.
2317 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2318 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2319 $response->header( 'Pragma: no-cache' );
2324 * Finally, all the text has been munged and accumulated into
2325 * the object, let's actually output it:
2327 * @param bool $return Set to true to get the result as a string rather than sending it
2328 * @return string|null
2329 * @throws Exception
2330 * @throws FatalError
2331 * @throws MWException
2333 public function output( $return = false ) {
2334 global $wgContLang;
2336 if ( $this->mDoNothing ) {
2337 return $return ? '' : null;
2340 $response = $this->getRequest()->response();
2341 $config = $this->getConfig();
2343 if ( $this->mRedirect != '' ) {
2344 # Standards require redirect URLs to be absolute
2345 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2347 $redirect = $this->mRedirect;
2348 $code = $this->mRedirectCode;
2350 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2351 if ( $code == '301' || $code == '303' ) {
2352 if ( !$config->get( 'DebugRedirects' ) ) {
2353 $response->statusHeader( $code );
2355 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2357 if ( $config->get( 'VaryOnXFP' ) ) {
2358 $this->addVaryHeader( 'X-Forwarded-Proto' );
2360 $this->sendCacheControl();
2362 $response->header( "Content-Type: text/html; charset=utf-8" );
2363 if ( $config->get( 'DebugRedirects' ) ) {
2364 $url = htmlspecialchars( $redirect );
2365 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2366 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2367 print "</body>\n</html>\n";
2368 } else {
2369 $response->header( 'Location: ' . $redirect );
2373 return $return ? '' : null;
2374 } elseif ( $this->mStatusCode ) {
2375 $response->statusHeader( $this->mStatusCode );
2378 # Buffer output; final headers may depend on later processing
2379 ob_start();
2381 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2382 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2384 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2385 // jQuery etc. can work correctly.
2386 $response->header( 'X-UA-Compatible: IE=Edge' );
2388 if ( !$this->mArticleBodyOnly ) {
2389 $sk = $this->getSkin();
2391 if ( $sk->shouldPreloadLogo() ) {
2392 $this->addLogoPreloadLinkHeaders();
2396 $linkHeader = $this->getLinkHeader();
2397 if ( $linkHeader ) {
2398 $response->header( $linkHeader );
2401 // Prevent framing, if requested
2402 $frameOptions = $this->getFrameOptions();
2403 if ( $frameOptions ) {
2404 $response->header( "X-Frame-Options: $frameOptions" );
2407 if ( $this->mArticleBodyOnly ) {
2408 echo $this->mBodytext;
2409 } else {
2410 // Enable safe mode if requested
2411 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2412 $this->disallowUserJs();
2415 $sk = $this->getSkin();
2416 foreach ( $sk->getDefaultModules() as $group ) {
2417 $this->addModules( $group );
2420 MWDebug::addModules( $this );
2422 // Avoid PHP 7.1 warning of passing $this by reference
2423 $outputPage = $this;
2424 // Hook that allows last minute changes to the output page, e.g.
2425 // adding of CSS or Javascript by extensions.
2426 Hooks::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2428 try {
2429 $sk->outputPage();
2430 } catch ( Exception $e ) {
2431 ob_end_clean(); // bug T129657
2432 throw $e;
2436 try {
2437 // This hook allows last minute changes to final overall output by modifying output buffer
2438 Hooks::run( 'AfterFinalPageOutput', [ $this ] );
2439 } catch ( Exception $e ) {
2440 ob_end_clean(); // bug T129657
2441 throw $e;
2444 $this->sendCacheControl();
2446 if ( $return ) {
2447 return ob_get_clean();
2448 } else {
2449 ob_end_flush();
2450 return null;
2455 * Prepare this object to display an error page; disable caching and
2456 * indexing, clear the current text and redirect, set the page's title
2457 * and optionally an custom HTML title (content of the "<title>" tag).
2459 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2460 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2461 * optional, if not passed the "<title>" attribute will be
2462 * based on $pageTitle
2464 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2465 $this->setPageTitle( $pageTitle );
2466 if ( $htmlTitle !== false ) {
2467 $this->setHTMLTitle( $htmlTitle );
2469 $this->setRobotPolicy( 'noindex,nofollow' );
2470 $this->setArticleRelated( false );
2471 $this->enableClientCache( false );
2472 $this->mRedirect = '';
2473 $this->clearSubtitle();
2474 $this->clearHTML();
2478 * Output a standard error page
2480 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2481 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2482 * showErrorPage( 'titlemsg', $messageObject );
2483 * showErrorPage( $titleMessageObject, $messageObject );
2485 * @param string|Message $title Message key (string) for page title, or a Message object
2486 * @param string|Message $msg Message key (string) for page text, or a Message object
2487 * @param array $params Message parameters; ignored if $msg is a Message object
2489 public function showErrorPage( $title, $msg, $params = [] ) {
2490 if ( !$title instanceof Message ) {
2491 $title = $this->msg( $title );
2494 $this->prepareErrorPage( $title );
2496 if ( $msg instanceof Message ) {
2497 if ( $params !== [] ) {
2498 trigger_error( 'Argument ignored: $params. The message parameters argument '
2499 . 'is discarded when the $msg argument is a Message object instead of '
2500 . 'a string.', E_USER_NOTICE );
2502 $this->addHTML( $msg->parseAsBlock() );
2503 } else {
2504 $this->addWikiMsgArray( $msg, $params );
2507 $this->returnToMain();
2511 * Output a standard permission error page
2513 * @param array $errors Error message keys or [key, param...] arrays
2514 * @param string $action Action that was denied or null if unknown
2516 public function showPermissionsErrorPage( array $errors, $action = null ) {
2517 foreach ( $errors as $key => $error ) {
2518 $errors[$key] = (array)$error;
2521 // For some action (read, edit, create and upload), display a "login to do this action"
2522 // error if all of the following conditions are met:
2523 // 1. the user is not logged in
2524 // 2. the only error is insufficient permissions (i.e. no block or something else)
2525 // 3. the error can be avoided simply by logging in
2526 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2527 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2528 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2529 && ( User::groupHasPermission( 'user', $action )
2530 || User::groupHasPermission( 'autoconfirmed', $action ) )
2532 $displayReturnto = null;
2534 # Due to T34276, if a user does not have read permissions,
2535 # $this->getTitle() will just give Special:Badtitle, which is
2536 # not especially useful as a returnto parameter. Use the title
2537 # from the request instead, if there was one.
2538 $request = $this->getRequest();
2539 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2540 if ( $action == 'edit' ) {
2541 $msg = 'whitelistedittext';
2542 $displayReturnto = $returnto;
2543 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2544 $msg = 'nocreatetext';
2545 } elseif ( $action == 'upload' ) {
2546 $msg = 'uploadnologintext';
2547 } else { # Read
2548 $msg = 'loginreqpagetext';
2549 $displayReturnto = Title::newMainPage();
2552 $query = [];
2554 if ( $returnto ) {
2555 $query['returnto'] = $returnto->getPrefixedText();
2557 if ( !$request->wasPosted() ) {
2558 $returntoquery = $request->getValues();
2559 unset( $returntoquery['title'] );
2560 unset( $returntoquery['returnto'] );
2561 unset( $returntoquery['returntoquery'] );
2562 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2565 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2566 $loginLink = $linkRenderer->makeKnownLink(
2567 SpecialPage::getTitleFor( 'Userlogin' ),
2568 $this->msg( 'loginreqlink' )->text(),
2570 $query
2573 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2574 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2576 # Don't return to a page the user can't read otherwise
2577 # we'll end up in a pointless loop
2578 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2579 $this->returnToMain( null, $displayReturnto );
2581 } else {
2582 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2583 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2588 * Display an error page indicating that a given version of MediaWiki is
2589 * required to use it
2591 * @param mixed $version The version of MediaWiki needed to use the page
2593 public function versionRequired( $version ) {
2594 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2596 $this->addWikiMsg( 'versionrequiredtext', $version );
2597 $this->returnToMain();
2601 * Format a list of error messages
2603 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2604 * @param string $action Action that was denied or null if unknown
2605 * @return string The wikitext error-messages, formatted into a list.
2607 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2608 if ( $action == null ) {
2609 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2610 } else {
2611 $action_desc = $this->msg( "action-$action" )->plain();
2612 $text = $this->msg(
2613 'permissionserrorstext-withaction',
2614 count( $errors ),
2615 $action_desc
2616 )->plain() . "\n\n";
2619 if ( count( $errors ) > 1 ) {
2620 $text .= '<ul class="permissions-errors">' . "\n";
2622 foreach ( $errors as $error ) {
2623 $text .= '<li>';
2624 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2625 $text .= "</li>\n";
2627 $text .= '</ul>';
2628 } else {
2629 $text .= "<div class=\"permissions-errors\">\n" .
2630 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2631 "\n</div>";
2634 return $text;
2638 * Display a page stating that the Wiki is in read-only mode.
2639 * Should only be called after wfReadOnly() has returned true.
2641 * Historically, this function was used to show the source of the page that the user
2642 * was trying to edit and _also_ permissions error messages. The relevant code was
2643 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2645 * @deprecated since 1.25; throw the exception directly
2646 * @throws ReadOnlyError
2648 public function readOnlyPage() {
2649 if ( func_num_args() > 0 ) {
2650 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2653 throw new ReadOnlyError;
2657 * Turn off regular page output and return an error response
2658 * for when rate limiting has triggered.
2660 * @deprecated since 1.25; throw the exception directly
2662 public function rateLimited() {
2663 wfDeprecated( __METHOD__, '1.25' );
2664 throw new ThrottledError;
2668 * Show a warning about replica DB lag
2670 * If the lag is higher than $wgSlaveLagCritical seconds,
2671 * then the warning is a bit more obvious. If the lag is
2672 * lower than $wgSlaveLagWarning, then no warning is shown.
2674 * @param int $lag Slave lag
2676 public function showLagWarning( $lag ) {
2677 $config = $this->getConfig();
2678 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2679 $lag = floor( $lag ); // floor to avoid nano seconds to display
2680 $message = $lag < $config->get( 'SlaveLagCritical' )
2681 ? 'lag-warn-normal'
2682 : 'lag-warn-high';
2683 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2684 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2688 public function showFatalError( $message ) {
2689 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2691 $this->addHTML( $message );
2694 public function showUnexpectedValueError( $name, $val ) {
2695 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2698 public function showFileCopyError( $old, $new ) {
2699 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2702 public function showFileRenameError( $old, $new ) {
2703 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2706 public function showFileDeleteError( $name ) {
2707 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2710 public function showFileNotFoundError( $name ) {
2711 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2715 * Add a "return to" link pointing to a specified title
2717 * @param Title $title Title to link
2718 * @param array $query Query string parameters
2719 * @param string $text Text of the link (input is not escaped)
2720 * @param array $options Options array to pass to Linker
2722 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2723 $linkRenderer = MediaWikiServices::getInstance()
2724 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2725 $link = $this->msg( 'returnto' )->rawParams(
2726 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2727 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2731 * Add a "return to" link pointing to a specified title,
2732 * or the title indicated in the request, or else the main page
2734 * @param mixed $unused
2735 * @param Title|string $returnto Title or String to return to
2736 * @param string $returntoquery Query string for the return to link
2738 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2739 if ( $returnto == null ) {
2740 $returnto = $this->getRequest()->getText( 'returnto' );
2743 if ( $returntoquery == null ) {
2744 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2747 if ( $returnto === '' ) {
2748 $returnto = Title::newMainPage();
2751 if ( is_object( $returnto ) ) {
2752 $titleObj = $returnto;
2753 } else {
2754 $titleObj = Title::newFromText( $returnto );
2756 // We don't want people to return to external interwiki. That
2757 // might potentially be used as part of a phishing scheme
2758 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2759 $titleObj = Title::newMainPage();
2762 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2765 private function getRlClientContext() {
2766 if ( !$this->rlClientContext ) {
2767 $query = ResourceLoader::makeLoaderQuery(
2768 [], // modules; not relevant
2769 $this->getLanguage()->getCode(),
2770 $this->getSkin()->getSkinName(),
2771 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2772 null, // version; not relevant
2773 ResourceLoader::inDebugMode(),
2774 null, // only; not relevant
2775 $this->isPrintable(),
2776 $this->getRequest()->getBool( 'handheld' )
2778 $this->rlClientContext = new ResourceLoaderContext(
2779 $this->getResourceLoader(),
2780 new FauxRequest( $query )
2783 return $this->rlClientContext;
2787 * Call this to freeze the module queue and JS config and create a formatter.
2789 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2790 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2791 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2792 * the module filters retroactively. Skins and extension hooks may also add modules until very
2793 * late in the request lifecycle.
2795 * @return ResourceLoaderClientHtml
2797 public function getRlClient() {
2798 if ( !$this->rlClient ) {
2799 $context = $this->getRlClientContext();
2800 $rl = $this->getResourceLoader();
2801 $this->addModules( [
2802 'user.options',
2803 'user.tokens',
2804 ] );
2805 $this->addModuleStyles( [
2806 'site.styles',
2807 'noscript',
2808 'user.styles',
2809 ] );
2810 $this->getSkin()->setupSkinUserCss( $this );
2812 // Prepare exempt modules for buildExemptModules()
2813 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2814 $exemptStates = [];
2815 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2817 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2818 // Separate user-specific batch for improved cache-hit ratio.
2819 $userBatch = [ 'user.styles', 'user' ];
2820 $siteBatch = array_diff( $moduleStyles, $userBatch );
2821 $dbr = wfGetDB( DB_REPLICA );
2822 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2823 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2825 // Filter out modules handled by buildExemptModules()
2826 $moduleStyles = array_filter( $moduleStyles,
2827 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2828 $module = $rl->getModule( $name );
2829 if ( $module ) {
2830 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2831 $exemptStates[$name] = 'ready';
2832 // Special case in buildExemptModules()
2833 return false;
2835 $group = $module->getGroup();
2836 if ( isset( $exemptGroups[$group] ) ) {
2837 $exemptStates[$name] = 'ready';
2838 if ( !$module->isKnownEmpty( $context ) ) {
2839 // E.g. Don't output empty <styles>
2840 $exemptGroups[$group][] = $name;
2842 return false;
2845 return true;
2848 $this->rlExemptStyleModules = $exemptGroups;
2850 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2851 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2852 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2853 if ( !$isUserModuleFiltered ) {
2854 // Manually handled by getBottomScripts()
2855 $userModule = $rl->getModule( 'user' );
2856 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2857 ? 'ready'
2858 : 'loading';
2859 $this->rlUserModuleState = $exemptStates['user'] = $userState;
2862 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2863 $rlClient->setConfig( $this->getJSVars() );
2864 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2865 $rlClient->setModuleStyles( $moduleStyles );
2866 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2867 $rlClient->setExemptStates( $exemptStates );
2868 $this->rlClient = $rlClient;
2870 return $this->rlClient;
2874 * @param Skin $sk The given Skin
2875 * @param bool $includeStyle Unused
2876 * @return string The doctype, opening "<html>", and head element.
2878 public function headElement( Skin $sk, $includeStyle = true ) {
2879 global $wgContLang;
2881 $userdir = $this->getLanguage()->getDir();
2882 $sitedir = $wgContLang->getDir();
2884 $pieces = [];
2885 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2886 $this->getRlClient()->getDocumentAttributes(),
2887 $sk->getHtmlElementAttributes()
2888 ) );
2889 $pieces[] = Html::openElement( 'head' );
2891 if ( $this->getHTMLTitle() == '' ) {
2892 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2895 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2896 // Add <meta charset="UTF-8">
2897 // This should be before <title> since it defines the charset used by
2898 // text including the text inside <title>.
2899 // The spec recommends defining XHTML5's charset using the XML declaration
2900 // instead of meta.
2901 // Our XML declaration is output by Html::htmlHeader.
2902 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2903 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2904 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2907 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2908 $pieces[] = $this->getRlClient()->getHeadHtml();
2909 $pieces[] = $this->buildExemptModules();
2910 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2911 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2913 $min = ResourceLoader::inDebugMode() ? '' : '.min';
2914 // Use an IE conditional comment to serve the script only to old IE
2915 $pieces[] = '<!--[if lt IE 9]>' .
2916 Html::element( 'script', [
2917 'src' => self::transformResourcePath(
2918 $this->getConfig(),
2919 "/resources/lib/html5shiv/html5shiv{$min}.js"
2921 ] ) .
2922 '<![endif]-->';
2924 $pieces[] = Html::closeElement( 'head' );
2926 $bodyClasses = [];
2927 $bodyClasses[] = 'mediawiki';
2929 # Classes for LTR/RTL directionality support
2930 $bodyClasses[] = $userdir;
2931 $bodyClasses[] = "sitedir-$sitedir";
2933 $underline = $this->getUser()->getOption( 'underline' );
2934 if ( $underline < 2 ) {
2935 // The following classes can be used here:
2936 // * mw-underline-always
2937 // * mw-underline-never
2938 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2941 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2942 # A <body> class is probably not the best way to do this . . .
2943 $bodyClasses[] = 'capitalize-all-nouns';
2946 // Parser feature migration class
2947 // The idea is that this will eventually be removed, after the wikitext
2948 // which requires it is cleaned up.
2949 $bodyClasses[] = 'mw-hide-empty-elt';
2951 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2952 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2953 $bodyClasses[] =
2954 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2956 $bodyAttrs = [];
2957 // While the implode() is not strictly needed, it's used for backwards compatibility
2958 // (this used to be built as a string and hooks likely still expect that).
2959 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2961 // Allow skins and extensions to add body attributes they need
2962 $sk->addToBodyAttributes( $this, $bodyAttrs );
2963 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2965 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2967 return self::combineWrappedStrings( $pieces );
2971 * Get a ResourceLoader object associated with this OutputPage
2973 * @return ResourceLoader
2975 public function getResourceLoader() {
2976 if ( is_null( $this->mResourceLoader ) ) {
2977 $this->mResourceLoader = new ResourceLoader(
2978 $this->getConfig(),
2979 LoggerFactory::getInstance( 'resourceloader' )
2982 return $this->mResourceLoader;
2986 * Explicily load or embed modules on a page.
2988 * @param array|string $modules One or more module names
2989 * @param string $only ResourceLoaderModule TYPE_ class constant
2990 * @param array $extraQuery [optional] Array with extra query parameters for the request
2991 * @return string|WrappedStringList HTML
2993 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2994 // Apply 'target' and 'origin' filters
2995 $modules = $this->filterModules( (array)$modules, null, $only );
2997 return ResourceLoaderClientHtml::makeLoad(
2998 $this->getRlClientContext(),
2999 $modules,
3000 $only,
3001 $extraQuery
3006 * Combine WrappedString chunks and filter out empty ones
3008 * @param array $chunks
3009 * @return string|WrappedStringList HTML
3011 protected static function combineWrappedStrings( array $chunks ) {
3012 // Filter out empty values
3013 $chunks = array_filter( $chunks, 'strlen' );
3014 return WrappedString::join( "\n", $chunks );
3017 private function isUserJsPreview() {
3018 return $this->getConfig()->get( 'AllowUserJs' )
3019 && $this->getTitle()
3020 && $this->getTitle()->isJsSubpage()
3021 && $this->userCanPreview();
3024 protected function isUserCssPreview() {
3025 return $this->getConfig()->get( 'AllowUserCss' )
3026 && $this->getTitle()
3027 && $this->getTitle()->isCssSubpage()
3028 && $this->userCanPreview();
3032 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
3033 * legacy scripts ($this->mScripts), and user JS.
3035 * @return string|WrappedStringList HTML
3037 public function getBottomScripts() {
3038 $chunks = [];
3039 $chunks[] = $this->getRlClient()->getBodyHtml();
3041 // Legacy non-ResourceLoader scripts
3042 $chunks[] = $this->mScripts;
3044 // Exempt 'user' module
3045 // - May need excludepages for live preview. (T28283)
3046 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3047 // ensures execution is scheduled after the "site" module.
3048 // - Don't load if module state is already resolved as "ready".
3049 if ( $this->rlUserModuleState === 'loading' ) {
3050 if ( $this->isUserJsPreview() ) {
3051 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3052 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3054 $chunks[] = ResourceLoader::makeInlineScript(
3055 Xml::encodeJsCall( 'mw.loader.using', [
3056 [ 'user', 'site' ],
3057 new XmlJsCode(
3058 'function () {'
3059 . Xml::encodeJsCall( '$.globalEval', [
3060 $this->getRequest()->getText( 'wpTextbox1' )
3062 . '}'
3066 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3067 // asynchronously and may arrive *after* the inline script here. So the previewed code
3068 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3069 // Similarly, when previewing ./common.js and the user module does arrive first,
3070 // it will arrive without common.js and the inline script runs after.
3071 // Thus running common after the excluded subpage.
3072 } else {
3073 // Load normally
3074 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3078 if ( $this->limitReportJSData ) {
3079 $chunks[] = ResourceLoader::makeInlineScript(
3080 ResourceLoader::makeConfigSetScript(
3081 [ 'wgPageParseReport' => $this->limitReportJSData ]
3086 return self::combineWrappedStrings( $chunks );
3090 * Get the javascript config vars to include on this page
3092 * @return array Array of javascript config vars
3093 * @since 1.23
3095 public function getJsConfigVars() {
3096 return $this->mJsConfigVars;
3100 * Add one or more variables to be set in mw.config in JavaScript
3102 * @param string|array $keys Key or array of key/value pairs
3103 * @param mixed $value [optional] Value of the configuration variable
3105 public function addJsConfigVars( $keys, $value = null ) {
3106 if ( is_array( $keys ) ) {
3107 foreach ( $keys as $key => $value ) {
3108 $this->mJsConfigVars[$key] = $value;
3110 return;
3113 $this->mJsConfigVars[$keys] = $value;
3117 * Get an array containing the variables to be set in mw.config in JavaScript.
3119 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3120 * - in other words, page-independent/site-wide variables (without state).
3121 * You will only be adding bloat to the html page and causing page caches to
3122 * have to be purged on configuration changes.
3123 * @return array
3125 public function getJSVars() {
3126 global $wgContLang;
3128 $curRevisionId = 0;
3129 $articleId = 0;
3130 $canonicalSpecialPageName = false; # T23115
3132 $title = $this->getTitle();
3133 $ns = $title->getNamespace();
3134 $canonicalNamespace = MWNamespace::exists( $ns )
3135 ? MWNamespace::getCanonicalName( $ns )
3136 : $title->getNsText();
3138 $sk = $this->getSkin();
3139 // Get the relevant title so that AJAX features can use the correct page name
3140 // when making API requests from certain special pages (T36972).
3141 $relevantTitle = $sk->getRelevantTitle();
3142 $relevantUser = $sk->getRelevantUser();
3144 if ( $ns == NS_SPECIAL ) {
3145 list( $canonicalSpecialPageName, /*...*/ ) =
3146 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3147 } elseif ( $this->canUseWikiPage() ) {
3148 $wikiPage = $this->getWikiPage();
3149 $curRevisionId = $wikiPage->getLatest();
3150 $articleId = $wikiPage->getId();
3153 $lang = $title->getPageViewLanguage();
3155 // Pre-process information
3156 $separatorTransTable = $lang->separatorTransformTable();
3157 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3158 $compactSeparatorTransTable = [
3159 implode( "\t", array_keys( $separatorTransTable ) ),
3160 implode( "\t", $separatorTransTable ),
3162 $digitTransTable = $lang->digitTransformTable();
3163 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3164 $compactDigitTransTable = [
3165 implode( "\t", array_keys( $digitTransTable ) ),
3166 implode( "\t", $digitTransTable ),
3169 $user = $this->getUser();
3171 $vars = [
3172 'wgCanonicalNamespace' => $canonicalNamespace,
3173 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3174 'wgNamespaceNumber' => $title->getNamespace(),
3175 'wgPageName' => $title->getPrefixedDBkey(),
3176 'wgTitle' => $title->getText(),
3177 'wgCurRevisionId' => $curRevisionId,
3178 'wgRevisionId' => (int)$this->getRevisionId(),
3179 'wgArticleId' => $articleId,
3180 'wgIsArticle' => $this->isArticle(),
3181 'wgIsRedirect' => $title->isRedirect(),
3182 'wgAction' => Action::getActionName( $this->getContext() ),
3183 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3184 'wgUserGroups' => $user->getEffectiveGroups(),
3185 'wgCategories' => $this->getCategories(),
3186 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3187 'wgPageContentLanguage' => $lang->getCode(),
3188 'wgPageContentModel' => $title->getContentModel(),
3189 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3190 'wgDigitTransformTable' => $compactDigitTransTable,
3191 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3192 'wgMonthNames' => $lang->getMonthNamesArray(),
3193 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3194 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3195 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3196 'wgRequestId' => WebRequest::getRequestId(),
3199 if ( $user->isLoggedIn() ) {
3200 $vars['wgUserId'] = $user->getId();
3201 $vars['wgUserEditCount'] = $user->getEditCount();
3202 $userReg = $user->getRegistration();
3203 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3204 // Get the revision ID of the oldest new message on the user's talk
3205 // page. This can be used for constructing new message alerts on
3206 // the client side.
3207 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3210 if ( $wgContLang->hasVariants() ) {
3211 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3213 // Same test as SkinTemplate
3214 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3215 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3217 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3218 && $relevantTitle->quickUserCan( 'edit', $user )
3219 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3221 foreach ( $title->getRestrictionTypes() as $type ) {
3222 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3225 if ( $title->isMainPage() ) {
3226 $vars['wgIsMainPage'] = true;
3229 if ( $this->mRedirectedFrom ) {
3230 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3233 if ( $relevantUser ) {
3234 $vars['wgRelevantUserName'] = $relevantUser->getName();
3237 // Allow extensions to add their custom variables to the mw.config map.
3238 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3239 // page-dependant but site-wide (without state).
3240 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3241 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3243 // Merge in variables from addJsConfigVars last
3244 return array_merge( $vars, $this->getJsConfigVars() );
3248 * To make it harder for someone to slip a user a fake
3249 * user-JavaScript or user-CSS preview, a random token
3250 * is associated with the login session. If it's not
3251 * passed back with the preview request, we won't render
3252 * the code.
3254 * @return bool
3256 public function userCanPreview() {
3257 $request = $this->getRequest();
3258 if (
3259 $request->getVal( 'action' ) !== 'submit' ||
3260 !$request->getCheck( 'wpPreview' ) ||
3261 !$request->wasPosted()
3263 return false;
3266 $user = $this->getUser();
3268 if ( !$user->isLoggedIn() ) {
3269 // Anons have predictable edit tokens
3270 return false;
3272 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3273 return false;
3276 $title = $this->getTitle();
3277 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3278 return false;
3280 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3281 // Don't execute another user's CSS or JS on preview (T85855)
3282 return false;
3285 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3286 if ( count( $errors ) !== 0 ) {
3287 return false;
3290 return true;
3294 * @return array Array in format "link name or number => 'link html'".
3296 public function getHeadLinksArray() {
3297 global $wgVersion;
3299 $tags = [];
3300 $config = $this->getConfig();
3302 $canonicalUrl = $this->mCanonicalUrl;
3304 $tags['meta-generator'] = Html::element( 'meta', [
3305 'name' => 'generator',
3306 'content' => "MediaWiki $wgVersion",
3307 ] );
3309 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3310 $tags['meta-referrer'] = Html::element( 'meta', [
3311 'name' => 'referrer',
3312 'content' => $config->get( 'ReferrerPolicy' )
3313 ] );
3316 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3317 if ( $p !== 'index,follow' ) {
3318 // http://www.robotstxt.org/wc/meta-user.html
3319 // Only show if it's different from the default robots policy
3320 $tags['meta-robots'] = Html::element( 'meta', [
3321 'name' => 'robots',
3322 'content' => $p,
3323 ] );
3326 foreach ( $this->mMetatags as $tag ) {
3327 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3328 $a = 'http-equiv';
3329 $tag[0] = substr( $tag[0], 5 );
3330 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3331 $a = 'property';
3332 } else {
3333 $a = 'name';
3335 $tagName = "meta-{$tag[0]}";
3336 if ( isset( $tags[$tagName] ) ) {
3337 $tagName .= $tag[1];
3339 $tags[$tagName] = Html::element( 'meta',
3341 $a => $tag[0],
3342 'content' => $tag[1]
3347 foreach ( $this->mLinktags as $tag ) {
3348 $tags[] = Html::element( 'link', $tag );
3351 # Universal edit button
3352 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3353 $user = $this->getUser();
3354 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3355 && ( $this->getTitle()->exists() ||
3356 $this->getTitle()->quickUserCan( 'create', $user ) )
3358 // Original UniversalEditButton
3359 $msg = $this->msg( 'edit' )->text();
3360 $tags['universal-edit-button'] = Html::element( 'link', [
3361 'rel' => 'alternate',
3362 'type' => 'application/x-wiki',
3363 'title' => $msg,
3364 'href' => $this->getTitle()->getEditURL(),
3365 ] );
3366 // Alternate edit link
3367 $tags['alternative-edit'] = Html::element( 'link', [
3368 'rel' => 'edit',
3369 'title' => $msg,
3370 'href' => $this->getTitle()->getEditURL(),
3371 ] );
3375 # Generally the order of the favicon and apple-touch-icon links
3376 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3377 # uses whichever one appears later in the HTML source. Make sure
3378 # apple-touch-icon is specified first to avoid this.
3379 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3380 $tags['apple-touch-icon'] = Html::element( 'link', [
3381 'rel' => 'apple-touch-icon',
3382 'href' => $config->get( 'AppleTouchIcon' )
3383 ] );
3386 if ( $config->get( 'Favicon' ) !== false ) {
3387 $tags['favicon'] = Html::element( 'link', [
3388 'rel' => 'shortcut icon',
3389 'href' => $config->get( 'Favicon' )
3390 ] );
3393 # OpenSearch description link
3394 $tags['opensearch'] = Html::element( 'link', [
3395 'rel' => 'search',
3396 'type' => 'application/opensearchdescription+xml',
3397 'href' => wfScript( 'opensearch_desc' ),
3398 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3399 ] );
3401 if ( $config->get( 'EnableAPI' ) ) {
3402 # Real Simple Discovery link, provides auto-discovery information
3403 # for the MediaWiki API (and potentially additional custom API
3404 # support such as WordPress or Twitter-compatible APIs for a
3405 # blogging extension, etc)
3406 $tags['rsd'] = Html::element( 'link', [
3407 'rel' => 'EditURI',
3408 'type' => 'application/rsd+xml',
3409 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3410 // Whether RSD accepts relative or protocol-relative URLs is completely
3411 // undocumented, though.
3412 'href' => wfExpandUrl( wfAppendQuery(
3413 wfScript( 'api' ),
3414 [ 'action' => 'rsd' ] ),
3415 PROTO_RELATIVE
3417 ] );
3420 # Language variants
3421 if ( !$config->get( 'DisableLangConversion' ) ) {
3422 $lang = $this->getTitle()->getPageLanguage();
3423 if ( $lang->hasVariants() ) {
3424 $variants = $lang->getVariants();
3425 foreach ( $variants as $variant ) {
3426 $tags["variant-$variant"] = Html::element( 'link', [
3427 'rel' => 'alternate',
3428 'hreflang' => wfBCP47( $variant ),
3429 'href' => $this->getTitle()->getLocalURL(
3430 [ 'variant' => $variant ] )
3434 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3435 $tags["variant-x-default"] = Html::element( 'link', [
3436 'rel' => 'alternate',
3437 'hreflang' => 'x-default',
3438 'href' => $this->getTitle()->getLocalURL() ] );
3442 # Copyright
3443 if ( $this->copyrightUrl !== null ) {
3444 $copyright = $this->copyrightUrl;
3445 } else {
3446 $copyright = '';
3447 if ( $config->get( 'RightsPage' ) ) {
3448 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3450 if ( $copy ) {
3451 $copyright = $copy->getLocalURL();
3455 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3456 $copyright = $config->get( 'RightsUrl' );
3460 if ( $copyright ) {
3461 $tags['copyright'] = Html::element( 'link', [
3462 'rel' => 'license',
3463 'href' => $copyright ]
3467 # Feeds
3468 if ( $config->get( 'Feed' ) ) {
3469 $feedLinks = [];
3471 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3472 # Use the page name for the title. In principle, this could
3473 # lead to issues with having the same name for different feeds
3474 # corresponding to the same page, but we can't avoid that at
3475 # this low a level.
3477 $feedLinks[] = $this->feedLink(
3478 $format,
3479 $link,
3480 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3481 $this->msg(
3482 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3483 )->text()
3487 # Recent changes feed should appear on every page (except recentchanges,
3488 # that would be redundant). Put it after the per-page feed to avoid
3489 # changing existing behavior. It's still available, probably via a
3490 # menu in your browser. Some sites might have a different feed they'd
3491 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3492 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3493 # If so, use it instead.
3494 $sitename = $config->get( 'Sitename' );
3495 if ( $config->get( 'OverrideSiteFeed' ) ) {
3496 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3497 // Note, this->feedLink escapes the url.
3498 $feedLinks[] = $this->feedLink(
3499 $type,
3500 $feedUrl,
3501 $this->msg( "site-{$type}-feed", $sitename )->text()
3504 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3505 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3506 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3507 $feedLinks[] = $this->feedLink(
3508 $format,
3509 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3510 # For grep: 'site-rss-feed', 'site-atom-feed'
3511 $this->msg( "site-{$format}-feed", $sitename )->text()
3516 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3517 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3518 # use OutputPage::addFeedLink() instead.
3519 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3521 $tags += $feedLinks;
3524 # Canonical URL
3525 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3526 if ( $canonicalUrl !== false ) {
3527 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3528 } else {
3529 if ( $this->isArticleRelated() ) {
3530 // This affects all requests where "setArticleRelated" is true. This is
3531 // typically all requests that show content (query title, curid, oldid, diff),
3532 // and all wikipage actions (edit, delete, purge, info, history etc.).
3533 // It does not apply to File pages and Special pages.
3534 // 'history' and 'info' actions address page metadata rather than the page
3535 // content itself, so they may not be canonicalized to the view page url.
3536 // TODO: this ought to be better encapsulated in the Action class.
3537 $action = Action::getActionName( $this->getContext() );
3538 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3539 $query = "action={$action}";
3540 } else {
3541 $query = '';
3543 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3544 } else {
3545 $reqUrl = $this->getRequest()->getRequestURL();
3546 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3550 if ( $canonicalUrl !== false ) {
3551 $tags[] = Html::element( 'link', [
3552 'rel' => 'canonical',
3553 'href' => $canonicalUrl
3554 ] );
3557 return $tags;
3561 * Generate a "<link rel/>" for a feed.
3563 * @param string $type Feed type
3564 * @param string $url URL to the feed
3565 * @param string $text Value of the "title" attribute
3566 * @return string HTML fragment
3568 private function feedLink( $type, $url, $text ) {
3569 return Html::element( 'link', [
3570 'rel' => 'alternate',
3571 'type' => "application/$type+xml",
3572 'title' => $text,
3573 'href' => $url ]
3578 * Add a local or specified stylesheet, with the given media options.
3579 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3581 * @param string $style URL to the file
3582 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3583 * @param string $condition For IE conditional comments, specifying an IE version
3584 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3586 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3587 $options = [];
3588 if ( $media ) {
3589 $options['media'] = $media;
3591 if ( $condition ) {
3592 $options['condition'] = $condition;
3594 if ( $dir ) {
3595 $options['dir'] = $dir;
3597 $this->styles[$style] = $options;
3601 * Adds inline CSS styles
3602 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3604 * @param mixed $style_css Inline CSS
3605 * @param string $flip Set to 'flip' to flip the CSS if needed
3607 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3608 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3609 # If wanted, and the interface is right-to-left, flip the CSS
3610 $style_css = CSSJanus::transform( $style_css, true, false );
3612 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3616 * Build exempt modules and legacy non-ResourceLoader styles.
3618 * @return string|WrappedStringList HTML
3620 protected function buildExemptModules() {
3621 global $wgContLang;
3623 $chunks = [];
3624 // Things that go after the ResourceLoaderDynamicStyles marker
3625 $append = [];
3627 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3628 if ( $this->isUserCssPreview() ) {
3629 $append[] = $this->makeResourceLoaderLink(
3630 'user.styles',
3631 ResourceLoaderModule::TYPE_STYLES,
3632 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3635 // Load the previewed CSS. Janus it if needed.
3636 // User-supplied CSS is assumed to in the wiki's content language.
3637 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3638 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3639 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3641 $append[] = Html::inlineStyle( $previewedCSS );
3644 // We want site, private and user styles to override dynamically added styles from
3645 // general modules, but we want dynamically added styles to override statically added
3646 // style modules. So the order has to be:
3647 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3648 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3649 // - ResourceLoaderDynamicStyles marker
3650 // - site/private/user styles
3652 // Add legacy styles added through addStyle()/addInlineStyle() here
3653 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3655 $chunks[] = Html::element(
3656 'meta',
3657 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3660 $separateReq = [ 'site.styles', 'user.styles' ];
3661 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3662 // Combinable modules
3663 $chunks[] = $this->makeResourceLoaderLink(
3664 array_diff( $moduleNames, $separateReq ),
3665 ResourceLoaderModule::TYPE_STYLES
3668 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3669 // These require their own dedicated request in order to support "@import"
3670 // syntax, which is incompatible with concatenation. (T147667, T37562)
3671 $chunks[] = $this->makeResourceLoaderLink( $name,
3672 ResourceLoaderModule::TYPE_STYLES
3677 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3681 * @return array
3683 public function buildCssLinksArray() {
3684 $links = [];
3686 // Add any extension CSS
3687 foreach ( $this->mExtStyles as $url ) {
3688 $this->addStyle( $url );
3690 $this->mExtStyles = [];
3692 foreach ( $this->styles as $file => $options ) {
3693 $link = $this->styleLink( $file, $options );
3694 if ( $link ) {
3695 $links[$file] = $link;
3698 return $links;
3702 * Generate \<link\> tags for stylesheets
3704 * @param string $style URL to the file
3705 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3706 * @return string HTML fragment
3708 protected function styleLink( $style, array $options ) {
3709 if ( isset( $options['dir'] ) ) {
3710 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3711 return '';
3715 if ( isset( $options['media'] ) ) {
3716 $media = self::transformCssMedia( $options['media'] );
3717 if ( is_null( $media ) ) {
3718 return '';
3720 } else {
3721 $media = 'all';
3724 if ( substr( $style, 0, 1 ) == '/' ||
3725 substr( $style, 0, 5 ) == 'http:' ||
3726 substr( $style, 0, 6 ) == 'https:' ) {
3727 $url = $style;
3728 } else {
3729 $config = $this->getConfig();
3730 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3731 $config->get( 'StyleVersion' );
3734 $link = Html::linkedStyle( $url, $media );
3736 if ( isset( $options['condition'] ) ) {
3737 $condition = htmlspecialchars( $options['condition'] );
3738 $link = "<!--[if $condition]>$link<![endif]-->";
3740 return $link;
3744 * Transform path to web-accessible static resource.
3746 * This is used to add a validation hash as query string.
3747 * This aids various behaviors:
3749 * - Put long Cache-Control max-age headers on responses for improved
3750 * cache performance.
3751 * - Get the correct version of a file as expected by the current page.
3752 * - Instantly get the updated version of a file after deployment.
3754 * Avoid using this for urls included in HTML as otherwise clients may get different
3755 * versions of a resource when navigating the site depending on when the page was cached.
3756 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3757 * an external stylesheet).
3759 * @since 1.27
3760 * @param Config $config
3761 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3762 * @return string URL
3764 public static function transformResourcePath( Config $config, $path ) {
3765 global $IP;
3767 $localDir = $IP;
3768 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3769 if ( $remotePathPrefix === '' ) {
3770 // The configured base path is required to be empty string for
3771 // wikis in the domain root
3772 $remotePath = '/';
3773 } else {
3774 $remotePath = $remotePathPrefix;
3776 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3777 // - Path is outside wgResourceBasePath, ignore.
3778 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3779 return $path;
3781 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3782 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3783 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3784 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3785 $uploadPath = $config->get( 'UploadPath' );
3786 if ( strpos( $path, $uploadPath ) === 0 ) {
3787 $localDir = $config->get( 'UploadDirectory' );
3788 $remotePathPrefix = $remotePath = $uploadPath;
3791 $path = RelPath\getRelativePath( $path, $remotePath );
3792 return self::transformFilePath( $remotePathPrefix, $localDir, $path );
3796 * Utility method for transformResourceFilePath().
3798 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3800 * @since 1.27
3801 * @param string $remotePathPrefix URL path prefix that points to $localPath
3802 * @param string $localPath File directory exposed at $remotePath
3803 * @param string $file Path to target file relative to $localPath
3804 * @return string URL
3806 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3807 $hash = md5_file( "$localPath/$file" );
3808 if ( $hash === false ) {
3809 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3810 $hash = '';
3812 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3816 * Transform "media" attribute based on request parameters
3818 * @param string $media Current value of the "media" attribute
3819 * @return string Modified value of the "media" attribute, or null to skip
3820 * this stylesheet
3822 public static function transformCssMedia( $media ) {
3823 global $wgRequest;
3825 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3826 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3828 // Switch in on-screen display for media testing
3829 $switches = [
3830 'printable' => 'print',
3831 'handheld' => 'handheld',
3833 foreach ( $switches as $switch => $targetMedia ) {
3834 if ( $wgRequest->getBool( $switch ) ) {
3835 if ( $media == $targetMedia ) {
3836 $media = '';
3837 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3838 /* This regex will not attempt to understand a comma-separated media_query_list
3840 * Example supported values for $media:
3841 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3842 * Example NOT supported value for $media:
3843 * '3d-glasses, screen, print and resolution > 90dpi'
3845 * If it's a print request, we never want any kind of screen stylesheets
3846 * If it's a handheld request (currently the only other choice with a switch),
3847 * we don't want simple 'screen' but we might want screen queries that
3848 * have a max-width or something, so we'll pass all others on and let the
3849 * client do the query.
3851 if ( $targetMedia == 'print' || $media == 'screen' ) {
3852 return null;
3858 return $media;
3862 * Add a wikitext-formatted message to the output.
3863 * This is equivalent to:
3865 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3867 public function addWikiMsg( /*...*/ ) {
3868 $args = func_get_args();
3869 $name = array_shift( $args );
3870 $this->addWikiMsgArray( $name, $args );
3874 * Add a wikitext-formatted message to the output.
3875 * Like addWikiMsg() except the parameters are taken as an array
3876 * instead of a variable argument list.
3878 * @param string $name
3879 * @param array $args
3881 public function addWikiMsgArray( $name, $args ) {
3882 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3886 * This function takes a number of message/argument specifications, wraps them in
3887 * some overall structure, and then parses the result and adds it to the output.
3889 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3890 * and so on. The subsequent arguments may be either
3891 * 1) strings, in which case they are message names, or
3892 * 2) arrays, in which case, within each array, the first element is the message
3893 * name, and subsequent elements are the parameters to that message.
3895 * Don't use this for messages that are not in the user's interface language.
3897 * For example:
3899 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3901 * Is equivalent to:
3903 * $wgOut->addWikiText( "<div class='error'>\n"
3904 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3906 * The newline after the opening div is needed in some wikitext. See T21226.
3908 * @param string $wrap
3910 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3911 $msgSpecs = func_get_args();
3912 array_shift( $msgSpecs );
3913 $msgSpecs = array_values( $msgSpecs );
3914 $s = $wrap;
3915 foreach ( $msgSpecs as $n => $spec ) {
3916 if ( is_array( $spec ) ) {
3917 $args = $spec;
3918 $name = array_shift( $args );
3919 if ( isset( $args['options'] ) ) {
3920 unset( $args['options'] );
3921 wfDeprecated(
3922 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3923 '1.20'
3926 } else {
3927 $args = [];
3928 $name = $spec;
3930 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3932 $this->addWikiText( $s );
3936 * Whether the output has a table of contents
3937 * @return bool
3938 * @since 1.22
3940 public function isTOCEnabled() {
3941 return $this->mEnableTOC;
3945 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3946 * @param bool $flag
3947 * @since 1.23
3949 public function enableSectionEditLinks( $flag = true ) {
3950 $this->mEnableSectionEditLinks = $flag;
3954 * @return bool
3955 * @since 1.23
3957 public function sectionEditLinksEnabled() {
3958 return $this->mEnableSectionEditLinks;
3962 * Helper function to setup the PHP implementation of OOUI to use in this request.
3964 * @since 1.26
3965 * @param String $skinName The Skin name to determine the correct OOUI theme
3966 * @param String $dir Language direction
3968 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3969 $themes = ResourceLoaderOOUIModule::getSkinThemeMap();
3970 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : $themes['default'];
3971 // For example, 'OOUI\WikimediaUITheme'.
3972 $themeClass = "OOUI\\{$theme}Theme";
3973 OOUI\Theme::setSingleton( new $themeClass() );
3974 OOUI\Element::setDefaultDir( $dir );
3978 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3979 * MediaWiki and this OutputPage instance.
3981 * @since 1.25
3983 public function enableOOUI() {
3984 self::setupOOUI(
3985 strtolower( $this->getSkin()->getSkinName() ),
3986 $this->getLanguage()->getDir()
3988 $this->addModuleStyles( [
3989 'oojs-ui-core.styles',
3990 'oojs-ui.styles.indicators',
3991 'oojs-ui.styles.textures',
3992 'mediawiki.widgets.styles',
3993 'oojs-ui.styles.icons-content',
3994 'oojs-ui.styles.icons-alerts',
3995 'oojs-ui.styles.icons-interactions',
3996 ] );
4000 * Add Link headers for preloading the wiki's logo.
4002 * @since 1.26
4004 protected function addLogoPreloadLinkHeaders() {
4005 $logo = ResourceLoaderSkinModule::getLogo( $this->getConfig() );
4007 $tags = [];
4008 $logosPerDppx = [];
4009 $logos = [];
4011 if ( !is_array( $logo ) ) {
4012 // No media queries required if we only have one variant
4013 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
4014 return;
4017 foreach ( $logo as $dppx => $src ) {
4018 // Keys are in this format: "1.5x"
4019 $dppx = substr( $dppx, 0, -1 );
4020 $logosPerDppx[$dppx] = $src;
4023 // Because PHP can't have floats as array keys
4024 uksort( $logosPerDppx, function ( $a , $b ) {
4025 $a = floatval( $a );
4026 $b = floatval( $b );
4028 if ( $a == $b ) {
4029 return 0;
4031 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
4032 return ( $a < $b ) ? -1 : 1;
4033 } );
4035 foreach ( $logosPerDppx as $dppx => $src ) {
4036 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
4039 $logosCount = count( $logos );
4040 // Logic must match ResourceLoaderSkinModule:
4041 // - 1x applies to resolution < 1.5dppx
4042 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4043 // - 2x applies to resolution >= 2dppx
4044 // Note that min-resolution and max-resolution are both inclusive.
4045 for ( $i = 0; $i < $logosCount; $i++ ) {
4046 if ( $i === 0 ) {
4047 // Smallest dppx
4048 // min-resolution is ">=" (larger than or equal to)
4049 // "not min-resolution" is essentially "<"
4050 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4051 } elseif ( $i !== $logosCount - 1 ) {
4052 // In between
4053 // Media query expressions can only apply "not" to the entire expression
4054 // (e.g. can't express ">= 1.5 and not >= 2).
4055 // Workaround: Use <= 1.9999 in place of < 2.
4056 $upper_bound = floatval( $logos[ $i + 1 ]['dppx'] ) - 0.000001;
4057 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4058 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4059 } else {
4060 // Largest dppx
4061 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4064 $this->addLinkHeader(
4065 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query