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 bool Whether parser output should contain section edit links
293 private $mEnableSectionEditLinks = true;
296 * @var string|null The URL to send in a <link> element with rel=license
298 private $copyrightUrl;
300 /** @var array Profiling data */
301 private $limitReportJSData = [];
304 * Link: header contents
306 private $mLinkHeader = [];
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource $context
314 function __construct( IContextSource
$context ) {
315 $this->setContext( $context );
319 * Redirect to $url rather than displaying the normal page
322 * @param string $responsecode HTTP status code
324 public function redirect( $url, $responsecode = '302' ) {
325 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
326 $this->mRedirect
= str_replace( "\n", '', $url );
327 $this->mRedirectCode
= $responsecode;
331 * Get the URL to redirect to, or an empty string if not redirect URL set
335 public function getRedirect() {
336 return $this->mRedirect
;
340 * Set the copyright URL to send with the output.
341 * Empty string to omit, null to reset.
345 * @param string|null $url
347 public function setCopyrightUrl( $url ) {
348 $this->copyrightUrl
= $url;
352 * Set the HTTP status code to send with the output.
354 * @param int $statusCode
356 public function setStatusCode( $statusCode ) {
357 $this->mStatusCode
= $statusCode;
361 * Add a new "<meta>" tag
362 * To add an http-equiv meta tag, precede the name with "http:"
364 * @param string $name Name of the meta tag
365 * @param string $val Value of the meta tag
367 function addMeta( $name, $val ) {
368 array_push( $this->mMetatags
, [ $name, $val ] );
372 * Returns the current <meta> tags
377 public function getMetaTags() {
378 return $this->mMetatags
;
382 * Add a new \<link\> tag to the page header.
384 * Note: use setCanonicalUrl() for rel=canonical.
386 * @param array $linkarr Associative array of attributes.
388 function addLink( array $linkarr ) {
389 array_push( $this->mLinktags
, $linkarr );
393 * Returns the current <link> tags
398 public function getLinkTags() {
399 return $this->mLinktags
;
403 * Add a new \<link\> with "rel" attribute set to "meta"
405 * @param array $linkarr Associative array mapping attribute names to their
406 * values, both keys and values will be escaped, and the
407 * "rel" attribute will be automatically added
409 function addMetadataLink( array $linkarr ) {
410 $linkarr['rel'] = $this->getMetadataAttribute();
411 $this->addLink( $linkarr );
415 * Set the URL to be used for the <link rel=canonical>. This should be used
416 * in preference to addLink(), to avoid duplicate link tags.
419 function setCanonicalUrl( $url ) {
420 $this->mCanonicalUrl
= $url;
424 * Returns the URL to be used for the <link rel=canonical> if
428 * @return bool|string
430 public function getCanonicalUrl() {
431 return $this->mCanonicalUrl
;
435 * Get the value of the "rel" attribute for metadata links
439 public function getMetadataAttribute() {
440 # note: buggy CC software only reads first "meta" link
441 static $haveMeta = false;
443 return 'alternate meta';
451 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
452 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
455 * @param string $script Raw HTML
457 function addScript( $script ) {
458 $this->mScripts
.= $script;
462 * Add a JavaScript file out of skins/common, or a given relative path.
463 * Internal use only. Use OutputPage::addModules() if possible.
465 * @param string $file Filename in skins/common or complete on-server path
467 * @param string $version Style version of the file. Defaults to $wgStyleVersion
469 public function addScriptFile( $file, $version = null ) {
470 // See if $file parameter is an absolute URL or begins with a slash
471 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
474 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
476 if ( is_null( $version ) ) {
477 $version = $this->getConfig()->get( 'StyleVersion' );
479 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
483 * Add a self-contained script tag with the given contents
484 * Internal use only. Use OutputPage::addModules() if possible.
486 * @param string $script JavaScript text, no script tags
488 public function addInlineScript( $script ) {
489 $this->mScripts
.= Html
::inlineScript( $script );
493 * Filter an array of modules to remove insufficiently trustworthy members, and modules
494 * which are no longer registered (eg a page is cached before an extension is disabled)
495 * @param array $modules
496 * @param string|null $position If not null, only return modules with this position
497 * @param string $type
500 protected function filterModules( array $modules, $position = null,
501 $type = ResourceLoaderModule
::TYPE_COMBINED
503 $resourceLoader = $this->getResourceLoader();
504 $filteredModules = [];
505 foreach ( $modules as $val ) {
506 $module = $resourceLoader->getModule( $val );
507 if ( $module instanceof ResourceLoaderModule
508 && $module->getOrigin() <= $this->getAllowedModules( $type )
509 && ( is_null( $position ) ||
$module->getPosition() == $position )
511 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
512 $this->warnModuleTargetFilter( $module->getName() );
515 $filteredModules[] = $val;
518 return $filteredModules;
521 private function warnModuleTargetFilter( $moduleName ) {
522 static $warnings = [];
523 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
526 $warnings[$this->mTarget
][$moduleName] = true;
527 $this->getResourceLoader()->getLogger()->debug(
528 'Module "{module}" not loadable on target "{target}".',
530 'module' => $moduleName,
531 'target' => $this->mTarget
,
537 * Get the list of modules to include on this page
539 * @param bool $filter Whether to filter out insufficiently trustworthy modules
540 * @param string|null $position If not null, only return modules with this position
541 * @param string $param
542 * @param string $type
543 * @return array Array of module names
545 public function getModules( $filter = false, $position = null, $param = 'mModules',
546 $type = ResourceLoaderModule
::TYPE_COMBINED
548 $modules = array_values( array_unique( $this->$param ) );
550 ?
$this->filterModules( $modules, $position, $type )
555 * Add one or more modules recognized by ResourceLoader. Modules added
556 * through this function will be loaded by ResourceLoader when the
559 * @param string|array $modules Module name (string) or array of module names
561 public function addModules( $modules ) {
562 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
566 * Get the list of module JS to include on this page
568 * @param bool $filter
569 * @param string|null $position
570 * @return array Array of module names
572 public function getModuleScripts( $filter = false, $position = null ) {
573 return $this->getModules( $filter, $position, 'mModuleScripts',
574 ResourceLoaderModule
::TYPE_SCRIPTS
579 * Add only JS of one or more modules recognized by ResourceLoader. Module
580 * scripts added through this function will be loaded by ResourceLoader when
583 * @param string|array $modules Module name (string) or array of module names
585 public function addModuleScripts( $modules ) {
586 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
590 * Get the list of module CSS to include on this page
592 * @param bool $filter
593 * @param string|null $position
594 * @return array Array of module names
596 public function getModuleStyles( $filter = false, $position = null ) {
597 return $this->getModules( $filter, $position, 'mModuleStyles',
598 ResourceLoaderModule
::TYPE_STYLES
603 * Add only CSS of one or more modules recognized by ResourceLoader.
605 * Module styles added through this function will be added using standard link CSS
606 * tags, rather than as a combined Javascript and CSS package. Thus, they will
607 * load when JavaScript is disabled (unless CSS also happens to be disabled).
609 * @param string|array $modules Module name (string) or array of module names
611 public function addModuleStyles( $modules ) {
612 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
616 * @return null|string ResourceLoader target
618 public function getTarget() {
619 return $this->mTarget
;
623 * Sets ResourceLoader target for load.php links. If null, will be omitted
625 * @param string|null $target
627 public function setTarget( $target ) {
628 $this->mTarget
= $target;
632 * Get an array of head items
636 function getHeadItemsArray() {
637 return $this->mHeadItems
;
641 * Add or replace a head item to the output
643 * Whenever possible, use more specific options like ResourceLoader modules,
644 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
645 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
646 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
647 * This would be your very LAST fallback.
649 * @param string $name Item name
650 * @param string $value Raw HTML
652 public function addHeadItem( $name, $value ) {
653 $this->mHeadItems
[$name] = $value;
657 * Add one or more head items to the output
660 * @param string|string[] $values Raw HTML
662 public function addHeadItems( $values ) {
663 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
667 * Check if the header item $name is already set
669 * @param string $name Item name
672 public function hasHeadItem( $name ) {
673 return isset( $this->mHeadItems
[$name] );
677 * Add a class to the <body> element
680 * @param string|string[] $classes One or more classes to add
682 public function addBodyClasses( $classes ) {
683 $this->mAdditionalBodyClasses
= array_merge( $this->mAdditionalBodyClasses
, (array)$classes );
687 * Set whether the output should only contain the body of the article,
688 * without any skin, sidebar, etc.
689 * Used e.g. when calling with "action=render".
691 * @param bool $only Whether to output only the body of the article
693 public function setArticleBodyOnly( $only ) {
694 $this->mArticleBodyOnly
= $only;
698 * Return whether the output will contain only the body of the article
702 public function getArticleBodyOnly() {
703 return $this->mArticleBodyOnly
;
707 * Set an additional output property
710 * @param string $name
711 * @param mixed $value
713 public function setProperty( $name, $value ) {
714 $this->mProperties
[$name] = $value;
718 * Get an additional output property
721 * @param string $name
722 * @return mixed Property value or null if not found
724 public function getProperty( $name ) {
725 if ( isset( $this->mProperties
[$name] ) ) {
726 return $this->mProperties
[$name];
733 * checkLastModified tells the client to use the client-cached page if
734 * possible. If successful, the OutputPage is disabled so that
735 * any future call to OutputPage->output() have no effect.
737 * Side effect: sets mLastModified for Last-Modified header
739 * @param string $timestamp
741 * @return bool True if cache-ok headers was sent.
743 public function checkLastModified( $timestamp ) {
744 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
745 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
748 $config = $this->getConfig();
749 if ( !$config->get( 'CachePages' ) ) {
750 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
754 $timestamp = wfTimestamp( TS_MW
, $timestamp );
756 'page' => $timestamp,
757 'user' => $this->getUser()->getTouched(),
758 'epoch' => $config->get( 'CacheEpoch' )
760 if ( $config->get( 'UseSquid' ) ) {
761 // T46570: the core page itself may not change, but resources might
762 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
764 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
766 $maxModified = max( $modifiedTimes );
767 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
769 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
770 if ( $clientHeader === false ) {
771 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
775 # IE sends sizes after the date like this:
776 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
777 # this breaks strtotime().
778 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
780 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
781 $clientHeaderTime = strtotime( $clientHeader );
782 MediaWiki\restoreWarnings
();
783 if ( !$clientHeaderTime ) {
785 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
788 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
792 foreach ( $modifiedTimes as $name => $value ) {
793 if ( $info !== '' ) {
796 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
799 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
800 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
801 wfDebug( __METHOD__
. ": effective Last-Modified: " .
802 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
803 if ( $clientHeaderTime < $maxModified ) {
804 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
809 # Give a 304 Not Modified response code and disable body output
810 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
811 ini_set( 'zlib.output_compression', 0 );
812 $this->getRequest()->response()->statusHeader( 304 );
813 $this->sendCacheControl();
816 // Don't output a compressed blob when using ob_gzhandler;
817 // it's technically against HTTP spec and seems to confuse
818 // Firefox when the response gets split over two packets.
819 wfClearOutputBuffers();
825 * Override the last modified timestamp
827 * @param string $timestamp New timestamp, in a format readable by
830 public function setLastModified( $timestamp ) {
831 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
835 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
837 * @param string $policy The literal string to output as the contents of
838 * the meta tag. Will be parsed according to the spec and output in
842 public function setRobotPolicy( $policy ) {
843 $policy = Article
::formatRobotPolicy( $policy );
845 if ( isset( $policy['index'] ) ) {
846 $this->setIndexPolicy( $policy['index'] );
848 if ( isset( $policy['follow'] ) ) {
849 $this->setFollowPolicy( $policy['follow'] );
854 * Set the index policy for the page, but leave the follow policy un-
857 * @param string $policy Either 'index' or 'noindex'.
860 public function setIndexPolicy( $policy ) {
861 $policy = trim( $policy );
862 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
863 $this->mIndexPolicy
= $policy;
868 * Set the follow policy for the page, but leave the index policy un-
871 * @param string $policy Either 'follow' or 'nofollow'.
874 public function setFollowPolicy( $policy ) {
875 $policy = trim( $policy );
876 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
877 $this->mFollowPolicy
= $policy;
882 * Set the new value of the "action text", this will be added to the
883 * "HTML title", separated from it with " - ".
885 * @param string $text New value of the "action text"
887 public function setPageTitleActionText( $text ) {
888 $this->mPageTitleActionText
= $text;
892 * Get the value of the "action text"
896 public function getPageTitleActionText() {
897 return $this->mPageTitleActionText
;
901 * "HTML title" means the contents of "<title>".
902 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
904 * @param string|Message $name
906 public function setHTMLTitle( $name ) {
907 if ( $name instanceof Message
) {
908 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
910 $this->mHTMLtitle
= $name;
915 * Return the "HTML title", i.e. the content of the "<title>" tag.
919 public function getHTMLTitle() {
920 return $this->mHTMLtitle
;
924 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
928 public function setRedirectedFrom( $t ) {
929 $this->mRedirectedFrom
= $t;
933 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
934 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
935 * but not bad tags like \<script\>. This function automatically sets
936 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
937 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
938 * good tags like \<i\> will be dropped entirely.
940 * @param string|Message $name
942 public function setPageTitle( $name ) {
943 if ( $name instanceof Message
) {
944 $name = $name->setContext( $this->getContext() )->text();
947 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
948 # but leave "<i>foobar</i>" alone
949 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
950 $this->mPagetitle
= $nameWithTags;
952 # change "<i>foo&bar</i>" to "foo&bar"
954 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
955 ->inContentLanguage()
960 * Return the "page title", i.e. the content of the \<h1\> tag.
964 public function getPageTitle() {
965 return $this->mPagetitle
;
969 * Set the Title object to use
973 public function setTitle( Title
$t ) {
974 $this->getContext()->setTitle( $t );
978 * Replace the subtitle with $str
980 * @param string|Message $str New value of the subtitle. String should be safe HTML.
982 public function setSubtitle( $str ) {
983 $this->clearSubtitle();
984 $this->addSubtitle( $str );
988 * Add $str to the subtitle
990 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
992 public function addSubtitle( $str ) {
993 if ( $str instanceof Message
) {
994 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
996 $this->mSubtitle
[] = $str;
1001 * Build message object for a subtitle containing a backlink to a page
1003 * @param Title $title Title to link to
1004 * @param array $query Array of additional parameters to include in the link
1008 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1009 if ( $title->isRedirect() ) {
1010 $query['redirect'] = 'no';
1012 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1013 return wfMessage( 'backlinksubtitle' )
1014 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1018 * Add a subtitle containing a backlink to a page
1020 * @param Title $title Title to link to
1021 * @param array $query Array of additional parameters to include in the link
1023 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1024 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1028 * Clear the subtitles
1030 public function clearSubtitle() {
1031 $this->mSubtitle
= [];
1039 public function getSubtitle() {
1040 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1044 * Set the page as printable, i.e. it'll be displayed with all
1045 * print styles included
1047 public function setPrintable() {
1048 $this->mPrintable
= true;
1052 * Return whether the page is "printable"
1056 public function isPrintable() {
1057 return $this->mPrintable
;
1061 * Disable output completely, i.e. calling output() will have no effect
1063 public function disable() {
1064 $this->mDoNothing
= true;
1068 * Return whether the output will be completely disabled
1072 public function isDisabled() {
1073 return $this->mDoNothing
;
1077 * Show an "add new section" link?
1081 public function showNewSectionLink() {
1082 return $this->mNewSectionLink
;
1086 * Forcibly hide the new section link?
1090 public function forceHideNewSectionLink() {
1091 return $this->mHideNewSectionLink
;
1095 * Add or remove feed links in the page header
1096 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1097 * for the new version
1098 * @see addFeedLink()
1100 * @param bool $show True: add default feeds, false: remove all feeds
1102 public function setSyndicated( $show = true ) {
1104 $this->setFeedAppendQuery( false );
1106 $this->mFeedLinks
= [];
1111 * Add default feeds to the page header
1112 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1113 * for the new version
1114 * @see addFeedLink()
1116 * @param string $val Query to append to feed links or false to output
1119 public function setFeedAppendQuery( $val ) {
1120 $this->mFeedLinks
= [];
1122 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1123 $query = "feed=$type";
1124 if ( is_string( $val ) ) {
1125 $query .= '&' . $val;
1127 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1132 * Add a feed link to the page header
1134 * @param string $format Feed type, should be a key of $wgFeedClasses
1135 * @param string $href URL
1137 public function addFeedLink( $format, $href ) {
1138 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1139 $this->mFeedLinks
[$format] = $href;
1144 * Should we output feed links for this page?
1147 public function isSyndicated() {
1148 return count( $this->mFeedLinks
) > 0;
1152 * Return URLs for each supported syndication format for this page.
1153 * @return array Associating format keys with URLs
1155 public function getSyndicationLinks() {
1156 return $this->mFeedLinks
;
1160 * Will currently always return null
1164 public function getFeedAppendQuery() {
1165 return $this->mFeedLinksAppendQuery
;
1169 * Set whether the displayed content is related to the source of the
1170 * corresponding article on the wiki
1171 * Setting true will cause the change "article related" toggle to true
1175 public function setArticleFlag( $v ) {
1176 $this->mIsarticle
= $v;
1178 $this->mIsArticleRelated
= $v;
1183 * Return whether the content displayed page is related to the source of
1184 * the corresponding article on the wiki
1188 public function isArticle() {
1189 return $this->mIsarticle
;
1193 * Set whether this page is related an article on the wiki
1194 * Setting false will cause the change of "article flag" toggle to false
1198 public function setArticleRelated( $v ) {
1199 $this->mIsArticleRelated
= $v;
1201 $this->mIsarticle
= false;
1206 * Return whether this page is related an article on the wiki
1210 public function isArticleRelated() {
1211 return $this->mIsArticleRelated
;
1215 * Add new language links
1217 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1218 * (e.g. 'fr:Test page')
1220 public function addLanguageLinks( array $newLinkArray ) {
1221 $this->mLanguageLinks +
= $newLinkArray;
1225 * Reset the language links and add new language links
1227 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1228 * (e.g. 'fr:Test page')
1230 public function setLanguageLinks( array $newLinkArray ) {
1231 $this->mLanguageLinks
= $newLinkArray;
1235 * Get the list of language links
1237 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1239 public function getLanguageLinks() {
1240 return $this->mLanguageLinks
;
1244 * Add an array of categories, with names in the keys
1246 * @param array $categories Mapping category name => sort key
1248 public function addCategoryLinks( array $categories ) {
1251 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1255 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1257 # Set all the values to 'normal'.
1258 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1260 # Mark hidden categories
1261 foreach ( $res as $row ) {
1262 if ( isset( $row->pp_value
) ) {
1263 $categories[$row->page_title
] = 'hidden';
1267 // Avoid PHP 7.1 warning of passing $this by reference
1268 $outputPage = $this;
1269 # Add the remaining categories to the skin
1271 'OutputPageMakeCategoryLinks',
1272 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1274 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1275 foreach ( $categories as $category => $type ) {
1276 // array keys will cast numeric category names to ints, so cast back to string
1277 $category = (string)$category;
1278 $origcategory = $category;
1279 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1283 $wgContLang->findVariantLink( $category, $title, true );
1284 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1287 $text = $wgContLang->convertHtml( $title->getText() );
1288 $this->mCategories
[$type][] = $title->getText();
1289 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1295 * @param array $categories
1296 * @return bool|ResultWrapper
1298 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1299 # Add the links to a LinkBatch
1300 $arr = [ NS_CATEGORY
=> $categories ];
1301 $lb = new LinkBatch
;
1302 $lb->setArray( $arr );
1304 # Fetch existence plus the hiddencat property
1305 $dbr = wfGetDB( DB_REPLICA
);
1306 $fields = array_merge(
1307 LinkCache
::getSelectFields(),
1308 [ 'page_namespace', 'page_title', 'pp_value' ]
1311 $res = $dbr->select( [ 'page', 'page_props' ],
1313 $lb->constructSet( 'page', $dbr ),
1316 [ 'page_props' => [ 'LEFT JOIN', [
1317 'pp_propname' => 'hiddencat',
1322 # Add the results to the link cache
1323 $lb->addResultToCache( LinkCache
::singleton(), $res );
1329 * Reset the category links (but not the category list) and add $categories
1331 * @param array $categories Mapping category name => sort key
1333 public function setCategoryLinks( array $categories ) {
1334 $this->mCategoryLinks
= [];
1335 $this->addCategoryLinks( $categories );
1339 * Get the list of category links, in a 2-D array with the following format:
1340 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1341 * hidden categories) and $link a HTML fragment with a link to the category
1346 public function getCategoryLinks() {
1347 return $this->mCategoryLinks
;
1351 * Get the list of category names this page belongs to.
1353 * @param string $type The type of categories which should be returned. Possible values:
1354 * * all: all categories of all types
1355 * * hidden: only the hidden categories
1356 * * normal: all categories, except hidden categories
1357 * @return array Array of strings
1359 public function getCategories( $type = 'all' ) {
1360 if ( $type === 'all' ) {
1361 $allCategories = [];
1362 foreach ( $this->mCategories
as $categories ) {
1363 $allCategories = array_merge( $allCategories, $categories );
1365 return $allCategories;
1367 if ( !isset( $this->mCategories
[$type] ) ) {
1368 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1370 return $this->mCategories
[$type];
1374 * Add an array of indicators, with their identifiers as array
1375 * keys and HTML contents as values.
1377 * In case of duplicate keys, existing values are overwritten.
1379 * @param array $indicators
1382 public function setIndicators( array $indicators ) {
1383 $this->mIndicators
= $indicators +
$this->mIndicators
;
1384 // Keep ordered by key
1385 ksort( $this->mIndicators
);
1389 * Get the indicators associated with this page.
1391 * The array will be internally ordered by item keys.
1393 * @return array Keys: identifiers, values: HTML contents
1396 public function getIndicators() {
1397 return $this->mIndicators
;
1401 * Adds help link with an icon via page indicators.
1402 * Link target can be overridden by a local message containing a wikilink:
1403 * the message key is: lowercase action or special page name + '-helppage'.
1404 * @param string $to Target MediaWiki.org page title or encoded URL.
1405 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1408 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1409 $this->addModuleStyles( 'mediawiki.helplink' );
1410 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1412 if ( $overrideBaseUrl ) {
1415 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1416 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1419 $link = Html
::rawElement(
1423 'target' => '_blank',
1424 'class' => 'mw-helplink',
1429 $this->setIndicators( [ 'mw-helplink' => $link ] );
1433 * Do not allow scripts which can be modified by wiki users to load on this page;
1434 * only allow scripts bundled with, or generated by, the software.
1435 * Site-wide styles are controlled by a config setting, since they can be
1436 * used to create a custom skin/theme, but not user-specific ones.
1438 * @todo this should be given a more accurate name
1440 public function disallowUserJs() {
1441 $this->reduceAllowedModules(
1442 ResourceLoaderModule
::TYPE_SCRIPTS
,
1443 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1446 // Site-wide styles are controlled by a config setting, see T73621
1447 // for background on why. User styles are never allowed.
1448 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1449 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1451 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1453 $this->reduceAllowedModules(
1454 ResourceLoaderModule
::TYPE_STYLES
,
1460 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1461 * @see ResourceLoaderModule::$origin
1462 * @param string $type ResourceLoaderModule TYPE_ constant
1463 * @return int ResourceLoaderModule ORIGIN_ class constant
1465 public function getAllowedModules( $type ) {
1466 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1467 return min( array_values( $this->mAllowedModules
) );
1469 return isset( $this->mAllowedModules
[$type] )
1470 ?
$this->mAllowedModules
[$type]
1471 : ResourceLoaderModule
::ORIGIN_ALL
;
1476 * Limit the highest level of CSS/JS untrustworthiness allowed.
1478 * If passed the same or a higher level than the current level of untrustworthiness set, the
1479 * level will remain unchanged.
1481 * @param string $type
1482 * @param int $level ResourceLoaderModule class constant
1484 public function reduceAllowedModules( $type, $level ) {
1485 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1489 * Prepend $text to the body HTML
1491 * @param string $text HTML
1493 public function prependHTML( $text ) {
1494 $this->mBodytext
= $text . $this->mBodytext
;
1498 * Append $text to the body HTML
1500 * @param string $text HTML
1502 public function addHTML( $text ) {
1503 $this->mBodytext
.= $text;
1507 * Shortcut for adding an Html::element via addHTML.
1511 * @param string $element
1512 * @param array $attribs
1513 * @param string $contents
1515 public function addElement( $element, array $attribs = [], $contents = '' ) {
1516 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1520 * Clear the body HTML
1522 public function clearHTML() {
1523 $this->mBodytext
= '';
1529 * @return string HTML
1531 public function getHTML() {
1532 return $this->mBodytext
;
1536 * Get/set the ParserOptions object to use for wikitext parsing
1538 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1539 * current ParserOption object. This parameter is deprecated since 1.31.
1540 * @return ParserOptions
1542 public function parserOptions( $options = null ) {
1543 if ( $options !== null ) {
1544 wfDeprecated( __METHOD__
. ' with non-null $options', '1.31' );
1547 if ( $options !== null && !empty( $options->isBogus
) ) {
1548 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1549 // been changed somehow, and keep it if so.
1550 $anonPO = ParserOptions
::newFromAnon();
1551 $anonPO->setEditSection( false );
1552 $anonPO->setAllowUnsafeRawHtml( false );
1553 if ( !$options->matches( $anonPO ) ) {
1554 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1555 $options->isBogus
= false;
1559 if ( !$this->mParserOptions
) {
1560 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1561 // $wgUser isn't unstubbable yet, so don't try to get a
1562 // ParserOptions for it. And don't cache this ParserOptions
1564 $po = ParserOptions
::newFromAnon();
1565 $po->setEditSection( false );
1566 $po->setAllowUnsafeRawHtml( false );
1567 $po->isBogus
= true;
1568 if ( $options !== null ) {
1569 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1574 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1575 $this->mParserOptions
->setEditSection( false );
1576 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1579 if ( $options !== null && !empty( $options->isBogus
) ) {
1580 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1582 return wfSetVar( $this->mParserOptions
, null, true );
1584 return wfSetVar( $this->mParserOptions
, $options );
1589 * Set the revision ID which will be seen by the wiki text parser
1590 * for things such as embedded {{REVISIONID}} variable use.
1592 * @param int|null $revid An positive integer, or null
1593 * @return mixed Previous value
1595 public function setRevisionId( $revid ) {
1596 $val = is_null( $revid ) ?
null : intval( $revid );
1597 return wfSetVar( $this->mRevisionId
, $val );
1601 * Get the displayed revision ID
1605 public function getRevisionId() {
1606 return $this->mRevisionId
;
1610 * Set the timestamp of the revision which will be displayed. This is used
1611 * to avoid a extra DB call in Skin::lastModified().
1613 * @param string|null $timestamp
1614 * @return mixed Previous value
1616 public function setRevisionTimestamp( $timestamp ) {
1617 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1621 * Get the timestamp of displayed revision.
1622 * This will be null if not filled by setRevisionTimestamp().
1624 * @return string|null
1626 public function getRevisionTimestamp() {
1627 return $this->mRevisionTimestamp
;
1631 * Set the displayed file version
1633 * @param File|bool $file
1634 * @return mixed Previous value
1636 public function setFileVersion( $file ) {
1638 if ( $file instanceof File
&& $file->exists() ) {
1639 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1641 return wfSetVar( $this->mFileVersion
, $val, true );
1645 * Get the displayed file version
1647 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1649 public function getFileVersion() {
1650 return $this->mFileVersion
;
1654 * Get the templates used on this page
1656 * @return array (namespace => dbKey => revId)
1659 public function getTemplateIds() {
1660 return $this->mTemplateIds
;
1664 * Get the files used on this page
1666 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1669 public function getFileSearchOptions() {
1670 return $this->mImageTimeKeys
;
1674 * Convert wikitext to HTML and add it to the buffer
1675 * Default assumes that the current page title will be used.
1677 * @param string $text
1678 * @param bool $linestart Is this the start of a line?
1679 * @param bool $interface Is this text in the user interface language?
1680 * @throws MWException
1682 public function addWikiText( $text, $linestart = true, $interface = true ) {
1683 $title = $this->getTitle(); // Work around E_STRICT
1685 throw new MWException( 'Title is null' );
1687 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1691 * Add wikitext with a custom Title object
1693 * @param string $text Wikitext
1694 * @param Title &$title
1695 * @param bool $linestart Is this the start of a line?
1697 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1698 $this->addWikiTextTitle( $text, $title, $linestart );
1702 * Add wikitext with a custom Title object and tidy enabled.
1704 * @param string $text Wikitext
1705 * @param Title &$title
1706 * @param bool $linestart Is this the start of a line?
1708 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1709 $this->addWikiTextTitle( $text, $title, $linestart, true );
1713 * Add wikitext with tidy enabled
1715 * @param string $text Wikitext
1716 * @param bool $linestart Is this the start of a line?
1718 public function addWikiTextTidy( $text, $linestart = true ) {
1719 $title = $this->getTitle();
1720 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1724 * Add wikitext with a custom Title object
1726 * @param string $text Wikitext
1727 * @param Title $title
1728 * @param bool $linestart Is this the start of a line?
1729 * @param bool $tidy Whether to use tidy
1730 * @param bool $interface Whether it is an interface message
1731 * (for example disables conversion)
1733 public function addWikiTextTitle( $text, Title
$title, $linestart,
1734 $tidy = false, $interface = false
1738 $popts = $this->parserOptions();
1739 $oldTidy = $popts->setTidy( $tidy );
1740 $popts->setInterfaceMessage( (bool)$interface );
1742 $parserOutput = $wgParser->getFreshParser()->parse(
1743 $text, $title, $popts,
1744 $linestart, true, $this->mRevisionId
1747 $popts->setTidy( $oldTidy );
1749 $this->addParserOutput( $parserOutput, [
1750 'enableSectionEditLinks' => false,
1755 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1756 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1760 * @param ParserOutput $parserOutput
1762 public function addParserOutputMetadata( $parserOutput ) {
1763 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1764 $this->addCategoryLinks( $parserOutput->getCategories() );
1765 $this->setIndicators( $parserOutput->getIndicators() );
1766 $this->mNewSectionLink
= $parserOutput->getNewSection();
1767 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1769 if ( !$parserOutput->isCacheable() ) {
1770 $this->enableClientCache( false );
1772 $this->mNoGallery
= $parserOutput->getNoGallery();
1773 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1774 $this->addModules( $parserOutput->getModules() );
1775 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1776 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1777 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1778 $this->mPreventClickjacking
= $this->mPreventClickjacking
1779 ||
$parserOutput->preventClickjacking();
1781 // Template versioning...
1782 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1783 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1784 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1786 $this->mTemplateIds
[$ns] = $dbks;
1789 // File versioning...
1790 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1791 $this->mImageTimeKeys
[$dbk] = $data;
1794 // Hooks registered in the object
1795 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1796 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1797 list( $hookName, $data ) = $hookInfo;
1798 if ( isset( $parserOutputHooks[$hookName] ) ) {
1799 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1803 // Enable OOUI if requested via ParserOutput
1804 if ( $parserOutput->getEnableOOUI() ) {
1805 $this->enableOOUI();
1808 // Include parser limit report
1809 if ( !$this->limitReportJSData
) {
1810 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1813 // Link flags are ignored for now, but may in the future be
1814 // used to mark individual language links.
1816 // Avoid PHP 7.1 warning of passing $this by reference
1817 $outputPage = $this;
1818 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1819 Hooks
::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1821 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1822 // so that extensions may modify ParserOutput to toggle TOC.
1823 // This cannot be moved to addParserOutputText because that is not
1824 // called by EditPage for Preview.
1825 if ( $parserOutput->getTOCEnabled() && $parserOutput->getTOCHTML() ) {
1826 $this->mEnableTOC
= true;
1831 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1832 * ParserOutput object, without any other metadata.
1835 * @param ParserOutput $parserOutput
1836 * @param array $poOptions Options to ParserOutput::getText()
1838 public function addParserOutputContent( $parserOutput, $poOptions = [] ) {
1839 $this->addParserOutputText( $parserOutput, $poOptions );
1841 $this->addModules( $parserOutput->getModules() );
1842 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1843 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1845 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1849 * Add the HTML associated with a ParserOutput object, without any metadata.
1852 * @param ParserOutput $parserOutput
1853 * @param array $poOptions Options to ParserOutput::getText()
1855 public function addParserOutputText( $parserOutput, $poOptions = [] ) {
1856 $text = $parserOutput->getText( $poOptions );
1857 // Avoid PHP 7.1 warning of passing $this by reference
1858 $outputPage = $this;
1859 Hooks
::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1860 $this->addHTML( $text );
1864 * Add everything from a ParserOutput object.
1866 * @param ParserOutput $parserOutput
1867 * @param array $poOptions Options to ParserOutput::getText()
1869 function addParserOutput( $parserOutput, $poOptions = [] ) {
1870 $this->addParserOutputMetadata( $parserOutput );
1872 // Touch section edit links only if not previously disabled
1873 if ( $parserOutput->getEditSectionTokens() ) {
1874 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1876 if ( !$this->mEnableSectionEditLinks
1877 && !array_key_exists( 'enableSectionEditLinks', $poOptions )
1879 $poOptions['enableSectionEditLinks'] = false;
1882 $this->addParserOutputText( $parserOutput, $poOptions );
1886 * Add the output of a QuickTemplate to the output buffer
1888 * @param QuickTemplate &$template
1890 public function addTemplate( &$template ) {
1891 $this->addHTML( $template->getHTML() );
1895 * Parse wikitext and return the HTML.
1897 * @param string $text
1898 * @param bool $linestart Is this the start of a line?
1899 * @param bool $interface Use interface language ($wgLang instead of
1900 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1901 * This also disables LanguageConverter.
1902 * @param Language $language Target language object, will override $interface
1903 * @throws MWException
1904 * @return string HTML
1906 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1909 if ( is_null( $this->getTitle() ) ) {
1910 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1913 $popts = $this->parserOptions();
1915 $popts->setInterfaceMessage( true );
1917 if ( $language !== null ) {
1918 $oldLang = $popts->setTargetLanguage( $language );
1921 $parserOutput = $wgParser->getFreshParser()->parse(
1922 $text, $this->getTitle(), $popts,
1923 $linestart, true, $this->mRevisionId
1927 $popts->setInterfaceMessage( false );
1929 if ( $language !== null ) {
1930 $popts->setTargetLanguage( $oldLang );
1933 return $parserOutput->getText( [
1934 'enableSectionEditLinks' => false,
1939 * Parse wikitext, strip paragraphs, and return the HTML.
1941 * @param string $text
1942 * @param bool $linestart Is this the start of a line?
1943 * @param bool $interface Use interface language ($wgLang instead of
1944 * $wgContLang) while parsing language sensitive magic
1945 * words like GRAMMAR and PLURAL
1946 * @return string HTML
1948 public function parseInline( $text, $linestart = true, $interface = false ) {
1949 $parsed = $this->parse( $text, $linestart, $interface );
1950 return Parser
::stripOuterParagraph( $parsed );
1954 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1956 * @param int $maxage Maximum cache time on the CDN, in seconds.
1958 public function setCdnMaxage( $maxage ) {
1959 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1963 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1965 * @param int $maxage Maximum cache time on the CDN, in seconds
1968 public function lowerCdnMaxage( $maxage ) {
1969 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1970 $this->setCdnMaxage( $this->mCdnMaxage
);
1974 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1976 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1977 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1978 * TTL is 90% of the age of the object, subject to the min and max.
1980 * @param string|int|float|bool|null $mtime Last-Modified timestamp
1981 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
1982 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1983 * @return int TTL in seconds
1986 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1987 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1988 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1990 if ( $mtime === null ||
$mtime === false ) {
1991 return $minTTL; // entity does not exist
1994 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1995 $adaptiveTTL = max( 0.9 * $age, $minTTL );
1996 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1998 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2000 return $adaptiveTTL;
2004 * Use enableClientCache(false) to force it to send nocache headers
2006 * @param bool $state
2010 public function enableClientCache( $state ) {
2011 return wfSetVar( $this->mEnableClientCache
, $state );
2015 * Get the list of cookies that will influence on the cache
2019 function getCacheVaryCookies() {
2021 if ( $cookies === null ) {
2022 $config = $this->getConfig();
2023 $cookies = array_merge(
2024 SessionManager
::singleton()->getVaryCookies(),
2028 $config->get( 'CacheVaryCookies' )
2030 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2036 * Check if the request has a cache-varying cookie header
2037 * If it does, it's very important that we don't allow public caching
2041 function haveCacheVaryCookies() {
2042 $request = $this->getRequest();
2043 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2044 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2045 wfDebug( __METHOD__
. ": found $cookieName\n" );
2049 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2054 * Add an HTTP header that will influence on the cache
2056 * @param string $header Header name
2057 * @param string[]|null $option Options for the Key header. See
2058 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2059 * for the list of valid options.
2061 public function addVaryHeader( $header, array $option = null ) {
2062 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2063 $this->mVaryHeader
[$header] = [];
2065 if ( !is_array( $option ) ) {
2068 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2072 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2073 * such as Accept-Encoding or Cookie
2077 public function getVaryHeader() {
2078 // If we vary on cookies, let's make sure it's always included here too.
2079 if ( $this->getCacheVaryCookies() ) {
2080 $this->addVaryHeader( 'Cookie' );
2083 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2084 $this->addVaryHeader( $header, $options );
2086 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2090 * Add an HTTP Link: header
2092 * @param string $header Header value
2094 public function addLinkHeader( $header ) {
2095 $this->mLinkHeader
[] = $header;
2099 * Return a Link: header. Based on the values of $mLinkHeader.
2103 public function getLinkHeader() {
2104 if ( !$this->mLinkHeader
) {
2108 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2112 * Get a complete Key header
2116 public function getKeyHeader() {
2117 $cvCookies = $this->getCacheVaryCookies();
2119 $cookiesOption = [];
2120 foreach ( $cvCookies as $cookieName ) {
2121 $cookiesOption[] = 'param=' . $cookieName;
2123 $this->addVaryHeader( 'Cookie', $cookiesOption );
2125 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2126 $this->addVaryHeader( $header, $options );
2130 foreach ( $this->mVaryHeader
as $header => $option ) {
2131 $newheader = $header;
2132 if ( is_array( $option ) && count( $option ) > 0 ) {
2133 $newheader .= ';' . implode( ';', $option );
2135 $headers[] = $newheader;
2137 $key = 'Key: ' . implode( ',', $headers );
2143 * T23672: Add Accept-Language to Vary and Key headers
2144 * if there's no 'variant' parameter existed in GET.
2147 * /w/index.php?title=Main_page should always be served; but
2148 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2150 function addAcceptLanguage() {
2151 $title = $this->getTitle();
2152 if ( !$title instanceof Title
) {
2156 $lang = $title->getPageLanguage();
2157 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2158 $variants = $lang->getVariants();
2160 foreach ( $variants as $variant ) {
2161 if ( $variant === $lang->getCode() ) {
2164 $aloption[] = 'substr=' . $variant;
2166 // IE and some other browsers use BCP 47 standards in
2167 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2168 // We should handle these too.
2169 $variantBCP47 = LanguageCode
::bcp47( $variant );
2170 if ( $variantBCP47 !== $variant ) {
2171 $aloption[] = 'substr=' . $variantBCP47;
2175 $this->addVaryHeader( 'Accept-Language', $aloption );
2180 * Set a flag which will cause an X-Frame-Options header appropriate for
2181 * edit pages to be sent. The header value is controlled by
2182 * $wgEditPageFrameOptions.
2184 * This is the default for special pages. If you display a CSRF-protected
2185 * form on an ordinary view page, then you need to call this function.
2187 * @param bool $enable
2189 public function preventClickjacking( $enable = true ) {
2190 $this->mPreventClickjacking
= $enable;
2194 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2195 * This can be called from pages which do not contain any CSRF-protected
2198 public function allowClickjacking() {
2199 $this->mPreventClickjacking
= false;
2203 * Get the prevent-clickjacking flag
2208 public function getPreventClickjacking() {
2209 return $this->mPreventClickjacking
;
2213 * Get the X-Frame-Options header value (without the name part), or false
2214 * if there isn't one. This is used by Skin to determine whether to enable
2215 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2217 * @return string|false
2219 public function getFrameOptions() {
2220 $config = $this->getConfig();
2221 if ( $config->get( 'BreakFrames' ) ) {
2223 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2224 return $config->get( 'EditPageFrameOptions' );
2230 * Send cache control HTTP headers
2232 public function sendCacheControl() {
2233 $response = $this->getRequest()->response();
2234 $config = $this->getConfig();
2236 $this->addVaryHeader( 'Cookie' );
2237 $this->addAcceptLanguage();
2239 # don't serve compressed data to clients who can't handle it
2240 # maintain different caches for logged-in users and non-logged in ones
2241 $response->header( $this->getVaryHeader() );
2243 if ( $config->get( 'UseKeyHeader' ) ) {
2244 $response->header( $this->getKeyHeader() );
2247 if ( $this->mEnableClientCache
) {
2249 $config->get( 'UseSquid' ) &&
2250 !$response->hasCookies() &&
2251 !SessionManager
::getGlobalSession()->isPersistent() &&
2252 !$this->isPrintable() &&
2253 $this->mCdnMaxage
!= 0 &&
2254 !$this->haveCacheVaryCookies()
2256 if ( $config->get( 'UseESI' ) ) {
2257 # We'll purge the proxy cache explicitly, but require end user agents
2258 # to revalidate against the proxy on each visit.
2259 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2260 wfDebug( __METHOD__
.
2261 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2262 # start with a shorter timeout for initial testing
2263 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2265 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2266 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2268 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2270 # We'll purge the proxy cache for anons explicitly, but require end user agents
2271 # to revalidate against the proxy on each visit.
2272 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2273 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2274 wfDebug( __METHOD__
.
2275 ": local proxy caching; {$this->mLastModified} **", 'private' );
2276 # start with a shorter timeout for initial testing
2277 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2278 $response->header( "Cache-Control: " .
2279 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2282 # We do want clients to cache if they can, but they *must* check for updates
2283 # on revisiting the page.
2284 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2285 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2286 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2288 if ( $this->mLastModified
) {
2289 $response->header( "Last-Modified: {$this->mLastModified}" );
2292 wfDebug( __METHOD__
. ": no caching **", 'private' );
2294 # In general, the absence of a last modified header should be enough to prevent
2295 # the client from using its cache. We send a few other things just to make sure.
2296 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2297 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2298 $response->header( 'Pragma: no-cache' );
2303 * Finally, all the text has been munged and accumulated into
2304 * the object, let's actually output it:
2306 * @param bool $return Set to true to get the result as a string rather than sending it
2307 * @return string|null
2309 * @throws FatalError
2310 * @throws MWException
2312 public function output( $return = false ) {
2315 if ( $this->mDoNothing
) {
2316 return $return ?
'' : null;
2319 $response = $this->getRequest()->response();
2320 $config = $this->getConfig();
2322 if ( $this->mRedirect
!= '' ) {
2323 # Standards require redirect URLs to be absolute
2324 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2326 $redirect = $this->mRedirect
;
2327 $code = $this->mRedirectCode
;
2329 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2330 if ( $code == '301' ||
$code == '303' ) {
2331 if ( !$config->get( 'DebugRedirects' ) ) {
2332 $response->statusHeader( $code );
2334 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2336 if ( $config->get( 'VaryOnXFP' ) ) {
2337 $this->addVaryHeader( 'X-Forwarded-Proto' );
2339 $this->sendCacheControl();
2341 $response->header( "Content-Type: text/html; charset=utf-8" );
2342 if ( $config->get( 'DebugRedirects' ) ) {
2343 $url = htmlspecialchars( $redirect );
2344 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2345 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2346 print "</body>\n</html>\n";
2348 $response->header( 'Location: ' . $redirect );
2352 return $return ?
'' : null;
2353 } elseif ( $this->mStatusCode
) {
2354 $response->statusHeader( $this->mStatusCode
);
2357 # Buffer output; final headers may depend on later processing
2360 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2361 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2363 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2364 // jQuery etc. can work correctly.
2365 $response->header( 'X-UA-Compatible: IE=Edge' );
2367 if ( !$this->mArticleBodyOnly
) {
2368 $sk = $this->getSkin();
2370 if ( $sk->shouldPreloadLogo() ) {
2371 $this->addLogoPreloadLinkHeaders();
2375 $linkHeader = $this->getLinkHeader();
2376 if ( $linkHeader ) {
2377 $response->header( $linkHeader );
2380 // Prevent framing, if requested
2381 $frameOptions = $this->getFrameOptions();
2382 if ( $frameOptions ) {
2383 $response->header( "X-Frame-Options: $frameOptions" );
2386 if ( $this->mArticleBodyOnly
) {
2387 echo $this->mBodytext
;
2389 // Enable safe mode if requested
2390 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2391 $this->disallowUserJs();
2394 $sk = $this->getSkin();
2395 foreach ( $sk->getDefaultModules() as $group ) {
2396 $this->addModules( $group );
2399 MWDebug
::addModules( $this );
2401 // Avoid PHP 7.1 warning of passing $this by reference
2402 $outputPage = $this;
2403 // Hook that allows last minute changes to the output page, e.g.
2404 // adding of CSS or Javascript by extensions.
2405 Hooks
::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2409 } catch ( Exception
$e ) {
2410 ob_end_clean(); // bug T129657
2416 // This hook allows last minute changes to final overall output by modifying output buffer
2417 Hooks
::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2418 } catch ( Exception
$e ) {
2419 ob_end_clean(); // bug T129657
2423 $this->sendCacheControl();
2426 return ob_get_clean();
2434 * Prepare this object to display an error page; disable caching and
2435 * indexing, clear the current text and redirect, set the page's title
2436 * and optionally an custom HTML title (content of the "<title>" tag).
2438 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2439 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2440 * optional, if not passed the "<title>" attribute will be
2441 * based on $pageTitle
2443 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2444 $this->setPageTitle( $pageTitle );
2445 if ( $htmlTitle !== false ) {
2446 $this->setHTMLTitle( $htmlTitle );
2448 $this->setRobotPolicy( 'noindex,nofollow' );
2449 $this->setArticleRelated( false );
2450 $this->enableClientCache( false );
2451 $this->mRedirect
= '';
2452 $this->clearSubtitle();
2457 * Output a standard error page
2459 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2460 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2461 * showErrorPage( 'titlemsg', $messageObject );
2462 * showErrorPage( $titleMessageObject, $messageObject );
2464 * @param string|Message $title Message key (string) for page title, or a Message object
2465 * @param string|Message $msg Message key (string) for page text, or a Message object
2466 * @param array $params Message parameters; ignored if $msg is a Message object
2468 public function showErrorPage( $title, $msg, $params = [] ) {
2469 if ( !$title instanceof Message
) {
2470 $title = $this->msg( $title );
2473 $this->prepareErrorPage( $title );
2475 if ( $msg instanceof Message
) {
2476 if ( $params !== [] ) {
2477 trigger_error( 'Argument ignored: $params. The message parameters argument '
2478 . 'is discarded when the $msg argument is a Message object instead of '
2479 . 'a string.', E_USER_NOTICE
);
2481 $this->addHTML( $msg->parseAsBlock() );
2483 $this->addWikiMsgArray( $msg, $params );
2486 $this->returnToMain();
2490 * Output a standard permission error page
2492 * @param array $errors Error message keys or [key, param...] arrays
2493 * @param string $action Action that was denied or null if unknown
2495 public function showPermissionsErrorPage( array $errors, $action = null ) {
2496 foreach ( $errors as $key => $error ) {
2497 $errors[$key] = (array)$error;
2500 // For some action (read, edit, create and upload), display a "login to do this action"
2501 // error if all of the following conditions are met:
2502 // 1. the user is not logged in
2503 // 2. the only error is insufficient permissions (i.e. no block or something else)
2504 // 3. the error can be avoided simply by logging in
2505 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2506 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2507 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2508 && ( User
::groupHasPermission( 'user', $action )
2509 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2511 $displayReturnto = null;
2513 # Due to T34276, if a user does not have read permissions,
2514 # $this->getTitle() will just give Special:Badtitle, which is
2515 # not especially useful as a returnto parameter. Use the title
2516 # from the request instead, if there was one.
2517 $request = $this->getRequest();
2518 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2519 if ( $action == 'edit' ) {
2520 $msg = 'whitelistedittext';
2521 $displayReturnto = $returnto;
2522 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2523 $msg = 'nocreatetext';
2524 } elseif ( $action == 'upload' ) {
2525 $msg = 'uploadnologintext';
2527 $msg = 'loginreqpagetext';
2528 $displayReturnto = Title
::newMainPage();
2534 $query['returnto'] = $returnto->getPrefixedText();
2536 if ( !$request->wasPosted() ) {
2537 $returntoquery = $request->getValues();
2538 unset( $returntoquery['title'] );
2539 unset( $returntoquery['returnto'] );
2540 unset( $returntoquery['returntoquery'] );
2541 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2544 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2545 $loginLink = $linkRenderer->makeKnownLink(
2546 SpecialPage
::getTitleFor( 'Userlogin' ),
2547 $this->msg( 'loginreqlink' )->text(),
2552 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2553 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2555 # Don't return to a page the user can't read otherwise
2556 # we'll end up in a pointless loop
2557 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2558 $this->returnToMain( null, $displayReturnto );
2561 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2562 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2567 * Display an error page indicating that a given version of MediaWiki is
2568 * required to use it
2570 * @param mixed $version The version of MediaWiki needed to use the page
2572 public function versionRequired( $version ) {
2573 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2575 $this->addWikiMsg( 'versionrequiredtext', $version );
2576 $this->returnToMain();
2580 * Format a list of error messages
2582 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2583 * @param string $action Action that was denied or null if unknown
2584 * @return string The wikitext error-messages, formatted into a list.
2586 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2587 if ( $action == null ) {
2588 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2590 $action_desc = $this->msg( "action-$action" )->plain();
2592 'permissionserrorstext-withaction',
2595 )->plain() . "\n\n";
2598 if ( count( $errors ) > 1 ) {
2599 $text .= '<ul class="permissions-errors">' . "\n";
2601 foreach ( $errors as $error ) {
2603 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2608 $text .= "<div class=\"permissions-errors\">\n" .
2609 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2617 * Show a warning about replica DB lag
2619 * If the lag is higher than $wgSlaveLagCritical seconds,
2620 * then the warning is a bit more obvious. If the lag is
2621 * lower than $wgSlaveLagWarning, then no warning is shown.
2623 * @param int $lag Slave lag
2625 public function showLagWarning( $lag ) {
2626 $config = $this->getConfig();
2627 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2628 $lag = floor( $lag ); // floor to avoid nano seconds to display
2629 $message = $lag < $config->get( 'SlaveLagCritical' )
2632 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2633 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2637 public function showFatalError( $message ) {
2638 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2640 $this->addHTML( $message );
2643 public function showUnexpectedValueError( $name, $val ) {
2644 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2647 public function showFileCopyError( $old, $new ) {
2648 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2651 public function showFileRenameError( $old, $new ) {
2652 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2655 public function showFileDeleteError( $name ) {
2656 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2659 public function showFileNotFoundError( $name ) {
2660 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2664 * Add a "return to" link pointing to a specified title
2666 * @param Title $title Title to link
2667 * @param array $query Query string parameters
2668 * @param string $text Text of the link (input is not escaped)
2669 * @param array $options Options array to pass to Linker
2671 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2672 $linkRenderer = MediaWikiServices
::getInstance()
2673 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2674 $link = $this->msg( 'returnto' )->rawParams(
2675 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2676 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2680 * Add a "return to" link pointing to a specified title,
2681 * or the title indicated in the request, or else the main page
2683 * @param mixed $unused
2684 * @param Title|string $returnto Title or String to return to
2685 * @param string $returntoquery Query string for the return to link
2687 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2688 if ( $returnto == null ) {
2689 $returnto = $this->getRequest()->getText( 'returnto' );
2692 if ( $returntoquery == null ) {
2693 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2696 if ( $returnto === '' ) {
2697 $returnto = Title
::newMainPage();
2700 if ( is_object( $returnto ) ) {
2701 $titleObj = $returnto;
2703 $titleObj = Title
::newFromText( $returnto );
2705 // We don't want people to return to external interwiki. That
2706 // might potentially be used as part of a phishing scheme
2707 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2708 $titleObj = Title
::newMainPage();
2711 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2714 private function getRlClientContext() {
2715 if ( !$this->rlClientContext
) {
2716 $query = ResourceLoader
::makeLoaderQuery(
2717 [], // modules; not relevant
2718 $this->getLanguage()->getCode(),
2719 $this->getSkin()->getSkinName(),
2720 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2721 null, // version; not relevant
2722 ResourceLoader
::inDebugMode(),
2723 null, // only; not relevant
2724 $this->isPrintable(),
2725 $this->getRequest()->getBool( 'handheld' )
2727 $this->rlClientContext
= new ResourceLoaderContext(
2728 $this->getResourceLoader(),
2729 new FauxRequest( $query )
2732 return $this->rlClientContext
;
2736 * Call this to freeze the module queue and JS config and create a formatter.
2738 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2739 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2740 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2741 * the module filters retroactively. Skins and extension hooks may also add modules until very
2742 * late in the request lifecycle.
2744 * @return ResourceLoaderClientHtml
2746 public function getRlClient() {
2747 if ( !$this->rlClient
) {
2748 $context = $this->getRlClientContext();
2749 $rl = $this->getResourceLoader();
2750 $this->addModules( [
2754 $this->addModuleStyles( [
2759 $this->getSkin()->setupSkinUserCss( $this );
2761 // Prepare exempt modules for buildExemptModules()
2762 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2764 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2766 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2767 // Separate user-specific batch for improved cache-hit ratio.
2768 $userBatch = [ 'user.styles', 'user' ];
2769 $siteBatch = array_diff( $moduleStyles, $userBatch );
2770 $dbr = wfGetDB( DB_REPLICA
);
2771 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2772 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2774 // Filter out modules handled by buildExemptModules()
2775 $moduleStyles = array_filter( $moduleStyles,
2776 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2777 $module = $rl->getModule( $name );
2779 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2780 $exemptStates[$name] = 'ready';
2781 // Special case in buildExemptModules()
2784 $group = $module->getGroup();
2785 if ( isset( $exemptGroups[$group] ) ) {
2786 $exemptStates[$name] = 'ready';
2787 if ( !$module->isKnownEmpty( $context ) ) {
2788 // E.g. Don't output empty <styles>
2789 $exemptGroups[$group][] = $name;
2797 $this->rlExemptStyleModules
= $exemptGroups;
2799 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2800 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2801 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2802 if ( !$isUserModuleFiltered ) {
2803 // Manually handled by getBottomScripts()
2804 $userModule = $rl->getModule( 'user' );
2805 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2808 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2811 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2812 $rlClient->setConfig( $this->getJSVars() );
2813 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2814 $rlClient->setModuleStyles( $moduleStyles );
2815 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2816 $rlClient->setExemptStates( $exemptStates );
2817 $this->rlClient
= $rlClient;
2819 return $this->rlClient
;
2823 * @param Skin $sk The given Skin
2824 * @param bool $includeStyle Unused
2825 * @return string The doctype, opening "<html>", and head element.
2827 public function headElement( Skin
$sk, $includeStyle = true ) {
2830 $userdir = $this->getLanguage()->getDir();
2831 $sitedir = $wgContLang->getDir();
2834 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2835 $this->getRlClient()->getDocumentAttributes(),
2836 $sk->getHtmlElementAttributes()
2838 $pieces[] = Html
::openElement( 'head' );
2840 if ( $this->getHTMLTitle() == '' ) {
2841 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2844 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2845 // Add <meta charset="UTF-8">
2846 // This should be before <title> since it defines the charset used by
2847 // text including the text inside <title>.
2848 // The spec recommends defining XHTML5's charset using the XML declaration
2850 // Our XML declaration is output by Html::htmlHeader.
2851 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2852 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2853 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2856 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2857 $pieces[] = $this->getRlClient()->getHeadHtml();
2858 $pieces[] = $this->buildExemptModules();
2859 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2860 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2862 // Use an IE conditional comment to serve the script only to old IE
2863 $pieces[] = '<!--[if lt IE 9]>' .
2864 ResourceLoaderClientHtml
::makeLoad(
2865 ResourceLoaderContext
::newDummyContext(),
2867 ResourceLoaderModule
::TYPE_SCRIPTS
,
2872 $pieces[] = Html
::closeElement( 'head' );
2874 $bodyClasses = $this->mAdditionalBodyClasses
;
2875 $bodyClasses[] = 'mediawiki';
2877 # Classes for LTR/RTL directionality support
2878 $bodyClasses[] = $userdir;
2879 $bodyClasses[] = "sitedir-$sitedir";
2881 $underline = $this->getUser()->getOption( 'underline' );
2882 if ( $underline < 2 ) {
2883 // The following classes can be used here:
2884 // * mw-underline-always
2885 // * mw-underline-never
2886 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2889 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2890 # A <body> class is probably not the best way to do this . . .
2891 $bodyClasses[] = 'capitalize-all-nouns';
2894 // Parser feature migration class
2895 // The idea is that this will eventually be removed, after the wikitext
2896 // which requires it is cleaned up.
2897 $bodyClasses[] = 'mw-hide-empty-elt';
2899 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2900 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2902 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2905 // While the implode() is not strictly needed, it's used for backwards compatibility
2906 // (this used to be built as a string and hooks likely still expect that).
2907 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2909 // Allow skins and extensions to add body attributes they need
2910 $sk->addToBodyAttributes( $this, $bodyAttrs );
2911 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2913 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2915 return self
::combineWrappedStrings( $pieces );
2919 * Get a ResourceLoader object associated with this OutputPage
2921 * @return ResourceLoader
2923 public function getResourceLoader() {
2924 if ( is_null( $this->mResourceLoader
) ) {
2925 $this->mResourceLoader
= new ResourceLoader(
2927 LoggerFactory
::getInstance( 'resourceloader' )
2930 return $this->mResourceLoader
;
2934 * Explicily load or embed modules on a page.
2936 * @param array|string $modules One or more module names
2937 * @param string $only ResourceLoaderModule TYPE_ class constant
2938 * @param array $extraQuery [optional] Array with extra query parameters for the request
2939 * @return string|WrappedStringList HTML
2941 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2942 // Apply 'target' and 'origin' filters
2943 $modules = $this->filterModules( (array)$modules, null, $only );
2945 return ResourceLoaderClientHtml
::makeLoad(
2946 $this->getRlClientContext(),
2954 * Combine WrappedString chunks and filter out empty ones
2956 * @param array $chunks
2957 * @return string|WrappedStringList HTML
2959 protected static function combineWrappedStrings( array $chunks ) {
2960 // Filter out empty values
2961 $chunks = array_filter( $chunks, 'strlen' );
2962 return WrappedString
::join( "\n", $chunks );
2965 private function isUserJsPreview() {
2966 return $this->getConfig()->get( 'AllowUserJs' )
2967 && $this->getTitle()
2968 && $this->getTitle()->isJsSubpage()
2969 && $this->userCanPreview();
2972 protected function isUserCssPreview() {
2973 return $this->getConfig()->get( 'AllowUserCss' )
2974 && $this->getTitle()
2975 && $this->getTitle()->isCssSubpage()
2976 && $this->userCanPreview();
2980 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2981 * legacy scripts ($this->mScripts), and user JS.
2983 * @return string|WrappedStringList HTML
2985 public function getBottomScripts() {
2987 $chunks[] = $this->getRlClient()->getBodyHtml();
2989 // Legacy non-ResourceLoader scripts
2990 $chunks[] = $this->mScripts
;
2992 // Exempt 'user' module
2993 // - May need excludepages for live preview. (T28283)
2994 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2995 // ensures execution is scheduled after the "site" module.
2996 // - Don't load if module state is already resolved as "ready".
2997 if ( $this->rlUserModuleState
=== 'loading' ) {
2998 if ( $this->isUserJsPreview() ) {
2999 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3000 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3002 $chunks[] = ResourceLoader
::makeInlineScript(
3003 Xml
::encodeJsCall( 'mw.loader.using', [
3007 . Xml
::encodeJsCall( '$.globalEval', [
3008 $this->getRequest()->getText( 'wpTextbox1' )
3014 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3015 // asynchronously and may arrive *after* the inline script here. So the previewed code
3016 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3017 // Similarly, when previewing ./common.js and the user module does arrive first,
3018 // it will arrive without common.js and the inline script runs after.
3019 // Thus running common after the excluded subpage.
3022 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3026 if ( $this->limitReportJSData
) {
3027 $chunks[] = ResourceLoader
::makeInlineScript(
3028 ResourceLoader
::makeConfigSetScript(
3029 [ 'wgPageParseReport' => $this->limitReportJSData
]
3034 return self
::combineWrappedStrings( $chunks );
3038 * Get the javascript config vars to include on this page
3040 * @return array Array of javascript config vars
3043 public function getJsConfigVars() {
3044 return $this->mJsConfigVars
;
3048 * Add one or more variables to be set in mw.config in JavaScript
3050 * @param string|array $keys Key or array of key/value pairs
3051 * @param mixed $value [optional] Value of the configuration variable
3053 public function addJsConfigVars( $keys, $value = null ) {
3054 if ( is_array( $keys ) ) {
3055 foreach ( $keys as $key => $value ) {
3056 $this->mJsConfigVars
[$key] = $value;
3061 $this->mJsConfigVars
[$keys] = $value;
3065 * Get an array containing the variables to be set in mw.config in JavaScript.
3067 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3068 * - in other words, page-independent/site-wide variables (without state).
3069 * You will only be adding bloat to the html page and causing page caches to
3070 * have to be purged on configuration changes.
3073 public function getJSVars() {
3078 $canonicalSpecialPageName = false; # T23115
3080 $title = $this->getTitle();
3081 $ns = $title->getNamespace();
3082 $canonicalNamespace = MWNamespace
::exists( $ns )
3083 ? MWNamespace
::getCanonicalName( $ns )
3084 : $title->getNsText();
3086 $sk = $this->getSkin();
3087 // Get the relevant title so that AJAX features can use the correct page name
3088 // when making API requests from certain special pages (T36972).
3089 $relevantTitle = $sk->getRelevantTitle();
3090 $relevantUser = $sk->getRelevantUser();
3092 if ( $ns == NS_SPECIAL
) {
3093 list( $canonicalSpecialPageName, /*...*/ ) =
3094 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3095 } elseif ( $this->canUseWikiPage() ) {
3096 $wikiPage = $this->getWikiPage();
3097 $curRevisionId = $wikiPage->getLatest();
3098 $articleId = $wikiPage->getId();
3101 $lang = $title->getPageViewLanguage();
3103 // Pre-process information
3104 $separatorTransTable = $lang->separatorTransformTable();
3105 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3106 $compactSeparatorTransTable = [
3107 implode( "\t", array_keys( $separatorTransTable ) ),
3108 implode( "\t", $separatorTransTable ),
3110 $digitTransTable = $lang->digitTransformTable();
3111 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3112 $compactDigitTransTable = [
3113 implode( "\t", array_keys( $digitTransTable ) ),
3114 implode( "\t", $digitTransTable ),
3117 $user = $this->getUser();
3120 'wgCanonicalNamespace' => $canonicalNamespace,
3121 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3122 'wgNamespaceNumber' => $title->getNamespace(),
3123 'wgPageName' => $title->getPrefixedDBkey(),
3124 'wgTitle' => $title->getText(),
3125 'wgCurRevisionId' => $curRevisionId,
3126 'wgRevisionId' => (int)$this->getRevisionId(),
3127 'wgArticleId' => $articleId,
3128 'wgIsArticle' => $this->isArticle(),
3129 'wgIsRedirect' => $title->isRedirect(),
3130 'wgAction' => Action
::getActionName( $this->getContext() ),
3131 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3132 'wgUserGroups' => $user->getEffectiveGroups(),
3133 'wgCategories' => $this->getCategories(),
3134 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3135 'wgPageContentLanguage' => $lang->getCode(),
3136 'wgPageContentModel' => $title->getContentModel(),
3137 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3138 'wgDigitTransformTable' => $compactDigitTransTable,
3139 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3140 'wgMonthNames' => $lang->getMonthNamesArray(),
3141 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3142 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3143 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3144 'wgRequestId' => WebRequest
::getRequestId(),
3147 if ( $user->isLoggedIn() ) {
3148 $vars['wgUserId'] = $user->getId();
3149 $vars['wgUserEditCount'] = $user->getEditCount();
3150 $userReg = $user->getRegistration();
3151 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3152 // Get the revision ID of the oldest new message on the user's talk
3153 // page. This can be used for constructing new message alerts on
3155 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3158 if ( $wgContLang->hasVariants() ) {
3159 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3161 // Same test as SkinTemplate
3162 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3163 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3165 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3166 && $relevantTitle->quickUserCan( 'edit', $user )
3167 && ( $relevantTitle->exists() ||
$relevantTitle->quickUserCan( 'create', $user ) );
3169 foreach ( $title->getRestrictionTypes() as $type ) {
3170 // Following keys are set in $vars:
3171 // wgRestrictionCreate, wgRestrictionEdit, wgRestrictionMove, wgRestrictionUpload
3172 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3175 if ( $title->isMainPage() ) {
3176 $vars['wgIsMainPage'] = true;
3179 if ( $this->mRedirectedFrom
) {
3180 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3183 if ( $relevantUser ) {
3184 $vars['wgRelevantUserName'] = $relevantUser->getName();
3187 // Allow extensions to add their custom variables to the mw.config map.
3188 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3189 // page-dependant but site-wide (without state).
3190 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3191 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3193 // Merge in variables from addJsConfigVars last
3194 return array_merge( $vars, $this->getJsConfigVars() );
3198 * To make it harder for someone to slip a user a fake
3199 * user-JavaScript or user-CSS preview, a random token
3200 * is associated with the login session. If it's not
3201 * passed back with the preview request, we won't render
3206 public function userCanPreview() {
3207 $request = $this->getRequest();
3209 $request->getVal( 'action' ) !== 'submit' ||
3210 !$request->getCheck( 'wpPreview' ) ||
3211 !$request->wasPosted()
3216 $user = $this->getUser();
3218 if ( !$user->isLoggedIn() ) {
3219 // Anons have predictable edit tokens
3222 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3226 $title = $this->getTitle();
3227 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
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 if ( $config->get( 'EnableAPI' ) ) {
3356 # Real Simple Discovery link, provides auto-discovery information
3357 # for the MediaWiki API (and potentially additional custom API
3358 # support such as WordPress or Twitter-compatible APIs for a
3359 # blogging extension, etc)
3360 $tags['rsd'] = Html
::element( 'link', [
3362 'type' => 'application/rsd+xml',
3363 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3364 // Whether RSD accepts relative or protocol-relative URLs is completely
3365 // undocumented, though.
3366 'href' => wfExpandUrl( wfAppendQuery(
3368 [ 'action' => 'rsd' ] ),
3375 if ( !$config->get( 'DisableLangConversion' ) ) {
3376 $lang = $this->getTitle()->getPageLanguage();
3377 if ( $lang->hasVariants() ) {
3378 $variants = $lang->getVariants();
3379 foreach ( $variants as $variant ) {
3380 $tags["variant-$variant"] = Html
::element( 'link', [
3381 'rel' => 'alternate',
3382 'hreflang' => LanguageCode
::bcp47( $variant ),
3383 'href' => $this->getTitle()->getLocalURL(
3384 [ 'variant' => $variant ] )
3388 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3389 $tags["variant-x-default"] = Html
::element( 'link', [
3390 'rel' => 'alternate',
3391 'hreflang' => 'x-default',
3392 'href' => $this->getTitle()->getLocalURL() ] );
3397 if ( $this->copyrightUrl
!== null ) {
3398 $copyright = $this->copyrightUrl
;
3401 if ( $config->get( 'RightsPage' ) ) {
3402 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3405 $copyright = $copy->getLocalURL();
3409 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3410 $copyright = $config->get( 'RightsUrl' );
3415 $tags['copyright'] = Html
::element( 'link', [
3417 'href' => $copyright ]
3422 if ( $config->get( 'Feed' ) ) {
3425 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3426 # Use the page name for the title. In principle, this could
3427 # lead to issues with having the same name for different feeds
3428 # corresponding to the same page, but we can't avoid that at
3431 $feedLinks[] = $this->feedLink(
3434 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3436 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3441 # Recent changes feed should appear on every page (except recentchanges,
3442 # that would be redundant). Put it after the per-page feed to avoid
3443 # changing existing behavior. It's still available, probably via a
3444 # menu in your browser. Some sites might have a different feed they'd
3445 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3446 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3447 # If so, use it instead.
3448 $sitename = $config->get( 'Sitename' );
3449 if ( $config->get( 'OverrideSiteFeed' ) ) {
3450 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3451 // Note, this->feedLink escapes the url.
3452 $feedLinks[] = $this->feedLink(
3455 $this->msg( "site-{$type}-feed", $sitename )->text()
3458 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3459 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3460 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3461 $feedLinks[] = $this->feedLink(
3463 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3464 # For grep: 'site-rss-feed', 'site-atom-feed'
3465 $this->msg( "site-{$format}-feed", $sitename )->text()
3470 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3471 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3472 # use OutputPage::addFeedLink() instead.
3473 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3475 $tags +
= $feedLinks;
3479 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3480 if ( $canonicalUrl !== false ) {
3481 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3483 if ( $this->isArticleRelated() ) {
3484 // This affects all requests where "setArticleRelated" is true. This is
3485 // typically all requests that show content (query title, curid, oldid, diff),
3486 // and all wikipage actions (edit, delete, purge, info, history etc.).
3487 // It does not apply to File pages and Special pages.
3488 // 'history' and 'info' actions address page metadata rather than the page
3489 // content itself, so they may not be canonicalized to the view page url.
3490 // TODO: this ought to be better encapsulated in the Action class.
3491 $action = Action
::getActionName( $this->getContext() );
3492 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3493 $query = "action={$action}";
3497 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3499 $reqUrl = $this->getRequest()->getRequestURL();
3500 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3504 if ( $canonicalUrl !== false ) {
3505 $tags[] = Html
::element( 'link', [
3506 'rel' => 'canonical',
3507 'href' => $canonicalUrl
3515 * Generate a "<link rel/>" for a feed.
3517 * @param string $type Feed type
3518 * @param string $url URL to the feed
3519 * @param string $text Value of the "title" attribute
3520 * @return string HTML fragment
3522 private function feedLink( $type, $url, $text ) {
3523 return Html
::element( 'link', [
3524 'rel' => 'alternate',
3525 'type' => "application/$type+xml",
3532 * Add a local or specified stylesheet, with the given media options.
3533 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3535 * @param string $style URL to the file
3536 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3537 * @param string $condition For IE conditional comments, specifying an IE version
3538 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3540 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3543 $options['media'] = $media;
3546 $options['condition'] = $condition;
3549 $options['dir'] = $dir;
3551 $this->styles
[$style] = $options;
3555 * Adds inline CSS styles
3556 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3558 * @param mixed $style_css Inline CSS
3559 * @param string $flip Set to 'flip' to flip the CSS if needed
3561 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3562 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3563 # If wanted, and the interface is right-to-left, flip the CSS
3564 $style_css = CSSJanus
::transform( $style_css, true, false );
3566 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3570 * Build exempt modules and legacy non-ResourceLoader styles.
3572 * @return string|WrappedStringList HTML
3574 protected function buildExemptModules() {
3578 // Things that go after the ResourceLoaderDynamicStyles marker
3581 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3582 if ( $this->isUserCssPreview() ) {
3583 $append[] = $this->makeResourceLoaderLink(
3585 ResourceLoaderModule
::TYPE_STYLES
,
3586 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3589 // Load the previewed CSS. Janus it if needed.
3590 // User-supplied CSS is assumed to in the wiki's content language.
3591 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3592 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3593 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3595 $append[] = Html
::inlineStyle( $previewedCSS );
3598 // We want site, private and user styles to override dynamically added styles from
3599 // general modules, but we want dynamically added styles to override statically added
3600 // style modules. So the order has to be:
3601 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3602 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3603 // - ResourceLoaderDynamicStyles marker
3604 // - site/private/user styles
3606 // Add legacy styles added through addStyle()/addInlineStyle() here
3607 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3609 $chunks[] = Html
::element(
3611 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3614 $separateReq = [ 'site.styles', 'user.styles' ];
3615 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3616 // Combinable modules
3617 $chunks[] = $this->makeResourceLoaderLink(
3618 array_diff( $moduleNames, $separateReq ),
3619 ResourceLoaderModule
::TYPE_STYLES
3622 foreach ( array_intersect( $moduleNames, $separateReq ) as $name ) {
3623 // These require their own dedicated request in order to support "@import"
3624 // syntax, which is incompatible with concatenation. (T147667, T37562)
3625 $chunks[] = $this->makeResourceLoaderLink( $name,
3626 ResourceLoaderModule
::TYPE_STYLES
3631 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3637 public function buildCssLinksArray() {
3640 foreach ( $this->styles
as $file => $options ) {
3641 $link = $this->styleLink( $file, $options );
3643 $links[$file] = $link;
3650 * Generate \<link\> tags for stylesheets
3652 * @param string $style URL to the file
3653 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3654 * @return string HTML fragment
3656 protected function styleLink( $style, array $options ) {
3657 if ( isset( $options['dir'] ) ) {
3658 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3663 if ( isset( $options['media'] ) ) {
3664 $media = self
::transformCssMedia( $options['media'] );
3665 if ( is_null( $media ) ) {
3672 if ( substr( $style, 0, 1 ) == '/' ||
3673 substr( $style, 0, 5 ) == 'http:' ||
3674 substr( $style, 0, 6 ) == 'https:' ) {
3677 $config = $this->getConfig();
3678 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3679 $config->get( 'StyleVersion' );
3682 $link = Html
::linkedStyle( $url, $media );
3684 if ( isset( $options['condition'] ) ) {
3685 $condition = htmlspecialchars( $options['condition'] );
3686 $link = "<!--[if $condition]>$link<![endif]-->";
3692 * Transform path to web-accessible static resource.
3694 * This is used to add a validation hash as query string.
3695 * This aids various behaviors:
3697 * - Put long Cache-Control max-age headers on responses for improved
3698 * cache performance.
3699 * - Get the correct version of a file as expected by the current page.
3700 * - Instantly get the updated version of a file after deployment.
3702 * Avoid using this for urls included in HTML as otherwise clients may get different
3703 * versions of a resource when navigating the site depending on when the page was cached.
3704 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3705 * an external stylesheet).
3708 * @param Config $config
3709 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3710 * @return string URL
3712 public static function transformResourcePath( Config
$config, $path ) {
3716 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3717 if ( $remotePathPrefix === '' ) {
3718 // The configured base path is required to be empty string for
3719 // wikis in the domain root
3722 $remotePath = $remotePathPrefix;
3724 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3725 // - Path is outside wgResourceBasePath, ignore.
3726 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3729 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3730 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3731 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3732 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3733 $uploadPath = $config->get( 'UploadPath' );
3734 if ( strpos( $path, $uploadPath ) === 0 ) {
3735 $localDir = $config->get( 'UploadDirectory' );
3736 $remotePathPrefix = $remotePath = $uploadPath;
3739 $path = RelPath
::getRelativePath( $path, $remotePath );
3740 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3744 * Utility method for transformResourceFilePath().
3746 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3749 * @param string $remotePathPrefix URL path prefix that points to $localPath
3750 * @param string $localPath File directory exposed at $remotePath
3751 * @param string $file Path to target file relative to $localPath
3752 * @return string URL
3754 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3755 $hash = md5_file( "$localPath/$file" );
3756 if ( $hash === false ) {
3757 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3760 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3764 * Transform "media" attribute based on request parameters
3766 * @param string $media Current value of the "media" attribute
3767 * @return string Modified value of the "media" attribute, or null to skip
3770 public static function transformCssMedia( $media ) {
3773 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3774 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3776 // Switch in on-screen display for media testing
3778 'printable' => 'print',
3779 'handheld' => 'handheld',
3781 foreach ( $switches as $switch => $targetMedia ) {
3782 if ( $wgRequest->getBool( $switch ) ) {
3783 if ( $media == $targetMedia ) {
3785 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3786 /* This regex will not attempt to understand a comma-separated media_query_list
3788 * Example supported values for $media:
3789 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3790 * Example NOT supported value for $media:
3791 * '3d-glasses, screen, print and resolution > 90dpi'
3793 * If it's a print request, we never want any kind of screen stylesheets
3794 * If it's a handheld request (currently the only other choice with a switch),
3795 * we don't want simple 'screen' but we might want screen queries that
3796 * have a max-width or something, so we'll pass all others on and let the
3797 * client do the query.
3799 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3810 * Add a wikitext-formatted message to the output.
3811 * This is equivalent to:
3813 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3815 public function addWikiMsg( /*...*/ ) {
3816 $args = func_get_args();
3817 $name = array_shift( $args );
3818 $this->addWikiMsgArray( $name, $args );
3822 * Add a wikitext-formatted message to the output.
3823 * Like addWikiMsg() except the parameters are taken as an array
3824 * instead of a variable argument list.
3826 * @param string $name
3827 * @param array $args
3829 public function addWikiMsgArray( $name, $args ) {
3830 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3834 * This function takes a number of message/argument specifications, wraps them in
3835 * some overall structure, and then parses the result and adds it to the output.
3837 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3838 * and so on. The subsequent arguments may be either
3839 * 1) strings, in which case they are message names, or
3840 * 2) arrays, in which case, within each array, the first element is the message
3841 * name, and subsequent elements are the parameters to that message.
3843 * Don't use this for messages that are not in the user's interface language.
3847 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3851 * $wgOut->addWikiText( "<div class='error'>\n"
3852 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3854 * The newline after the opening div is needed in some wikitext. See T21226.
3856 * @param string $wrap
3858 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3859 $msgSpecs = func_get_args();
3860 array_shift( $msgSpecs );
3861 $msgSpecs = array_values( $msgSpecs );
3863 foreach ( $msgSpecs as $n => $spec ) {
3864 if ( is_array( $spec ) ) {
3866 $name = array_shift( $args );
3867 if ( isset( $args['options'] ) ) {
3868 unset( $args['options'] );
3870 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3878 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3880 $this->addWikiText( $s );
3884 * Whether the output has a table of contents
3888 public function isTOCEnabled() {
3889 return $this->mEnableTOC
;
3893 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3896 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3898 public function enableSectionEditLinks( $flag = true ) {
3899 $this->mEnableSectionEditLinks
= $flag;
3905 * @deprecated since 1.31, use $poOptions to addParserOutput() instead.
3907 public function sectionEditLinksEnabled() {
3908 return $this->mEnableSectionEditLinks
;
3912 * Helper function to setup the PHP implementation of OOUI to use in this request.
3915 * @param String $skinName The Skin name to determine the correct OOUI theme
3916 * @param String $dir Language direction
3918 public static function setupOOUI( $skinName = 'default', $dir = 'ltr' ) {
3919 $themes = ResourceLoaderOOUIModule
::getSkinThemeMap();
3920 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : $themes['default'];
3921 // For example, 'OOUI\WikimediaUITheme'.
3922 $themeClass = "OOUI\\{$theme}Theme";
3923 OOUI\Theme
::setSingleton( new $themeClass() );
3924 OOUI\Element
::setDefaultDir( $dir );
3928 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3929 * MediaWiki and this OutputPage instance.
3933 public function enableOOUI() {
3935 strtolower( $this->getSkin()->getSkinName() ),
3936 $this->getLanguage()->getDir()
3938 $this->addModuleStyles( [
3939 'oojs-ui-core.styles',
3940 'oojs-ui.styles.indicators',
3941 'oojs-ui.styles.textures',
3942 'mediawiki.widgets.styles',
3943 'oojs-ui.styles.icons-content',
3944 'oojs-ui.styles.icons-alerts',
3945 'oojs-ui.styles.icons-interactions',
3950 * Add Link headers for preloading the wiki's logo.
3954 protected function addLogoPreloadLinkHeaders() {
3955 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
3961 if ( !is_array( $logo ) ) {
3962 // No media queries required if we only have one variant
3963 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
3967 if ( isset( $logo['svg'] ) ) {
3968 // No media queries required if we only have a 1x and svg variant
3969 // because all preload-capable browsers support SVGs
3970 $this->addLinkHeader( '<' . $logo['svg'] . '>;rel=preload;as=image' );
3974 foreach ( $logo as $dppx => $src ) {
3975 // Keys are in this format: "1.5x"
3976 $dppx = substr( $dppx, 0, -1 );
3977 $logosPerDppx[$dppx] = $src;
3980 // Because PHP can't have floats as array keys
3981 uksort( $logosPerDppx, function ( $a , $b ) {
3982 $a = floatval( $a );
3983 $b = floatval( $b );
3988 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
3989 return ( $a < $b ) ?
-1 : 1;
3992 foreach ( $logosPerDppx as $dppx => $src ) {
3993 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
3996 $logosCount = count( $logos );
3997 // Logic must match ResourceLoaderSkinModule:
3998 // - 1x applies to resolution < 1.5dppx
3999 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4000 // - 2x applies to resolution >= 2dppx
4001 // Note that min-resolution and max-resolution are both inclusive.
4002 for ( $i = 0; $i < $logosCount; $i++
) {
4005 // min-resolution is ">=" (larger than or equal to)
4006 // "not min-resolution" is essentially "<"
4007 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4008 } elseif ( $i !== $logosCount - 1 ) {
4010 // Media query expressions can only apply "not" to the entire expression
4011 // (e.g. can't express ">= 1.5 and not >= 2).
4012 // Workaround: Use <= 1.9999 in place of < 2.
4013 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4014 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4015 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4018 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4021 $this->addLinkHeader(
4022 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query