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
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use Wikimedia\RelPath
;
27 use Wikimedia\WrappedString
;
28 use Wikimedia\WrappedStringList
;
31 * This class should be covered by a general architecture document which does
32 * not exist as of January 2011. This is one of the Core classes and should
33 * be read at least once by any new developers.
35 * This class is used to prepare the final rendering. A skin is then
36 * applied to the output parameters (links, javascript, html, categories ...).
38 * @todo FIXME: Another class handles sending the whole page to the client.
40 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
45 class OutputPage
extends ContextSource
{
46 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
47 protected $mMetatags = [];
50 protected $mLinktags = [];
53 protected $mCanonicalUrl = false;
56 * @var string Should be private - has getter and setter. Contains
58 public $mPagetitle = '';
61 * @var string Contains all of the "<body>" content. Should be private we
62 * got set/get accessors and the append() method.
64 public $mBodytext = '';
66 /** @var string Stores contents of "<title>" tag */
67 private $mHTMLtitle = '';
70 * @var bool Is the displayed content related to the source of the
71 * corresponding wiki article.
73 private $mIsarticle = false;
75 /** @var bool Stores "article flag" toggle. */
76 private $mIsArticleRelated = true;
79 * @var bool We have to set isPrintable(). Some pages should
80 * never be printed (ex: redirections).
82 private $mPrintable = false;
85 * @var array Contains the page subtitle. Special pages usually have some
86 * links here. Don't confuse with site subtitle added by skins.
88 private $mSubtitle = [];
91 public $mRedirect = '';
94 protected $mStatusCode;
97 * @var string Used for sending cache control.
98 * The whole caching system should probably be moved into its own class.
100 protected $mLastModified = '';
103 protected $mCategoryLinks = [];
106 protected $mCategories = [
112 protected $mIndicators = [];
114 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
115 private $mLanguageLinks = [];
118 * Used for JavaScript (predates ResourceLoader)
119 * @todo We should split JS / CSS.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contain either a link to a stylesheet or inline CSS.
123 private $mScripts = '';
125 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
126 protected $mInlineStyles = '';
129 * @var string Used by skin template.
130 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
132 public $mPageLinkTitle = '';
134 /** @var array Array of elements in "<head>". Parser might add its own headers! */
135 protected $mHeadItems = [];
137 /** @var array Additional <body> classes; there are also <body> classes from other sources */
138 protected $mAdditionalBodyClasses = [];
141 protected $mModules = [];
144 protected $mModuleScripts = [];
147 protected $mModuleStyles = [];
149 /** @var ResourceLoader */
150 protected $mResourceLoader;
152 /** @var ResourceLoaderClientHtml */
155 /** @var ResourceLoaderContext */
156 private $rlClientContext;
159 private $rlUserModuleState;
162 private $rlExemptStyleModules;
165 protected $mJsConfigVars = [];
168 protected $mTemplateIds = [];
171 protected $mImageTimeKeys = [];
174 public $mRedirectCode = '';
176 protected $mFeedLinksAppendQuery = null;
179 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
180 * @see ResourceLoaderModule::$origin
181 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
183 protected $mAllowedModules = [
184 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
187 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
188 protected $mDoNothing = false;
193 protected $mContainsNewMagic = 0;
196 * lazy initialised, use parserOptions()
199 protected $mParserOptions = null;
202 * Handles the Atom / RSS links.
203 * We probably only support Atom in 2011.
204 * @see $wgAdvertisedFeedTypes
206 private $mFeedLinks = [];
208 // Gwicke work on squid caching? Roughly from 2003.
209 protected $mEnableClientCache = true;
211 /** @var bool Flag if output should only contain the body of the article. */
212 private $mArticleBodyOnly = false;
215 protected $mNewSectionLink = false;
218 protected $mHideNewSectionLink = false;
221 * @var bool Comes from the parser. This was probably made to load CSS/JS
222 * only if we had "<gallery>". Used directly in CategoryPage.php.
223 * Looks like ResourceLoader can replace this.
225 public $mNoGallery = false;
228 private $mPageTitleActionText = '';
230 /** @var int Cache stuff. Looks like mEnableClientCache */
231 protected $mCdnMaxage = 0;
232 /** @var int Upper limit on mCdnMaxage */
233 protected $mCdnMaxageLimit = INF
;
236 * @var bool Controls if anti-clickjacking / frame-breaking headers will
237 * be sent. This should be done for pages where edit actions are possible.
238 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
240 protected $mPreventClickjacking = true;
242 /** @var int To include the variable {{REVISIONID}} */
243 private $mRevisionId = null;
246 private $mRevisionTimestamp = null;
249 protected $mFileVersion = null;
252 * @var array An array of stylesheet filenames (relative from skins path),
253 * with options for CSS media, IE conditions, and RTL/LTR direction.
254 * For internal use; add settings in the skin via $this->addStyle()
256 * Style again! This seems like a code duplication since we already have
257 * mStyles. This is what makes Open Source amazing.
259 protected $styles = [];
261 private $mIndexPolicy = 'index';
262 private $mFollowPolicy = 'follow';
263 private $mVaryHeader = [
264 'Accept-Encoding' => [ 'match=gzip' ],
268 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
273 private $mRedirectedFrom = null;
276 * Additional key => value data
278 private $mProperties = [];
281 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
283 private $mTarget = null;
286 * @var bool Whether parser output contains a table of contents
288 private $mEnableTOC = false;
291 * @var string|null The URL to send in a <link> element with rel=license
293 private $copyrightUrl;
295 /** @var array Profiling data */
296 private $limitReportJSData = [];
299 * Link: header contents
301 private $mLinkHeader = [];
304 * Constructor for OutputPage. This should not be called directly.
305 * Instead a new RequestContext should be created and it will implicitly create
306 * a OutputPage tied to that context.
307 * @param IContextSource $context
309 function __construct( IContextSource
$context ) {
310 $this->setContext( $context );
314 * Redirect to $url rather than displaying the normal page
317 * @param string $responsecode HTTP status code
319 public function redirect( $url, $responsecode = '302' ) {
320 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
321 $this->mRedirect
= str_replace( "\n", '', $url );
322 $this->mRedirectCode
= $responsecode;
326 * Get the URL to redirect to, or an empty string if not redirect URL set
330 public function getRedirect() {
331 return $this->mRedirect
;
335 * Set the copyright URL to send with the output.
336 * Empty string to omit, null to reset.
340 * @param string|null $url
342 public function setCopyrightUrl( $url ) {
343 $this->copyrightUrl
= $url;
347 * Set the HTTP status code to send with the output.
349 * @param int $statusCode
351 public function setStatusCode( $statusCode ) {
352 $this->mStatusCode
= $statusCode;
356 * Add a new "<meta>" tag
357 * To add an http-equiv meta tag, precede the name with "http:"
359 * @param string $name Name of the meta tag
360 * @param string $val Value of the meta tag
362 function addMeta( $name, $val ) {
363 array_push( $this->mMetatags
, [ $name, $val ] );
367 * Returns the current <meta> tags
372 public function getMetaTags() {
373 return $this->mMetatags
;
377 * Add a new \<link\> tag to the page header.
379 * Note: use setCanonicalUrl() for rel=canonical.
381 * @param array $linkarr Associative array of attributes.
383 function addLink( array $linkarr ) {
384 array_push( $this->mLinktags
, $linkarr );
388 * Returns the current <link> tags
393 public function getLinkTags() {
394 return $this->mLinktags
;
398 * Add a new \<link\> with "rel" attribute set to "meta"
400 * @param array $linkarr Associative array mapping attribute names to their
401 * values, both keys and values will be escaped, and the
402 * "rel" attribute will be automatically added
404 function addMetadataLink( array $linkarr ) {
405 $linkarr['rel'] = $this->getMetadataAttribute();
406 $this->addLink( $linkarr );
410 * Set the URL to be used for the <link rel=canonical>. This should be used
411 * in preference to addLink(), to avoid duplicate link tags.
414 function setCanonicalUrl( $url ) {
415 $this->mCanonicalUrl
= $url;
419 * Returns the URL to be used for the <link rel=canonical> if
423 * @return bool|string
425 public function getCanonicalUrl() {
426 return $this->mCanonicalUrl
;
430 * Get the value of the "rel" attribute for metadata links
434 public function getMetadataAttribute() {
435 # note: buggy CC software only reads first "meta" link
436 static $haveMeta = false;
438 return 'alternate meta';
446 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
447 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
450 * @param string $script Raw HTML
452 function addScript( $script ) {
453 $this->mScripts
.= $script;
457 * Add a JavaScript file out of skins/common, or a given relative path.
458 * Internal use only. Use OutputPage::addModules() if possible.
460 * @param string $file Filename in skins/common or complete on-server path
462 * @param string $version Style version of the file. Defaults to $wgStyleVersion
464 public function addScriptFile( $file, $version = null ) {
465 // See if $file parameter is an absolute URL or begins with a slash
466 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
469 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
471 if ( is_null( $version ) ) {
472 $version = $this->getConfig()->get( 'StyleVersion' );
474 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
478 * Add a self-contained script tag with the given contents
479 * Internal use only. Use OutputPage::addModules() if possible.
481 * @param string $script JavaScript text, no script tags
483 public function addInlineScript( $script ) {
484 $this->mScripts
.= Html
::inlineScript( $script );
488 * Filter an array of modules to remove insufficiently trustworthy members, and modules
489 * which are no longer registered (eg a page is cached before an extension is disabled)
490 * @param array $modules
491 * @param string|null $position Unused
492 * @param string $type
495 protected function filterModules( array $modules, $position = null,
496 $type = ResourceLoaderModule
::TYPE_COMBINED
498 $resourceLoader = $this->getResourceLoader();
499 $filteredModules = [];
500 foreach ( $modules as $val ) {
501 $module = $resourceLoader->getModule( $val );
502 if ( $module instanceof ResourceLoaderModule
503 && $module->getOrigin() <= $this->getAllowedModules( $type )
505 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
506 $this->warnModuleTargetFilter( $module->getName() );
509 $filteredModules[] = $val;
512 return $filteredModules;
515 private function warnModuleTargetFilter( $moduleName ) {
516 static $warnings = [];
517 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
520 $warnings[$this->mTarget
][$moduleName] = true;
521 $this->getResourceLoader()->getLogger()->debug(
522 'Module "{module}" not loadable on target "{target}".',
524 'module' => $moduleName,
525 'target' => $this->mTarget
,
531 * Get the list of modules to include on this page
533 * @param bool $filter Whether to filter out insufficiently trustworthy modules
534 * @param string|null $position Unused
535 * @param string $param
536 * @param string $type
537 * @return array Array of module names
539 public function getModules( $filter = false, $position = null, $param = 'mModules',
540 $type = ResourceLoaderModule
::TYPE_COMBINED
542 $modules = array_values( array_unique( $this->$param ) );
544 ?
$this->filterModules( $modules, null, $type )
549 * Add one or more modules recognized by ResourceLoader. Modules added
550 * through this function will be loaded by ResourceLoader when the
553 * @param string|array $modules Module name (string) or array of module names
555 public function addModules( $modules ) {
556 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
560 * Get the list of module JS to include on this page
562 * @param bool $filter
563 * @param string|null $position Unused
564 * @return array Array of module names
566 public function getModuleScripts( $filter = false, $position = null ) {
567 return $this->getModules( $filter, null, 'mModuleScripts',
568 ResourceLoaderModule
::TYPE_SCRIPTS
573 * Add only JS of one or more modules recognized by ResourceLoader. Module
574 * scripts added through this function will be loaded by ResourceLoader when
577 * @param string|array $modules Module name (string) or array of module names
579 public function addModuleScripts( $modules ) {
580 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
584 * Get the list of module CSS to include on this page
586 * @param bool $filter
587 * @param string|null $position Unused
588 * @return array Array of module names
590 public function getModuleStyles( $filter = false, $position = null ) {
591 return $this->getModules( $filter, null, 'mModuleStyles',
592 ResourceLoaderModule
::TYPE_STYLES
597 * Add only CSS of one or more modules recognized by ResourceLoader.
599 * Module styles added through this function will be added using standard link CSS
600 * tags, rather than as a combined Javascript and CSS package. Thus, they will
601 * load when JavaScript is disabled (unless CSS also happens to be disabled).
603 * @param string|array $modules Module name (string) or array of module names
605 public function addModuleStyles( $modules ) {
606 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
610 * @return null|string ResourceLoader target
612 public function getTarget() {
613 return $this->mTarget
;
617 * Sets ResourceLoader target for load.php links. If null, will be omitted
619 * @param string|null $target
621 public function setTarget( $target ) {
622 $this->mTarget
= $target;
626 * Get an array of head items
630 function getHeadItemsArray() {
631 return $this->mHeadItems
;
635 * Add or replace a head item to the output
637 * Whenever possible, use more specific options like ResourceLoader modules,
638 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
639 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
640 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
641 * This would be your very LAST fallback.
643 * @param string $name Item name
644 * @param string $value Raw HTML
646 public function addHeadItem( $name, $value ) {
647 $this->mHeadItems
[$name] = $value;
651 * Add one or more head items to the output
654 * @param string|string[] $values Raw HTML
656 public function addHeadItems( $values ) {
657 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
661 * Check if the header item $name is already set
663 * @param string $name Item name
666 public function hasHeadItem( $name ) {
667 return isset( $this->mHeadItems
[$name] );
671 * Add a class to the <body> element
674 * @param string|string[] $classes One or more classes to add
676 public function addBodyClasses( $classes ) {
677 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
681 * Set whether the output should only contain the body of the article,
682 * without any skin, sidebar, etc.
683 * Used e.g. when calling with "action=render".
685 * @param bool $only Whether to output only the body of the article
687 public function setArticleBodyOnly( $only ) {
688 $this->mArticleBodyOnly
= $only;
692 * Return whether the output will contain only the body of the article
696 public function getArticleBodyOnly() {
697 return $this->mArticleBodyOnly
;
701 * Set an additional output property
704 * @param string $name
705 * @param mixed $value
707 public function setProperty( $name, $value ) {
708 $this->mProperties
[$name] = $value;
712 * Get an additional output property
715 * @param string $name
716 * @return mixed Property value or null if not found
718 public function getProperty( $name ) {
719 if ( isset( $this->mProperties
[$name] ) ) {
720 return $this->mProperties
[$name];
727 * checkLastModified tells the client to use the client-cached page if
728 * possible. If successful, the OutputPage is disabled so that
729 * any future call to OutputPage->output() have no effect.
731 * Side effect: sets mLastModified for Last-Modified header
733 * @param string $timestamp
735 * @return bool True if cache-ok headers was sent.
737 public function checkLastModified( $timestamp ) {
738 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
739 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
742 $config = $this->getConfig();
743 if ( !$config->get( 'CachePages' ) ) {
744 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
748 $timestamp = wfTimestamp( TS_MW
, $timestamp );
750 'page' => $timestamp,
751 'user' => $this->getUser()->getTouched(),
752 'epoch' => $config->get( 'CacheEpoch' )
754 if ( $config->get( 'UseSquid' ) ) {
755 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, $this->getCdnCacheEpoch(
757 $config->get( 'SquidMaxage' )
760 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
762 $maxModified = max( $modifiedTimes );
763 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
765 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
766 if ( $clientHeader === false ) {
767 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
771 # IE sends sizes after the date like this:
772 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
773 # this breaks strtotime().
774 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
776 Wikimedia\
suppressWarnings(); // E_STRICT system time bitching
777 $clientHeaderTime = strtotime( $clientHeader );
778 Wikimedia\restoreWarnings
();
779 if ( !$clientHeaderTime ) {
781 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
784 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
788 foreach ( $modifiedTimes as $name => $value ) {
789 if ( $info !== '' ) {
792 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
795 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
796 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
797 wfDebug( __METHOD__
. ": effective Last-Modified: " .
798 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
799 if ( $clientHeaderTime < $maxModified ) {
800 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
805 # Give a 304 Not Modified response code and disable body output
806 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
807 ini_set( 'zlib.output_compression', 0 );
808 $this->getRequest()->response()->statusHeader( 304 );
809 $this->sendCacheControl();
812 // Don't output a compressed blob when using ob_gzhandler;
813 // it's technically against HTTP spec and seems to confuse
814 // Firefox when the response gets split over two packets.
815 wfClearOutputBuffers();
821 * @param int $reqTime Time of request (eg. now)
822 * @param int $maxAge Cache TTL in seconds
823 * @return int Timestamp
825 private function getCdnCacheEpoch( $reqTime, $maxAge ) {
826 // Ensure Last-Modified is never more than (wgSquidMaxage) in the past,
827 // because even if the wiki page content hasn't changed since, static
828 // resources may have changed (skin HTML, interface messages, urls, etc.)
829 // and must roll-over in a timely manner (T46570)
830 return $reqTime - $maxAge;
834 * Override the last modified timestamp
836 * @param string $timestamp New timestamp, in a format readable by
839 public function setLastModified( $timestamp ) {
840 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
844 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
846 * @param string $policy The literal string to output as the contents of
847 * the meta tag. Will be parsed according to the spec and output in
851 public function setRobotPolicy( $policy ) {
852 $policy = Article
::formatRobotPolicy( $policy );
854 if ( isset( $policy['index'] ) ) {
855 $this->setIndexPolicy( $policy['index'] );
857 if ( isset( $policy['follow'] ) ) {
858 $this->setFollowPolicy( $policy['follow'] );
863 * Set the index policy for the page, but leave the follow policy un-
866 * @param string $policy Either 'index' or 'noindex'.
869 public function setIndexPolicy( $policy ) {
870 $policy = trim( $policy );
871 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
872 $this->mIndexPolicy
= $policy;
877 * Set the follow policy for the page, but leave the index policy un-
880 * @param string $policy Either 'follow' or 'nofollow'.
883 public function setFollowPolicy( $policy ) {
884 $policy = trim( $policy );
885 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
886 $this->mFollowPolicy
= $policy;
891 * Set the new value of the "action text", this will be added to the
892 * "HTML title", separated from it with " - ".
894 * @param string $text New value of the "action text"
896 public function setPageTitleActionText( $text ) {
897 $this->mPageTitleActionText
= $text;
901 * Get the value of the "action text"
905 public function getPageTitleActionText() {
906 return $this->mPageTitleActionText
;
910 * "HTML title" means the contents of "<title>".
911 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
913 * @param string|Message $name
915 public function setHTMLTitle( $name ) {
916 if ( $name instanceof Message
) {
917 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
919 $this->mHTMLtitle
= $name;
924 * Return the "HTML title", i.e. the content of the "<title>" tag.
928 public function getHTMLTitle() {
929 return $this->mHTMLtitle
;
933 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
937 public function setRedirectedFrom( $t ) {
938 $this->mRedirectedFrom
= $t;
942 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
943 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
944 * but not bad tags like \<script\>. This function automatically sets
945 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
946 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
947 * good tags like \<i\> will be dropped entirely.
949 * @param string|Message $name
951 public function setPageTitle( $name ) {
952 if ( $name instanceof Message
) {
953 $name = $name->setContext( $this->getContext() )->text();
956 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
957 # but leave "<i>foobar</i>" alone
958 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
959 $this->mPagetitle
= $nameWithTags;
961 # change "<i>foo&bar</i>" to "foo&bar"
963 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
964 ->inContentLanguage()
969 * Return the "page title", i.e. the content of the \<h1\> tag.
973 public function getPageTitle() {
974 return $this->mPagetitle
;
978 * Set the Title object to use
982 public function setTitle( Title
$t ) {
983 $this->getContext()->setTitle( $t );
987 * Replace the subtitle with $str
989 * @param string|Message $str New value of the subtitle. String should be safe HTML.
991 public function setSubtitle( $str ) {
992 $this->clearSubtitle();
993 $this->addSubtitle( $str );
997 * Add $str to the subtitle
999 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1001 public function addSubtitle( $str ) {
1002 if ( $str instanceof Message
) {
1003 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1005 $this->mSubtitle
[] = $str;
1010 * Build message object for a subtitle containing a backlink to a page
1012 * @param Title $title Title to link to
1013 * @param array $query Array of additional parameters to include in the link
1017 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1018 if ( $title->isRedirect() ) {
1019 $query['redirect'] = 'no';
1021 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1022 return wfMessage( 'backlinksubtitle' )
1023 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1027 * Add a subtitle containing a backlink to a page
1029 * @param Title $title Title to link to
1030 * @param array $query Array of additional parameters to include in the link
1032 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1033 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1037 * Clear the subtitles
1039 public function clearSubtitle() {
1040 $this->mSubtitle
= [];
1048 public function getSubtitle() {
1049 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1053 * Set the page as printable, i.e. it'll be displayed with all
1054 * print styles included
1056 public function setPrintable() {
1057 $this->mPrintable
= true;
1061 * Return whether the page is "printable"
1065 public function isPrintable() {
1066 return $this->mPrintable
;
1070 * Disable output completely, i.e. calling output() will have no effect
1072 public function disable() {
1073 $this->mDoNothing
= true;
1077 * Return whether the output will be completely disabled
1081 public function isDisabled() {
1082 return $this->mDoNothing
;
1086 * Show an "add new section" link?
1090 public function showNewSectionLink() {
1091 return $this->mNewSectionLink
;
1095 * Forcibly hide the new section link?
1099 public function forceHideNewSectionLink() {
1100 return $this->mHideNewSectionLink
;
1104 * Add or remove feed links in the page header
1105 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1106 * for the new version
1107 * @see addFeedLink()
1109 * @param bool $show True: add default feeds, false: remove all feeds
1111 public function setSyndicated( $show = true ) {
1113 $this->setFeedAppendQuery( false );
1115 $this->mFeedLinks
= [];
1120 * Add default feeds to the page header
1121 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1122 * for the new version
1123 * @see addFeedLink()
1125 * @param string $val Query to append to feed links or false to output
1128 public function setFeedAppendQuery( $val ) {
1129 $this->mFeedLinks
= [];
1131 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1132 $query = "feed=$type";
1133 if ( is_string( $val ) ) {
1134 $query .= '&' . $val;
1136 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1141 * Add a feed link to the page header
1143 * @param string $format Feed type, should be a key of $wgFeedClasses
1144 * @param string $href URL
1146 public function addFeedLink( $format, $href ) {
1147 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1148 $this->mFeedLinks
[$format] = $href;
1153 * Should we output feed links for this page?
1156 public function isSyndicated() {
1157 return count( $this->mFeedLinks
) > 0;
1161 * Return URLs for each supported syndication format for this page.
1162 * @return array Associating format keys with URLs
1164 public function getSyndicationLinks() {
1165 return $this->mFeedLinks
;
1169 * Will currently always return null
1173 public function getFeedAppendQuery() {
1174 return $this->mFeedLinksAppendQuery
;
1178 * Set whether the displayed content is related to the source of the
1179 * corresponding article on the wiki
1180 * Setting true will cause the change "article related" toggle to true
1184 public function setArticleFlag( $v ) {
1185 $this->mIsarticle
= $v;
1187 $this->mIsArticleRelated
= $v;
1192 * Return whether the content displayed page is related to the source of
1193 * the corresponding article on the wiki
1197 public function isArticle() {
1198 return $this->mIsarticle
;
1202 * Set whether this page is related an article on the wiki
1203 * Setting false will cause the change of "article flag" toggle to false
1207 public function setArticleRelated( $v ) {
1208 $this->mIsArticleRelated
= $v;
1210 $this->mIsarticle
= false;
1215 * Return whether this page is related an article on the wiki
1219 public function isArticleRelated() {
1220 return $this->mIsArticleRelated
;
1224 * Add new language links
1226 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1227 * (e.g. 'fr:Test page')
1229 public function addLanguageLinks( array $newLinkArray ) {
1230 $this->mLanguageLinks +
= $newLinkArray;
1234 * Reset the language links and add new language links
1236 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1237 * (e.g. 'fr:Test page')
1239 public function setLanguageLinks( array $newLinkArray ) {
1240 $this->mLanguageLinks
= $newLinkArray;
1244 * Get the list of language links
1246 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1248 public function getLanguageLinks() {
1249 return $this->mLanguageLinks
;
1253 * Add an array of categories, with names in the keys
1255 * @param array $categories Mapping category name => sort key
1257 public function addCategoryLinks( array $categories ) {
1260 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1264 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1266 # Set all the values to 'normal'.
1267 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1269 # Mark hidden categories
1270 foreach ( $res as $row ) {
1271 if ( isset( $row->pp_value
) ) {
1272 $categories[$row->page_title
] = 'hidden';
1276 // Avoid PHP 7.1 warning of passing $this by reference
1277 $outputPage = $this;
1278 # Add the remaining categories to the skin
1280 'OutputPageMakeCategoryLinks',
1281 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1283 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1284 foreach ( $categories as $category => $type ) {
1285 // array keys will cast numeric category names to ints, so cast back to string
1286 $category = (string)$category;
1287 $origcategory = $category;
1288 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1292 $wgContLang->findVariantLink( $category, $title, true );
1293 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1296 $text = $wgContLang->convertHtml( $title->getText() );
1297 $this->mCategories
[$type][] = $title->getText();
1298 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1304 * @param array $categories
1305 * @return bool|ResultWrapper
1307 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1308 # Add the links to a LinkBatch
1309 $arr = [ NS_CATEGORY
=> $categories ];
1310 $lb = new LinkBatch
;
1311 $lb->setArray( $arr );
1313 # Fetch existence plus the hiddencat property
1314 $dbr = wfGetDB( DB_REPLICA
);
1315 $fields = array_merge(
1316 LinkCache
::getSelectFields(),
1317 [ 'page_namespace', 'page_title', 'pp_value' ]
1320 $res = $dbr->select( [ 'page', 'page_props' ],
1322 $lb->constructSet( 'page', $dbr ),
1325 [ 'page_props' => [ 'LEFT JOIN', [
1326 'pp_propname' => 'hiddencat',
1331 # Add the results to the link cache
1332 $lb->addResultToCache( LinkCache
::singleton(), $res );
1338 * Reset the category links (but not the category list) and add $categories
1340 * @param array $categories Mapping category name => sort key
1342 public function setCategoryLinks( array $categories ) {
1343 $this->mCategoryLinks
= [];
1344 $this->addCategoryLinks( $categories );
1348 * Get the list of category links, in a 2-D array with the following format:
1349 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1350 * hidden categories) and $link a HTML fragment with a link to the category
1355 public function getCategoryLinks() {
1356 return $this->mCategoryLinks
;
1360 * Get the list of category names this page belongs to.
1362 * @param string $type The type of categories which should be returned. Possible values:
1363 * * all: all categories of all types
1364 * * hidden: only the hidden categories
1365 * * normal: all categories, except hidden categories
1366 * @return array Array of strings
1368 public function getCategories( $type = 'all' ) {
1369 if ( $type === 'all' ) {
1370 $allCategories = [];
1371 foreach ( $this->mCategories
as $categories ) {
1372 $allCategories = array_merge( $allCategories, $categories );
1374 return $allCategories;
1376 if ( !isset( $this->mCategories
[$type] ) ) {
1377 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1379 return $this->mCategories
[$type];
1383 * Add an array of indicators, with their identifiers as array
1384 * keys and HTML contents as values.
1386 * In case of duplicate keys, existing values are overwritten.
1388 * @param array $indicators
1391 public function setIndicators( array $indicators ) {
1392 $this->mIndicators
= $indicators +
$this->mIndicators
;
1393 // Keep ordered by key
1394 ksort( $this->mIndicators
);
1398 * Get the indicators associated with this page.
1400 * The array will be internally ordered by item keys.
1402 * @return array Keys: identifiers, values: HTML contents
1405 public function getIndicators() {
1406 return $this->mIndicators
;
1410 * Adds help link with an icon via page indicators.
1411 * Link target can be overridden by a local message containing a wikilink:
1412 * the message key is: lowercase action or special page name + '-helppage'.
1413 * @param string $to Target MediaWiki.org page title or encoded URL.
1414 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1417 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1418 $this->addModuleStyles( 'mediawiki.helplink' );
1419 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1421 if ( $overrideBaseUrl ) {
1424 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1425 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1428 $link = Html
::rawElement(
1432 'target' => '_blank',
1433 'class' => 'mw-helplink',
1438 $this->setIndicators( [ 'mw-helplink' => $link ] );
1442 * Do not allow scripts which can be modified by wiki users to load on this page;
1443 * only allow scripts bundled with, or generated by, the software.
1444 * Site-wide styles are controlled by a config setting, since they can be
1445 * used to create a custom skin/theme, but not user-specific ones.
1447 * @todo this should be given a more accurate name
1449 public function disallowUserJs() {
1450 $this->reduceAllowedModules(
1451 ResourceLoaderModule
::TYPE_SCRIPTS
,
1452 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1455 // Site-wide styles are controlled by a config setting, see T73621
1456 // for background on why. User styles are never allowed.
1457 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1458 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1460 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1462 $this->reduceAllowedModules(
1463 ResourceLoaderModule
::TYPE_STYLES
,
1469 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1470 * @see ResourceLoaderModule::$origin
1471 * @param string $type ResourceLoaderModule TYPE_ constant
1472 * @return int ResourceLoaderModule ORIGIN_ class constant
1474 public function getAllowedModules( $type ) {
1475 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1476 return min( array_values( $this->mAllowedModules
) );
1478 return isset( $this->mAllowedModules
[$type] )
1479 ?
$this->mAllowedModules
[$type]
1480 : ResourceLoaderModule
::ORIGIN_ALL
;
1485 * Limit the highest level of CSS/JS untrustworthiness allowed.
1487 * If passed the same or a higher level than the current level of untrustworthiness set, the
1488 * level will remain unchanged.
1490 * @param string $type
1491 * @param int $level ResourceLoaderModule class constant
1493 public function reduceAllowedModules( $type, $level ) {
1494 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1498 * Prepend $text to the body HTML
1500 * @param string $text HTML
1502 public function prependHTML( $text ) {
1503 $this->mBodytext
= $text . $this->mBodytext
;
1507 * Append $text to the body HTML
1509 * @param string $text HTML
1511 public function addHTML( $text ) {
1512 $this->mBodytext
.= $text;
1516 * Shortcut for adding an Html::element via addHTML.
1520 * @param string $element
1521 * @param array $attribs
1522 * @param string $contents
1524 public function addElement( $element, array $attribs = [], $contents = '' ) {
1525 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1529 * Clear the body HTML
1531 public function clearHTML() {
1532 $this->mBodytext
= '';
1538 * @return string HTML
1540 public function getHTML() {
1541 return $this->mBodytext
;
1545 * Get/set the ParserOptions object to use for wikitext parsing
1547 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1548 * current ParserOption object. This parameter is deprecated since 1.31.
1549 * @return ParserOptions
1551 public function parserOptions( $options = null ) {
1552 if ( $options !== null ) {
1553 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1556 if ( $options !== null && !empty( $options->isBogus
) ) {
1557 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1558 // been changed somehow, and keep it if so.
1559 $anonPO = ParserOptions
::newFromAnon();
1560 $anonPO->setAllowUnsafeRawHtml( false );
1561 if ( !$options->matches( $anonPO ) ) {
1562 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1563 $options->isBogus
= false;
1567 if ( !$this->mParserOptions
) {
1568 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1569 // $wgUser isn't unstubbable yet, so don't try to get a
1570 // ParserOptions for it. And don't cache this ParserOptions
1572 $po = ParserOptions
::newFromAnon();
1573 $po->setAllowUnsafeRawHtml( false );
1574 $po->isBogus
= true;
1575 if ( $options !== null ) {
1576 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1581 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1582 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1585 if ( $options !== null && !empty( $options->isBogus
) ) {
1586 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1588 return wfSetVar( $this->mParserOptions
, null, true );
1590 return wfSetVar( $this->mParserOptions
, $options );
1595 * Set the revision ID which will be seen by the wiki text parser
1596 * for things such as embedded {{REVISIONID}} variable use.
1598 * @param int|null $revid An positive integer, or null
1599 * @return mixed Previous value
1601 public function setRevisionId( $revid ) {
1602 $val = is_null( $revid ) ?
null : intval( $revid );
1603 return wfSetVar( $this->mRevisionId
, $val );
1607 * Get the displayed revision ID
1611 public function getRevisionId() {
1612 return $this->mRevisionId
;
1616 * Set the timestamp of the revision which will be displayed. This is used
1617 * to avoid a extra DB call in Skin::lastModified().
1619 * @param string|null $timestamp
1620 * @return mixed Previous value
1622 public function setRevisionTimestamp( $timestamp ) {
1623 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1627 * Get the timestamp of displayed revision.
1628 * This will be null if not filled by setRevisionTimestamp().
1630 * @return string|null
1632 public function getRevisionTimestamp() {
1633 return $this->mRevisionTimestamp
;
1637 * Set the displayed file version
1639 * @param File|bool $file
1640 * @return mixed Previous value
1642 public function setFileVersion( $file ) {
1644 if ( $file instanceof File
&& $file->exists() ) {
1645 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1647 return wfSetVar( $this->mFileVersion
, $val, true );
1651 * Get the displayed file version
1653 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1655 public function getFileVersion() {
1656 return $this->mFileVersion
;
1660 * Get the templates used on this page
1662 * @return array (namespace => dbKey => revId)
1665 public function getTemplateIds() {
1666 return $this->mTemplateIds
;
1670 * Get the files used on this page
1672 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1675 public function getFileSearchOptions() {
1676 return $this->mImageTimeKeys
;
1680 * Convert wikitext to HTML and add it to the buffer
1681 * Default assumes that the current page title will be used.
1683 * @param string $text
1684 * @param bool $linestart Is this the start of a line?
1685 * @param bool $interface Is this text in the user interface language?
1686 * @throws MWException
1688 public function addWikiText( $text, $linestart = true, $interface = true ) {
1689 $title = $this->getTitle(); // Work around E_STRICT
1691 throw new MWException( 'Title is null' );
1693 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1697 * Add wikitext with a custom Title object
1699 * @param string $text Wikitext
1700 * @param Title &$title
1701 * @param bool $linestart Is this the start of a line?
1703 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1704 $this->addWikiTextTitle( $text, $title, $linestart );
1708 * Add wikitext with a custom Title object and tidy enabled.
1710 * @param string $text Wikitext
1711 * @param Title &$title
1712 * @param bool $linestart Is this the start of a line?
1714 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1715 $this->addWikiTextTitle( $text, $title, $linestart, true );
1719 * Add wikitext with tidy enabled
1721 * @param string $text Wikitext
1722 * @param bool $linestart Is this the start of a line?
1724 public function addWikiTextTidy( $text, $linestart = true ) {
1725 $title = $this->getTitle();
1726 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1730 * Add wikitext with a custom Title object
1732 * @param string $text Wikitext
1733 * @param Title $title
1734 * @param bool $linestart Is this the start of a line?
1735 * @param bool $tidy Whether to use tidy
1736 * @param bool $interface Whether it is an interface message
1737 * (for example disables conversion)
1739 public function addWikiTextTitle( $text, Title
$title, $linestart,
1740 $tidy = false, $interface = false
1744 $popts = $this->parserOptions();
1745 $oldTidy = $popts->setTidy( $tidy );
1746 $popts->setInterfaceMessage( (bool)$interface );
1748 $parserOutput = $wgParser->getFreshParser()->parse(
1749 $text, $title, $popts,
1750 $linestart, true, $this->mRevisionId
1753 $popts->setTidy( $oldTidy );
1755 $this->addParserOutput( $parserOutput, [
1756 'enableSectionEditLinks' => false,
1761 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1762 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1766 * @param ParserOutput $parserOutput
1768 public function addParserOutputMetadata( $parserOutput ) {
1769 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1770 $this->addCategoryLinks( $parserOutput->getCategories() );
1771 $this->setIndicators( $parserOutput->getIndicators() );
1772 $this->mNewSectionLink
= $parserOutput->getNewSection();
1773 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1775 if ( !$parserOutput->isCacheable() ) {
1776 $this->enableClientCache( false );
1778 $this->mNoGallery
= $parserOutput->getNoGallery();
1779 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1780 $this->addModules( $parserOutput->getModules() );
1781 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1782 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1783 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1784 $this->mPreventClickjacking
= $this->mPreventClickjacking
1785 ||
$parserOutput->preventClickjacking();
1787 // Template versioning...
1788 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1789 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1790 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1792 $this->mTemplateIds
[$ns] = $dbks;
1795 // File versioning...
1796 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1797 $this->mImageTimeKeys
[$dbk] = $data;
1800 // Hooks registered in the object
1801 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1802 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1803 list( $hookName, $data ) = $hookInfo;
1804 if ( isset( $parserOutputHooks[$hookName] ) ) {
1805 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1809 // Enable OOUI if requested via ParserOutput
1810 if ( $parserOutput->getEnableOOUI() ) {
1811 $this->enableOOUI();
1814 // Include parser limit report
1815 if ( !$this->limitReportJSData
) {
1816 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1819 // Link flags are ignored for now, but may in the future be
1820 // used to mark individual language links.
1822 // Avoid PHP 7.1 warning of passing $this by reference
1823 $outputPage = $this;
1824 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1825 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1827 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1828 // so that extensions may modify ParserOutput to toggle TOC.
1829 // This cannot be moved to addParserOutputText because that is not
1830 // called by EditPage for Preview.
1831 if ( $parserOutput->getTOCHTML() ) {
1832 $this->mEnableTOC
= true;
1837 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1838 * ParserOutput object, without any other metadata.
1841 * @param ParserOutput $parserOutput
1842 * @param array $poOptions Options to ParserOutput::getText()
1844 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1845 $this->addParserOutputText( $parserOutput, $poOptions );
1847 $this->addModules( $parserOutput->getModules() );
1848 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1849 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1851 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1855 * Add the HTML associated with a ParserOutput object, without any metadata.
1858 * @param ParserOutput $parserOutput
1859 * @param array $poOptions Options to ParserOutput::getText()
1861 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1862 $text = $parserOutput->getText( $poOptions );
1863 // Avoid PHP 7.1 warning of passing $this by reference
1864 $outputPage = $this;
1865 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1866 $this->addHTML( $text );
1870 * Add everything from a ParserOutput object.
1872 * @param ParserOutput $parserOutput
1873 * @param array $poOptions Options to ParserOutput::getText()
1875 function addParserOutput( $parserOutput, $poOptions = [] ) {
1876 $this->addParserOutputMetadata( $parserOutput );
1877 $this->addParserOutputText( $parserOutput, $poOptions );
1881 * Add the output of a QuickTemplate to the output buffer
1883 * @param QuickTemplate &$template
1885 public function addTemplate( &$template ) {
1886 $this->addHTML( $template->getHTML() );
1890 * Parse wikitext and return the HTML.
1892 * @param string $text
1893 * @param bool $linestart Is this the start of a line?
1894 * @param bool $interface Use interface language ($wgLang instead of
1895 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1896 * This also disables LanguageConverter.
1897 * @param Language $language Target language object, will override $interface
1898 * @throws MWException
1899 * @return string HTML
1901 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1904 if ( is_null( $this->getTitle() ) ) {
1905 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1908 $popts = $this->parserOptions();
1910 $popts->setInterfaceMessage( true );
1912 if ( $language !== null ) {
1913 $oldLang = $popts->setTargetLanguage( $language );
1916 $parserOutput = $wgParser->getFreshParser()->parse(
1917 $text, $this->getTitle(), $popts,
1918 $linestart, true, $this->mRevisionId
1922 $popts->setInterfaceMessage( false );
1924 if ( $language !== null ) {
1925 $popts->setTargetLanguage( $oldLang );
1928 return $parserOutput->getText( [
1929 'enableSectionEditLinks' => false,
1934 * Parse wikitext, strip paragraphs, and return the HTML.
1936 * @param string $text
1937 * @param bool $linestart Is this the start of a line?
1938 * @param bool $interface Use interface language ($wgLang instead of
1939 * $wgContLang) while parsing language sensitive magic
1940 * words like GRAMMAR and PLURAL
1941 * @return string HTML
1943 public function parseInline( $text, $linestart = true, $interface = false ) {
1944 $parsed = $this->parse( $text, $linestart, $interface );
1945 return Parser
::stripOuterParagraph( $parsed );
1949 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1951 * @param int $maxage Maximum cache time on the CDN, in seconds.
1953 public function setCdnMaxage( $maxage ) {
1954 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1958 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1960 * @param int $maxage Maximum cache time on the CDN, in seconds
1963 public function lowerCdnMaxage( $maxage ) {
1964 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1965 $this->setCdnMaxage( $this->mCdnMaxage
);
1969 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1971 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1972 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1973 * TTL is 90% of the age of the object, subject to the min and max.
1975 * @param string|int|float|bool|null $mtime Last-Modified timestamp
1976 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
1977 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1978 * @return int TTL in seconds
1981 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1982 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1983 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1985 if ( $mtime === null ||
$mtime === false ) {
1986 return $minTTL; // entity does not exist
1989 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1990 $adaptiveTTL = max( 0.9 * $age, $minTTL );
1991 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1993 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1995 return $adaptiveTTL;
1999 * Use enableClientCache(false) to force it to send nocache headers
2001 * @param bool $state
2005 public function enableClientCache( $state ) {
2006 return wfSetVar( $this->mEnableClientCache
, $state );
2010 * Get the list of cookies that will influence on the cache
2014 function getCacheVaryCookies() {
2016 if ( $cookies === null ) {
2017 $config = $this->getConfig();
2018 $cookies = array_merge(
2019 SessionManager
::singleton()->getVaryCookies(),
2023 $config->get( 'CacheVaryCookies' )
2025 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2031 * Check if the request has a cache-varying cookie header
2032 * If it does, it's very important that we don't allow public caching
2036 function haveCacheVaryCookies() {
2037 $request = $this->getRequest();
2038 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2039 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2040 wfDebug( __METHOD__
. ": found $cookieName\n" );
2044 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2049 * Add an HTTP header that will influence on the cache
2051 * @param string $header Header name
2052 * @param string[]|null $option Options for the Key header. See
2053 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2054 * for the list of valid options.
2056 public function addVaryHeader( $header, array $option = null ) {
2057 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2058 $this->mVaryHeader
[$header] = [];
2060 if ( !is_array( $option ) ) {
2063 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2067 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2068 * such as Accept-Encoding or Cookie
2072 public function getVaryHeader() {
2073 // If we vary on cookies, let's make sure it's always included here too.
2074 if ( $this->getCacheVaryCookies() ) {
2075 $this->addVaryHeader( 'Cookie' );
2078 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2079 $this->addVaryHeader( $header, $options );
2081 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2085 * Add an HTTP Link: header
2087 * @param string $header Header value
2089 public function addLinkHeader( $header ) {
2090 $this->mLinkHeader
[] = $header;
2094 * Return a Link: header. Based on the values of $mLinkHeader.
2098 public function getLinkHeader() {
2099 if ( !$this->mLinkHeader
) {
2103 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2107 * Get a complete Key header
2111 public function getKeyHeader() {
2112 $cvCookies = $this->getCacheVaryCookies();
2114 $cookiesOption = [];
2115 foreach ( $cvCookies as $cookieName ) {
2116 $cookiesOption[] = 'param=' . $cookieName;
2118 $this->addVaryHeader( 'Cookie', $cookiesOption );
2120 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2121 $this->addVaryHeader( $header, $options );
2125 foreach ( $this->mVaryHeader
as $header => $option ) {
2126 $newheader = $header;
2127 if ( is_array( $option ) && count( $option ) > 0 ) {
2128 $newheader .= ';' . implode( ';', $option );
2130 $headers[] = $newheader;
2132 $key = 'Key: ' . implode( ',', $headers );
2138 * T23672: Add Accept-Language to Vary and Key headers
2139 * if there's no 'variant' parameter existed in GET.
2142 * /w/index.php?title=Main_page should always be served; but
2143 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2145 function addAcceptLanguage() {
2146 $title = $this->getTitle();
2147 if ( !$title instanceof Title
) {
2151 $lang = $title->getPageLanguage();
2152 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2153 $variants = $lang->getVariants();
2155 foreach ( $variants as $variant ) {
2156 if ( $variant === $lang->getCode() ) {
2159 $aloption[] = 'substr=' . $variant;
2161 // IE and some other browsers use BCP 47 standards in
2162 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2163 // We should handle these too.
2164 $variantBCP47 = LanguageCode
::bcp47( $variant );
2165 if ( $variantBCP47 !== $variant ) {
2166 $aloption[] = 'substr=' . $variantBCP47;
2170 $this->addVaryHeader( 'Accept-Language', $aloption );
2175 * Set a flag which will cause an X-Frame-Options header appropriate for
2176 * edit pages to be sent. The header value is controlled by
2177 * $wgEditPageFrameOptions.
2179 * This is the default for special pages. If you display a CSRF-protected
2180 * form on an ordinary view page, then you need to call this function.
2182 * @param bool $enable
2184 public function preventClickjacking( $enable = true ) {
2185 $this->mPreventClickjacking
= $enable;
2189 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2190 * This can be called from pages which do not contain any CSRF-protected
2193 public function allowClickjacking() {
2194 $this->mPreventClickjacking
= false;
2198 * Get the prevent-clickjacking flag
2203 public function getPreventClickjacking() {
2204 return $this->mPreventClickjacking
;
2208 * Get the X-Frame-Options header value (without the name part), or false
2209 * if there isn't one. This is used by Skin to determine whether to enable
2210 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2212 * @return string|false
2214 public function getFrameOptions() {
2215 $config = $this->getConfig();
2216 if ( $config->get( 'BreakFrames' ) ) {
2218 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2219 return $config->get( 'EditPageFrameOptions' );
2225 * Send cache control HTTP headers
2227 public function sendCacheControl() {
2228 $response = $this->getRequest()->response();
2229 $config = $this->getConfig();
2231 $this->addVaryHeader( 'Cookie' );
2232 $this->addAcceptLanguage();
2234 # don't serve compressed data to clients who can't handle it
2235 # maintain different caches for logged-in users and non-logged in ones
2236 $response->header( $this->getVaryHeader() );
2238 if ( $config->get( 'UseKeyHeader' ) ) {
2239 $response->header( $this->getKeyHeader() );
2242 if ( $this->mEnableClientCache
) {
2244 $config->get( 'UseSquid' ) &&
2245 !$response->hasCookies() &&
2246 !SessionManager
::getGlobalSession()->isPersistent() &&
2247 !$this->isPrintable() &&
2248 $this->mCdnMaxage
!= 0 &&
2249 !$this->haveCacheVaryCookies()
2251 if ( $config->get( 'UseESI' ) ) {
2252 # We'll purge the proxy cache explicitly, but require end user agents
2253 # to revalidate against the proxy on each visit.
2254 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2255 wfDebug( __METHOD__
.
2256 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2257 # start with a shorter timeout for initial testing
2258 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2260 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2261 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2263 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2265 # We'll purge the proxy cache for anons explicitly, but require end user agents
2266 # to revalidate against the proxy on each visit.
2267 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2268 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2269 wfDebug( __METHOD__
.
2270 ": local proxy caching; {$this->mLastModified} **", 'private' );
2271 # start with a shorter timeout for initial testing
2272 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2273 $response->header( "Cache-Control: " .
2274 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2277 # We do want clients to cache if they can, but they *must* check for updates
2278 # on revisiting the page.
2279 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2280 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2281 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2283 if ( $this->mLastModified
) {
2284 $response->header( "Last-Modified: {$this->mLastModified}" );
2287 wfDebug( __METHOD__
. ": no caching **", 'private' );
2289 # In general, the absence of a last modified header should be enough to prevent
2290 # the client from using its cache. We send a few other things just to make sure.
2291 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2292 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2293 $response->header( 'Pragma: no-cache' );
2298 * Finally, all the text has been munged and accumulated into
2299 * the object, let's actually output it:
2301 * @param bool $return Set to true to get the result as a string rather than sending it
2302 * @return string|null
2304 * @throws FatalError
2305 * @throws MWException
2307 public function output( $return = false ) {
2310 if ( $this->mDoNothing
) {
2311 return $return ?
'' : null;
2314 $response = $this->getRequest()->response();
2315 $config = $this->getConfig();
2317 if ( $this->mRedirect
!= '' ) {
2318 # Standards require redirect URLs to be absolute
2319 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2321 $redirect = $this->mRedirect
;
2322 $code = $this->mRedirectCode
;
2324 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2325 if ( $code == '301' ||
$code == '303' ) {
2326 if ( !$config->get( 'DebugRedirects' ) ) {
2327 $response->statusHeader( $code );
2329 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2331 if ( $config->get( 'VaryOnXFP' ) ) {
2332 $this->addVaryHeader( 'X-Forwarded-Proto' );
2334 $this->sendCacheControl();
2336 $response->header( "Content-Type: text/html; charset=utf-8" );
2337 if ( $config->get( 'DebugRedirects' ) ) {
2338 $url = htmlspecialchars( $redirect );
2339 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2340 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2341 print "</body>\n</html>\n";
2343 $response->header( 'Location: ' . $redirect );
2347 return $return ?
'' : null;
2348 } elseif ( $this->mStatusCode
) {
2349 $response->statusHeader( $this->mStatusCode
);
2352 # Buffer output; final headers may depend on later processing
2355 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2356 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2358 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2359 // jQuery etc. can work correctly.
2360 $response->header( 'X-UA-Compatible: IE=Edge' );
2362 if ( !$this->mArticleBodyOnly
) {
2363 $sk = $this->getSkin();
2365 if ( $sk->shouldPreloadLogo() ) {
2366 $this->addLogoPreloadLinkHeaders();
2370 $linkHeader = $this->getLinkHeader();
2371 if ( $linkHeader ) {
2372 $response->header( $linkHeader );
2375 // Prevent framing, if requested
2376 $frameOptions = $this->getFrameOptions();
2377 if ( $frameOptions ) {
2378 $response->header( "X-Frame-Options: $frameOptions" );
2381 if ( $this->mArticleBodyOnly
) {
2382 echo $this->mBodytext
;
2384 // Enable safe mode if requested
2385 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2386 $this->disallowUserJs();
2389 $sk = $this->getSkin();
2390 foreach ( $sk->getDefaultModules() as $group ) {
2391 $this->addModules( $group );
2394 MWDebug
::addModules( $this );
2396 // Avoid PHP 7.1 warning of passing $this by reference
2397 $outputPage = $this;
2398 // Hook that allows last minute changes to the output page, e.g.
2399 // adding of CSS or Javascript by extensions.
2400 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2404 } catch ( Exception
$e ) {
2405 ob_end_clean(); // bug T129657
2411 // This hook allows last minute changes to final overall output by modifying output buffer
2412 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2413 } catch ( Exception
$e ) {
2414 ob_end_clean(); // bug T129657
2418 $this->sendCacheControl();
2421 return ob_get_clean();
2429 * Prepare this object to display an error page; disable caching and
2430 * indexing, clear the current text and redirect, set the page's title
2431 * and optionally an custom HTML title (content of the "<title>" tag).
2433 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2434 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2435 * optional, if not passed the "<title>" attribute will be
2436 * based on $pageTitle
2438 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2439 $this->setPageTitle( $pageTitle );
2440 if ( $htmlTitle !== false ) {
2441 $this->setHTMLTitle( $htmlTitle );
2443 $this->setRobotPolicy( 'noindex,nofollow' );
2444 $this->setArticleRelated( false );
2445 $this->enableClientCache( false );
2446 $this->mRedirect
= '';
2447 $this->clearSubtitle();
2452 * Output a standard error page
2454 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2455 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2456 * showErrorPage( 'titlemsg', $messageObject );
2457 * showErrorPage( $titleMessageObject, $messageObject );
2459 * @param string|Message $title Message key (string) for page title, or a Message object
2460 * @param string|Message $msg Message key (string) for page text, or a Message object
2461 * @param array $params Message parameters; ignored if $msg is a Message object
2463 public function showErrorPage( $title, $msg, $params = [] ) {
2464 if ( !$title instanceof Message
) {
2465 $title = $this->msg( $title );
2468 $this->prepareErrorPage( $title );
2470 if ( $msg instanceof Message
) {
2471 if ( $params !== [] ) {
2472 trigger_error( 'Argument ignored: $params. The message parameters argument '
2473 . 'is discarded when the $msg argument is a Message object instead of '
2474 . 'a string.', E_USER_NOTICE
);
2476 $this->addHTML( $msg->parseAsBlock() );
2478 $this->addWikiMsgArray( $msg, $params );
2481 $this->returnToMain();
2485 * Output a standard permission error page
2487 * @param array $errors Error message keys or [key, param...] arrays
2488 * @param string $action Action that was denied or null if unknown
2490 public function showPermissionsErrorPage( array $errors, $action = null ) {
2491 foreach ( $errors as $key => $error ) {
2492 $errors[$key] = (array)$error;
2495 // For some action (read, edit, create and upload), display a "login to do this action"
2496 // error if all of the following conditions are met:
2497 // 1. the user is not logged in
2498 // 2. the only error is insufficient permissions (i.e. no block or something else)
2499 // 3. the error can be avoided simply by logging in
2500 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2501 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2502 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2503 && ( User
::groupHasPermission( 'user', $action )
2504 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2506 $displayReturnto = null;
2508 # Due to T34276, if a user does not have read permissions,
2509 # $this->getTitle() will just give Special:Badtitle, which is
2510 # not especially useful as a returnto parameter. Use the title
2511 # from the request instead, if there was one.
2512 $request = $this->getRequest();
2513 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2514 if ( $action == 'edit' ) {
2515 $msg = 'whitelistedittext';
2516 $displayReturnto = $returnto;
2517 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2518 $msg = 'nocreatetext';
2519 } elseif ( $action == 'upload' ) {
2520 $msg = 'uploadnologintext';
2522 $msg = 'loginreqpagetext';
2523 $displayReturnto = Title
::newMainPage();
2529 $query['returnto'] = $returnto->getPrefixedText();
2531 if ( !$request->wasPosted() ) {
2532 $returntoquery = $request->getValues();
2533 unset( $returntoquery['title'] );
2534 unset( $returntoquery['returnto'] );
2535 unset( $returntoquery['returntoquery'] );
2536 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2539 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2540 $loginLink = $linkRenderer->makeKnownLink(
2541 SpecialPage
::getTitleFor( 'Userlogin' ),
2542 $this->msg( 'loginreqlink' )->text(),
2547 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2548 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2550 # Don't return to a page the user can't read otherwise
2551 # we'll end up in a pointless loop
2552 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2553 $this->returnToMain( null, $displayReturnto );
2556 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2557 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2562 * Display an error page indicating that a given version of MediaWiki is
2563 * required to use it
2565 * @param mixed $version The version of MediaWiki needed to use the page
2567 public function versionRequired( $version ) {
2568 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2570 $this->addWikiMsg( 'versionrequiredtext', $version );
2571 $this->returnToMain();
2575 * Format a list of error messages
2577 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2578 * @param string $action Action that was denied or null if unknown
2579 * @return string The wikitext error-messages, formatted into a list.
2581 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2582 if ( $action == null ) {
2583 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2585 $action_desc = $this->msg( "action-$action" )->plain();
2587 'permissionserrorstext-withaction',
2590 )->plain() . "\n\n";
2593 if ( count( $errors ) > 1 ) {
2594 $text .= '<ul class="permissions-errors">' . "\n";
2596 foreach ( $errors as $error ) {
2598 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2603 $text .= "<div class=\"permissions-errors\">\n" .
2604 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2612 * Show a warning about replica DB lag
2614 * If the lag is higher than $wgSlaveLagCritical seconds,
2615 * then the warning is a bit more obvious. If the lag is
2616 * lower than $wgSlaveLagWarning, then no warning is shown.
2618 * @param int $lag Slave lag
2620 public function showLagWarning( $lag ) {
2621 $config = $this->getConfig();
2622 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2623 $lag = floor( $lag ); // floor to avoid nano seconds to display
2624 $message = $lag < $config->get( 'SlaveLagCritical' )
2627 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2628 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2632 public function showFatalError( $message ) {
2633 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2635 $this->addHTML( $message );
2638 public function showUnexpectedValueError( $name, $val ) {
2639 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2642 public function showFileCopyError( $old, $new ) {
2643 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2646 public function showFileRenameError( $old, $new ) {
2647 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2650 public function showFileDeleteError( $name ) {
2651 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2654 public function showFileNotFoundError( $name ) {
2655 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2659 * Add a "return to" link pointing to a specified title
2661 * @param Title $title Title to link
2662 * @param array $query Query string parameters
2663 * @param string $text Text of the link (input is not escaped)
2664 * @param array $options Options array to pass to Linker
2666 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2667 $linkRenderer = MediaWikiServices
::getInstance()
2668 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2669 $link = $this->msg( 'returnto' )->rawParams(
2670 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2671 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2675 * Add a "return to" link pointing to a specified title,
2676 * or the title indicated in the request, or else the main page
2678 * @param mixed $unused
2679 * @param Title|string $returnto Title or String to return to
2680 * @param string $returntoquery Query string for the return to link
2682 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2683 if ( $returnto == null ) {
2684 $returnto = $this->getRequest()->getText( 'returnto' );
2687 if ( $returntoquery == null ) {
2688 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2691 if ( $returnto === '' ) {
2692 $returnto = Title
::newMainPage();
2695 if ( is_object( $returnto ) ) {
2696 $titleObj = $returnto;
2698 $titleObj = Title
::newFromText( $returnto );
2700 // We don't want people to return to external interwiki. That
2701 // might potentially be used as part of a phishing scheme
2702 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2703 $titleObj = Title
::newMainPage();
2706 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2709 private function getRlClientContext() {
2710 if ( !$this->rlClientContext
) {
2711 $query = ResourceLoader
::makeLoaderQuery(
2712 [], // modules; not relevant
2713 $this->getLanguage()->getCode(),
2714 $this->getSkin()->getSkinName(),
2715 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2716 null, // version; not relevant
2717 ResourceLoader
::inDebugMode(),
2718 null, // only; not relevant
2719 $this->isPrintable(),
2720 $this->getRequest()->getBool( 'handheld' )
2722 $this->rlClientContext
= new ResourceLoaderContext(
2723 $this->getResourceLoader(),
2724 new FauxRequest( $query )
2727 return $this->rlClientContext
;
2731 * Call this to freeze the module queue and JS config and create a formatter.
2733 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2734 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2735 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2736 * the module filters retroactively. Skins and extension hooks may also add modules until very
2737 * late in the request lifecycle.
2739 * @return ResourceLoaderClientHtml
2741 public function getRlClient() {
2742 if ( !$this->rlClient
) {
2743 $context = $this->getRlClientContext();
2744 $rl = $this->getResourceLoader();
2745 $this->addModules( [
2749 $this->addModuleStyles( [
2754 $this->getSkin()->setupSkinUserCss( $this );
2756 // Prepare exempt modules for buildExemptModules()
2757 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2759 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2761 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2762 // Separate user-specific batch for improved cache-hit ratio.
2763 $userBatch = [ 'user.styles', 'user' ];
2764 $siteBatch = array_diff( $moduleStyles, $userBatch );
2765 $dbr = wfGetDB( DB_REPLICA
);
2766 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2767 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2769 // Filter out modules handled by buildExemptModules()
2770 $moduleStyles = array_filter( $moduleStyles,
2771 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2772 $module = $rl->getModule( $name );
2774 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2775 $exemptStates[$name] = 'ready';
2776 // Special case in buildExemptModules()
2779 $group = $module->getGroup();
2780 if ( isset( $exemptGroups[$group] ) ) {
2781 $exemptStates[$name] = 'ready';
2782 if ( !$module->isKnownEmpty( $context ) ) {
2783 // E.g. Don't output empty <styles>
2784 $exemptGroups[$group][] = $name;
2792 $this->rlExemptStyleModules
= $exemptGroups;
2794 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2795 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2796 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2797 if ( !$isUserModuleFiltered ) {
2798 // Manually handled by getBottomScripts()
2799 $userModule = $rl->getModule( 'user' );
2800 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2803 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2806 $rlClient = new ResourceLoaderClientHtml( $context, [
2807 'target' => $this->getTarget(),
2809 $rlClient->setConfig( $this->getJSVars() );
2810 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2811 $rlClient->setModuleStyles( $moduleStyles );
2812 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2813 $rlClient->setExemptStates( $exemptStates );
2814 $this->rlClient
= $rlClient;
2816 return $this->rlClient
;
2820 * @param Skin $sk The given Skin
2821 * @param bool $includeStyle Unused
2822 * @return string The doctype, opening "<html>", and head element.
2824 public function headElement( Skin
$sk, $includeStyle = true ) {
2827 $userdir = $this->getLanguage()->getDir();
2828 $sitedir = $wgContLang->getDir();
2831 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2832 $this->getRlClient()->getDocumentAttributes(),
2833 $sk->getHtmlElementAttributes()
2835 $pieces[] = Html
::openElement( 'head' );
2837 if ( $this->getHTMLTitle() == '' ) {
2838 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2841 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2842 // Add <meta charset="UTF-8">
2843 // This should be before <title> since it defines the charset used by
2844 // text including the text inside <title>.
2845 // The spec recommends defining XHTML5's charset using the XML declaration
2847 // Our XML declaration is output by Html::htmlHeader.
2848 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2849 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2850 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2853 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2854 $pieces[] = $this->getRlClient()->getHeadHtml();
2855 $pieces[] = $this->buildExemptModules();
2856 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2857 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2859 // Use an IE conditional comment to serve the script only to old IE
2860 $pieces[] = '<!--[if lt IE 9]>' .
2861 ResourceLoaderClientHtml
::makeLoad(
2862 ResourceLoaderContext
::newDummyContext(),
2864 ResourceLoaderModule
::TYPE_SCRIPTS
,
2869 $pieces[] = Html
::closeElement( 'head' );
2871 $bodyClasses = $this->mAdditionalBodyClasses
;
2872 $bodyClasses[] = 'mediawiki';
2874 # Classes for LTR/RTL directionality support
2875 $bodyClasses[] = $userdir;
2876 $bodyClasses[] = "sitedir-$sitedir";
2878 $underline = $this->getUser()->getOption( 'underline' );
2879 if ( $underline < 2 ) {
2880 // The following classes can be used here:
2881 // * mw-underline-always
2882 // * mw-underline-never
2883 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2886 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2887 # A <body> class is probably not the best way to do this . . .
2888 $bodyClasses[] = 'capitalize-all-nouns';
2891 // Parser feature migration class
2892 // The idea is that this will eventually be removed, after the wikitext
2893 // which requires it is cleaned up.
2894 $bodyClasses[] = 'mw-hide-empty-elt';
2896 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2897 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2899 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2902 // While the implode() is not strictly needed, it's used for backwards compatibility
2903 // (this used to be built as a string and hooks likely still expect that).
2904 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2906 // Allow skins and extensions to add body attributes they need
2907 $sk->addToBodyAttributes( $this, $bodyAttrs );
2908 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2910 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2912 return self
::combineWrappedStrings( $pieces );
2916 * Get a ResourceLoader object associated with this OutputPage
2918 * @return ResourceLoader
2920 public function getResourceLoader() {
2921 if ( is_null( $this->mResourceLoader
) ) {
2922 $this->mResourceLoader
= new ResourceLoader(
2924 LoggerFactory
::getInstance( 'resourceloader' )
2927 return $this->mResourceLoader
;
2931 * Explicily load or embed modules on a page.
2933 * @param array|string $modules One or more module names
2934 * @param string $only ResourceLoaderModule TYPE_ class constant
2935 * @param array $extraQuery [optional] Array with extra query parameters for the request
2936 * @return string|WrappedStringList HTML
2938 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2939 // Apply 'target' and 'origin' filters
2940 $modules = $this->filterModules( (array)$modules, null, $only );
2942 return ResourceLoaderClientHtml
::makeLoad(
2943 $this->getRlClientContext(),
2951 * Combine WrappedString chunks and filter out empty ones
2953 * @param array $chunks
2954 * @return string|WrappedStringList HTML
2956 protected static function combineWrappedStrings( array $chunks ) {
2957 // Filter out empty values
2958 $chunks = array_filter( $chunks, 'strlen' );
2959 return WrappedString
::join( "\n", $chunks );
2962 private function isUserJsPreview() {
2963 return $this->getConfig()->get( 'AllowUserJs' )
2964 && $this->getTitle()
2965 && $this->getTitle()->isUserJsConfigPage()
2966 && $this->userCanPreview();
2969 protected function isUserCssPreview() {
2970 return $this->getConfig()->get( 'AllowUserCss' )
2971 && $this->getTitle()
2972 && $this->getTitle()->isUserCssConfigPage()
2973 && $this->userCanPreview();
2977 * JS stuff to put at the bottom of the `<body>`.
2978 * These are legacy scripts ($this->mScripts), and user JS.
2980 * @return string|WrappedStringList HTML
2982 public function getBottomScripts() {
2984 $chunks[] = $this->getRlClient()->getBodyHtml();
2986 // Legacy non-ResourceLoader scripts
2987 $chunks[] = $this->mScripts
;
2989 // Exempt 'user' module
2990 // - May need excludepages for live preview. (T28283)
2991 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2992 // ensures execution is scheduled after the "site" module.
2993 // - Don't load if module state is already resolved as "ready".
2994 if ( $this->rlUserModuleState
=== 'loading' ) {
2995 if ( $this->isUserJsPreview() ) {
2996 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2997 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2999 $chunks[] = ResourceLoader
::makeInlineScript(
3000 Xml
::encodeJsCall( 'mw.loader.using', [
3004 . Xml
::encodeJsCall( '$.globalEval', [
3005 $this->getRequest()->getText( 'wpTextbox1' )
3011 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3012 // asynchronously and may arrive *after* the inline script here. So the previewed code
3013 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3014 // Similarly, when previewing ./common.js and the user module does arrive first,
3015 // it will arrive without common.js and the inline script runs after.
3016 // Thus running common after the excluded subpage.
3019 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3023 if ( $this->limitReportJSData
) {
3024 $chunks[] = ResourceLoader
::makeInlineScript(
3025 ResourceLoader
::makeConfigSetScript(
3026 [ 'wgPageParseReport' => $this->limitReportJSData
]
3031 return self
::combineWrappedStrings( $chunks );
3035 * Get the javascript config vars to include on this page
3037 * @return array Array of javascript config vars
3040 public function getJsConfigVars() {
3041 return $this->mJsConfigVars
;
3045 * Add one or more variables to be set in mw.config in JavaScript
3047 * @param string|array $keys Key or array of key/value pairs
3048 * @param mixed $value [optional] Value of the configuration variable
3050 public function addJsConfigVars( $keys, $value = null ) {
3051 if ( is_array( $keys ) ) {
3052 foreach ( $keys as $key => $value ) {
3053 $this->mJsConfigVars
[$key] = $value;
3058 $this->mJsConfigVars
[$keys] = $value;
3062 * Get an array containing the variables to be set in mw.config in JavaScript.
3064 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3065 * - in other words, page-independent/site-wide variables (without state).
3066 * You will only be adding bloat to the html page and causing page caches to
3067 * have to be purged on configuration changes.
3070 public function getJSVars() {
3075 $canonicalSpecialPageName = false; # T23115
3077 $title = $this->getTitle();
3078 $ns = $title->getNamespace();
3079 $canonicalNamespace = MWNamespace
::exists( $ns )
3080 ? MWNamespace
::getCanonicalName( $ns )
3081 : $title->getNsText();
3083 $sk = $this->getSkin();
3084 // Get the relevant title so that AJAX features can use the correct page name
3085 // when making API requests from certain special pages (T36972).
3086 $relevantTitle = $sk->getRelevantTitle();
3087 $relevantUser = $sk->getRelevantUser();
3089 if ( $ns == NS_SPECIAL
) {
3090 list( $canonicalSpecialPageName, /*...*/ ) =
3091 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3092 } elseif ( $this->canUseWikiPage() ) {
3093 $wikiPage = $this->getWikiPage();
3094 $curRevisionId = $wikiPage->getLatest();
3095 $articleId = $wikiPage->getId();
3098 $lang = $title->getPageViewLanguage();
3100 // Pre-process information
3101 $separatorTransTable = $lang->separatorTransformTable();
3102 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3103 $compactSeparatorTransTable = [
3104 implode( "\t", array_keys( $separatorTransTable ) ),
3105 implode( "\t", $separatorTransTable ),
3107 $digitTransTable = $lang->digitTransformTable();
3108 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3109 $compactDigitTransTable = [
3110 implode( "\t", array_keys( $digitTransTable ) ),
3111 implode( "\t", $digitTransTable ),
3114 $user = $this->getUser();
3117 'wgCanonicalNamespace' => $canonicalNamespace,
3118 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3119 'wgNamespaceNumber' => $title->getNamespace(),
3120 'wgPageName' => $title->getPrefixedDBkey(),
3121 'wgTitle' => $title->getText(),
3122 'wgCurRevisionId' => $curRevisionId,
3123 'wgRevisionId' => (int)$this->getRevisionId(),
3124 'wgArticleId' => $articleId,
3125 'wgIsArticle' => $this->isArticle(),
3126 'wgIsRedirect' => $title->isRedirect(),
3127 'wgAction' => Action
::getActionName( $this->getContext() ),
3128 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3129 'wgUserGroups' => $user->getEffectiveGroups(),
3130 'wgCategories' => $this->getCategories(),
3131 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3132 'wgPageContentLanguage' => $lang->getCode(),
3133 'wgPageContentModel' => $title->getContentModel(),
3134 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3135 'wgDigitTransformTable' => $compactDigitTransTable,
3136 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3137 'wgMonthNames' => $lang->getMonthNamesArray(),
3138 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3139 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3140 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3141 'wgRequestId' => WebRequest
::getRequestId(),
3144 if ( $user->isLoggedIn() ) {
3145 $vars['wgUserId'] = $user->getId();
3146 $vars['wgUserEditCount'] = $user->getEditCount();
3147 $userReg = $user->getRegistration();
3148 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3149 // Get the revision ID of the oldest new message on the user's talk
3150 // page. This can be used for constructing new message alerts on
3152 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3155 if ( $wgContLang->hasVariants() ) {
3156 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3158 // Same test as SkinTemplate
3159 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3160 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3162 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3163 && $relevantTitle->quickUserCan( 'edit', $user )
3164 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3166 foreach ( $title->getRestrictionTypes() as $type ) {
3167 // Following keys are set in $vars:
3168 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3169 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3172 if ( $title->isMainPage() ) {
3173 $vars['wgIsMainPage'] = true;
3176 if ( $this->mRedirectedFrom
) {
3177 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3180 if ( $relevantUser ) {
3181 $vars['wgRelevantUserName'] = $relevantUser->getName();
3184 // Allow extensions to add their custom variables to the mw.config map.
3185 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3186 // page-dependant but site-wide (without state).
3187 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3188 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3190 // Merge in variables from addJsConfigVars last
3191 return array_merge( $vars, $this->getJsConfigVars() );
3195 * To make it harder for someone to slip a user a fake
3196 * user-JavaScript or user-CSS preview, a random token
3197 * is associated with the login session. If it's not
3198 * passed back with the preview request, we won't render
3203 public function userCanPreview() {
3204 $request = $this->getRequest();
3206 $request->getVal( 'action' ) !== 'submit' ||
3207 !$request->getCheck( 'wpPreview' ) ||
3208 !$request->wasPosted()
3213 $user = $this->getUser();
3215 if ( !$user->isLoggedIn() ) {
3216 // Anons have predictable edit tokens
3219 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3223 $title = $this->getTitle();
3225 !$title->isUserJsConfigPage()
3226 && !$title->isUserCssConfigPage()
3230 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3231 // Don't execute another user's CSS or JS on preview (T85855)
3235 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3236 if ( count( $errors ) !== 0 ) {
3244 * @return array Array in format "link name or number => 'link html'".
3246 public function getHeadLinksArray() {
3250 $config = $this->getConfig();
3252 $canonicalUrl = $this->mCanonicalUrl
;
3254 $tags['meta-generator'] = Html
::element( 'meta', [
3255 'name' => 'generator',
3256 'content' => "MediaWiki $wgVersion",
3259 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3260 // Per https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values
3261 // fallbacks should come before the primary value so we need to reverse the array.
3262 foreach ( array_reverse( (array)$config->get( 'ReferrerPolicy' ) ) as $i => $policy ) {
3263 $tags["meta-referrer-$i"] = Html
::element( 'meta', [
3264 'name' => 'referrer',
3265 'content' => $policy,
3270 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3271 if ( $p !== 'index,follow' ) {
3272 // http://www.robotstxt.org/wc/meta-user.html
3273 // Only show if it's different from the default robots policy
3274 $tags['meta-robots'] = Html
::element( 'meta', [
3280 foreach ( $this->mMetatags
as $tag ) {
3281 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3283 $tag[0] = substr( $tag[0], 5 );
3284 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3289 $tagName = "meta-{$tag[0]}";
3290 if ( isset( $tags[$tagName] ) ) {
3291 $tagName .= $tag[1];
3293 $tags[$tagName] = Html
::element( 'meta',
3296 'content' => $tag[1]
3301 foreach ( $this->mLinktags
as $tag ) {
3302 $tags[] = Html
::element( 'link', $tag );
3305 # Universal edit button
3306 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3307 $user = $this->getUser();
3308 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3309 && ( $this->getTitle()->exists() ||
3310 $this->getTitle()->quickUserCan( 'create', $user ) )
3312 // Original UniversalEditButton
3313 $msg = $this->msg( 'edit' )->text();
3314 $tags['universal-edit-button'] = Html
::element( 'link', [
3315 'rel' => 'alternate',
3316 'type' => 'application/x-wiki',
3318 'href' => $this->getTitle()->getEditURL(),
3320 // Alternate edit link
3321 $tags['alternative-edit'] = Html
::element( 'link', [
3324 'href' => $this->getTitle()->getEditURL(),
3329 # Generally the order of the favicon and apple-touch-icon links
3330 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3331 # uses whichever one appears later in the HTML source. Make sure
3332 # apple-touch-icon is specified first to avoid this.
3333 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3334 $tags['apple-touch-icon'] = Html
::element( 'link', [
3335 'rel' => 'apple-touch-icon',
3336 'href' => $config->get( 'AppleTouchIcon' )
3340 if ( $config->get( 'Favicon' ) !== false ) {
3341 $tags['favicon'] = Html
::element( 'link', [
3342 'rel' => 'shortcut icon',
3343 'href' => $config->get( 'Favicon' )
3347 # OpenSearch description link
3348 $tags['opensearch'] = Html
::element( 'link', [
3350 'type' => 'application/opensearchdescription+xml',
3351 'href' => wfScript( 'opensearch_desc' ),
3352 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3355 # Real Simple Discovery link, provides auto-discovery information
3356 # for the MediaWiki API (and potentially additional custom API
3357 # support such as WordPress or Twitter-compatible APIs for a
3358 # blogging extension, etc)
3359 $tags['rsd'] = Html
::element( 'link', [
3361 'type' => 'application/rsd+xml',
3362 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3363 // Whether RSD accepts relative or protocol-relative URLs is completely
3364 // undocumented, though.
3365 'href' => wfExpandUrl( wfAppendQuery(
3367 [ 'action' => 'rsd' ] ),
3373 if ( !$config->get( 'DisableLangConversion' ) ) {
3374 $lang = $this->getTitle()->getPageLanguage();
3375 if ( $lang->hasVariants() ) {
3376 $variants = $lang->getVariants();
3377 foreach ( $variants as $variant ) {
3378 $tags["variant-$variant"] = Html
::element( 'link', [
3379 'rel' => 'alternate',
3380 'hreflang' => LanguageCode
::bcp47( $variant ),
3381 'href' => $this->getTitle()->getLocalURL(
3382 [ 'variant' => $variant ] )
3386 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3387 $tags["variant-x-default"] = Html
::element( 'link', [
3388 'rel' => 'alternate',
3389 'hreflang' => 'x-default',
3390 'href' => $this->getTitle()->getLocalURL() ] );
3395 if ( $this->copyrightUrl
!== null ) {
3396 $copyright = $this->copyrightUrl
;
3399 if ( $config->get( 'RightsPage' ) ) {
3400 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3403 $copyright = $copy->getLocalURL();
3407 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3408 $copyright = $config->get( 'RightsUrl' );
3413 $tags['copyright'] = Html
::element( 'link', [
3415 'href' => $copyright ]
3420 if ( $config->get( 'Feed' ) ) {
3423 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3424 # Use the page name for the title. In principle, this could
3425 # lead to issues with having the same name for different feeds
3426 # corresponding to the same page, but we can't avoid that at
3429 $feedLinks[] = $this->feedLink(
3432 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3434 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3439 # Recent changes feed should appear on every page (except recentchanges,
3440 # that would be redundant). Put it after the per-page feed to avoid
3441 # changing existing behavior. It's still available, probably via a
3442 # menu in your browser. Some sites might have a different feed they'd
3443 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3444 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3445 # If so, use it instead.
3446 $sitename = $config->get( 'Sitename' );
3447 if ( $config->get( 'OverrideSiteFeed' ) ) {
3448 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3449 // Note, this->feedLink escapes the url.
3450 $feedLinks[] = $this->feedLink(
3453 $this->msg( "site-{$type}-feed", $sitename )->text()
3456 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3457 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3458 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3459 $feedLinks[] = $this->feedLink(
3461 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3462 # For grep: 'site-rss-feed', 'site-atom-feed'
3463 $this->msg( "site-{$format}-feed", $sitename )->text()
3468 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3469 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3470 # use OutputPage::addFeedLink() instead.
3471 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3473 $tags +
= $feedLinks;
3477 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3478 if ( $canonicalUrl !== false ) {
3479 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3481 if ( $this->isArticleRelated() ) {
3482 // This affects all requests where "setArticleRelated" is true. This is
3483 // typically all requests that show content (query title, curid, oldid, diff),
3484 // and all wikipage actions (edit, delete, purge, info, history etc.).
3485 // It does not apply to File pages and Special pages.
3486 // 'history' and 'info' actions address page metadata rather than the page
3487 // content itself, so they may not be canonicalized to the view page url.
3488 // TODO: this ought to be better encapsulated in the Action class.
3489 $action = Action
::getActionName( $this->getContext() );
3490 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3491 $query = "action={$action}";
3495 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3497 $reqUrl = $this->getRequest()->getRequestURL();
3498 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3502 if ( $canonicalUrl !== false ) {
3503 $tags[] = Html
::element( 'link', [
3504 'rel' => 'canonical',
3505 'href' => $canonicalUrl
3513 * Generate a "<link rel/>" for a feed.
3515 * @param string $type Feed type
3516 * @param string $url URL to the feed
3517 * @param string $text Value of the "title" attribute
3518 * @return string HTML fragment
3520 private function feedLink( $type, $url, $text ) {
3521 return Html
::element( 'link', [
3522 'rel' => 'alternate',
3523 'type' => "application/$type+xml",
3530 * Add a local or specified stylesheet, with the given media options.
3531 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3533 * @param string $style URL to the file
3534 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3535 * @param string $condition For IE conditional comments, specifying an IE version
3536 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3538 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3541 $options['media'] = $media;
3544 $options['condition'] = $condition;
3547 $options['dir'] = $dir;
3549 $this->styles
[$style] = $options;
3553 * Adds inline CSS styles
3554 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3556 * @param mixed $style_css Inline CSS
3557 * @param string $flip Set to 'flip' to flip the CSS if needed
3559 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3560 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3561 # If wanted, and the interface is right-to-left, flip the CSS
3562 $style_css = CSSJanus
::transform( $style_css, true, false );
3564 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3568 * Build exempt modules and legacy non-ResourceLoader styles.
3570 * @return string|WrappedStringList HTML
3572 protected function buildExemptModules() {
3576 // Things that go after the ResourceLoaderDynamicStyles marker
3579 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3580 if ( $this->isUserCssPreview() ) {
3581 $append[] = $this->makeResourceLoaderLink(
3583 ResourceLoaderModule
::TYPE_STYLES
,
3584 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3587 // Load the previewed CSS. Janus it if needed.
3588 // User-supplied CSS is assumed to in the wiki's content language.
3589 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3590 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3591 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3593 $append[] = Html
::inlineStyle( $previewedCSS );
3596 // We want site, private and user styles to override dynamically added styles from
3597 // general modules, but we want dynamically added styles to override statically added
3598 // style modules. So the order has to be:
3599 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3600 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3601 // - ResourceLoaderDynamicStyles marker
3602 // - site/private/user styles
3604 // Add legacy styles added through addStyle()/addInlineStyle() here
3605 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3607 $chunks[] = Html
::element(
3609 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3612 $separateReq = [ 'site.styles', 'user.styles' ];
3613 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3614 // Combinable modules
3615 $chunks[] = $this->makeResourceLoaderLink(
3616 array_diff( $moduleNames, $separateReq ),
3617 ResourceLoaderModule
::TYPE_STYLES
3620 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3621 // These require their own dedicated request in order to support "@import"
3622 // syntax, which is incompatible with concatenation. (T147667, T37562)
3623 $chunks[] = $this->makeResourceLoaderLink( $name,
3624 ResourceLoaderModule
::TYPE_STYLES
3629 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3635 public function buildCssLinksArray() {
3638 foreach ( $this->styles
as $file => $options ) {
3639 $link = $this->styleLink( $file, $options );
3641 $links[$file] = $link;
3648 * Generate \<link\> tags for stylesheets
3650 * @param string $style URL to the file
3651 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3652 * @return string HTML fragment
3654 protected function styleLink( $style, array $options ) {
3655 if ( isset( $options['dir'] ) ) {
3656 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3661 if ( isset( $options['media'] ) ) {
3662 $media = self
::transformCssMedia( $options['media'] );
3663 if ( is_null( $media ) ) {
3670 if ( substr( $style, 0, 1 ) == '/' ||
3671 substr( $style, 0, 5 ) == 'http:' ||
3672 substr( $style, 0, 6 ) == 'https:' ) {
3675 $config = $this->getConfig();
3676 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3677 $config->get( 'StyleVersion' );
3680 $link = Html
::linkedStyle( $url, $media );
3682 if ( isset( $options['condition'] ) ) {
3683 $condition = htmlspecialchars( $options['condition'] );
3684 $link = "<!--[if $condition]>$link<![endif]-->";
3690 * Transform path to web-accessible static resource.
3692 * This is used to add a validation hash as query string.
3693 * This aids various behaviors:
3695 * - Put long Cache-Control max-age headers on responses for improved
3696 * cache performance.
3697 * - Get the correct version of a file as expected by the current page.
3698 * - Instantly get the updated version of a file after deployment.
3700 * Avoid using this for urls included in HTML as otherwise clients may get different
3701 * versions of a resource when navigating the site depending on when the page was cached.
3702 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3703 * an external stylesheet).
3706 * @param Config $config
3707 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3708 * @return string URL
3710 public static function transformResourcePath( Config
$config, $path ) {
3714 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3715 if ( $remotePathPrefix === '' ) {
3716 // The configured base path is required to be empty string for
3717 // wikis in the domain root
3720 $remotePath = $remotePathPrefix;
3722 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3723 // - Path is outside wgResourceBasePath, ignore.
3724 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3727 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3728 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3729 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3730 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3731 $uploadPath = $config->get( 'UploadPath' );
3732 if ( strpos( $path, $uploadPath ) === 0 ) {
3733 $localDir = $config->get( 'UploadDirectory' );
3734 $remotePathPrefix = $remotePath = $uploadPath;
3737 $path = RelPath
::getRelativePath( $path, $remotePath );
3738 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3742 * Utility method for transformResourceFilePath().
3744 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3747 * @param string $remotePathPrefix URL path prefix that points to $localPath
3748 * @param string $localPath File directory exposed at $remotePath
3749 * @param string $file Path to target file relative to $localPath
3750 * @return string URL
3752 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3753 $hash = md5_file( "$localPath/$file" );
3754 if ( $hash === false ) {
3755 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3758 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3762 * Transform "media" attribute based on request parameters
3764 * @param string $media Current value of the "media" attribute
3765 * @return string Modified value of the "media" attribute, or null to skip
3768 public static function transformCssMedia( $media ) {
3771 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3772 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3774 // Switch in on-screen display for media testing
3776 'printable' => 'print',
3777 'handheld' => 'handheld',
3779 foreach ( $switches as $switch => $targetMedia ) {
3780 if ( $wgRequest->getBool( $switch ) ) {
3781 if ( $media == $targetMedia ) {
3783 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3784 /* This regex will not attempt to understand a comma-separated media_query_list
3786 * Example supported values for $media:
3787 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3788 * Example NOT supported value for $media:
3789 * '3d-glasses, screen, print and resolution > 90dpi'
3791 * If it's a print request, we never want any kind of screen stylesheets
3792 * If it's a handheld request (currently the only other choice with a switch),
3793 * we don't want simple 'screen' but we might want screen queries that
3794 * have a max-width or something, so we'll pass all others on and let the
3795 * client do the query.
3797 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3808 * Add a wikitext-formatted message to the output.
3809 * This is equivalent to:
3811 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3813 public function addWikiMsg( /*...*/ ) {
3814 $args = func_get_args();
3815 $name = array_shift( $args );
3816 $this->addWikiMsgArray( $name, $args );
3820 * Add a wikitext-formatted message to the output.
3821 * Like addWikiMsg() except the parameters are taken as an array
3822 * instead of a variable argument list.
3824 * @param string $name
3825 * @param array $args
3827 public function addWikiMsgArray( $name, $args ) {
3828 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3832 * This function takes a number of message/argument specifications, wraps them in
3833 * some overall structure, and then parses the result and adds it to the output.
3835 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3836 * and so on. The subsequent arguments may be either
3837 * 1) strings, in which case they are message names, or
3838 * 2) arrays, in which case, within each array, the first element is the message
3839 * name, and subsequent elements are the parameters to that message.
3841 * Don't use this for messages that are not in the user's interface language.
3845 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3849 * $wgOut->addWikiText( "<div class='error'>\n"
3850 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3852 * The newline after the opening div is needed in some wikitext. See T21226.
3854 * @param string $wrap
3856 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3857 $msgSpecs = func_get_args();
3858 array_shift( $msgSpecs );
3859 $msgSpecs = array_values( $msgSpecs );
3861 foreach ( $msgSpecs as $n => $spec ) {
3862 if ( is_array( $spec ) ) {
3864 $name = array_shift( $args );
3865 if ( isset( $args['options'] ) ) {
3866 unset( $args['options'] );
3868 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3876 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3878 $this->addWikiText( $s );
3882 * Whether the output has a table of contents
3886 public function isTOCEnabled() {
3887 return $this->mEnableTOC
;
3891 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3894 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3896 public function enableSectionEditLinks( $flag = true ) {
3897 wfDeprecated( __METHOD__
, '1.31' );
3903 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3905 public function sectionEditLinksEnabled() {
3906 wfDeprecated( __METHOD__
, '1.31' );
3911 * Helper function to setup the PHP implementation of OOUI to use in this request.
3914 * @param String $skinName The Skin name to determine the correct OOUI theme
3915 * @param String $dir Language direction
3917 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3918 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3919 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
3920 // For example, 'OOUI\WikimediaUITheme'.
3921 $themeClass = "OOUI\\{$theme}Theme";
3922 OOUI\Theme
::setSingleton( new $themeClass() );
3923 OOUI\Element
::setDefaultDir( $dir );
3927 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3928 * MediaWiki and this OutputPage instance.
3932 public function enableOOUI() {
3934 strtolower( $this->getSkin()->getSkinName() ),
3935 $this->getLanguage()->getDir()
3937 $this->addModuleStyles( [
3938 'oojs-ui-core.styles',
3939 'oojs-ui.styles.indicators',
3940 'oojs-ui.styles.textures',
3941 'mediawiki.widgets.styles',
3942 'oojs-ui.styles.icons-content',
3943 'oojs-ui.styles.icons-alerts',
3944 'oojs-ui.styles.icons-interactions',
3949 * Add Link headers for preloading the wiki's logo.
3953 protected function addLogoPreloadLinkHeaders() {
3954 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3960 if ( !is_array( $logo ) ) {
3961 // No media queries required if we only have one variant
3962 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3966 if ( isset( $logo['svg'] ) ) {
3967 // No media queries required if we only have a 1x and svg variant
3968 // because all preload-capable browsers support SVGs
3969 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3973 foreach ( $logo as $dppx => $src ) {
3974 // Keys are in this format: "1.5x"
3975 $dppx = substr( $dppx, 0, -1 );
3976 $logosPerDppx[$dppx] = $src;
3979 // Because PHP can't have floats as array keys
3980 uksort( $logosPerDppx, function ( $a , $b ) {
3981 $a = floatval( $a );
3982 $b = floatval( $b );
3987 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3988 return ( $a < $b ) ?
-1 : 1;
3991 foreach ( $logosPerDppx as $dppx => $src ) {
3992 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3995 $logosCount = count( $logos );
3996 // Logic must match ResourceLoaderSkinModule:
3997 // - 1x applies to resolution < 1.5dppx
3998 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
3999 // - 2x applies to resolution >= 2dppx
4000 // Note that min-resolution and max-resolution are both inclusive.
4001 for ( $i = 0; $i < $logosCount; $i++
) {
4004 // min-resolution is ">=" (larger than or equal to)
4005 // "not min-resolution" is essentially "<"
4006 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4007 } elseif ( $i !== $logosCount - 1 ) {
4009 // Media query expressions can only apply "not" to the entire expression
4010 // (e.g. can't express ">= 1.5 and not >= 2).
4011 // Workaround: Use <= 1.9999 in place of < 2.
4012 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4013 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4014 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4017 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4020 $this->addLinkHeader(
4021 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query