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 WrappedString\WrappedString
;
27 use WrappedString\WrappedStringList
;
30 * This class should be covered by a general architecture document which does
31 * not exist as of January 2011. This is one of the Core classes and should
32 * be read at least once by any new developers.
34 * This class is used to prepare the final rendering. A skin is then
35 * applied to the output parameters (links, javascript, html, categories ...).
37 * @todo FIXME: Another class handles sending the whole page to the client.
39 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
44 class OutputPage
extends ContextSource
{
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
49 protected $mLinktags = [];
52 protected $mCanonicalUrl = false;
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
58 protected $mExtStyles = [];
61 * @var string Should be private - has getter and setter. Contains
63 public $mPagetitle = '';
66 * @var string Contains all of the "<body>" content. Should be private we
67 * got set/get accessors and the append() method.
69 public $mBodytext = '';
71 /** @var string Stores contents of "<title>" tag */
72 private $mHTMLtitle = '';
75 * @var bool Is the displayed content related to the source of the
76 * corresponding wiki article.
78 private $mIsarticle = false;
80 /** @var bool Stores "article flag" toggle. */
81 private $mIsArticleRelated = true;
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
87 private $mPrintable = false;
90 * @var array Contains the page subtitle. Special pages usually have some
91 * links here. Don't confuse with site subtitle added by skins.
93 private $mSubtitle = [];
96 public $mRedirect = '';
99 protected $mStatusCode;
102 * @var string Used for sending cache control.
103 * The whole caching system should probably be moved into its own class.
105 protected $mLastModified = '';
108 protected $mCategoryLinks = [];
111 protected $mCategories = [
117 protected $mIndicators = [];
119 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
120 private $mLanguageLinks = [];
123 * Used for JavaScript (predates ResourceLoader)
124 * @todo We should split JS / CSS.
125 * mScripts content is inserted as is in "<head>" by Skin. This might
126 * contain either a link to a stylesheet or inline CSS.
128 private $mScripts = '';
130 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
131 protected $mInlineStyles = '';
134 * @var string Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 public $mPageLinkTitle = '';
139 /** @var array Array of elements in "<head>". Parser might add its own headers! */
140 protected $mHeadItems = [];
143 protected $mModules = [];
146 protected $mModuleScripts = [];
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
161 private $rlUserModuleState;
164 private $rlExemptStyleModules;
167 protected $mJsConfigVars = [];
170 protected $mTemplateIds = [];
173 protected $mImageTimeKeys = [];
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = [
186 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = [];
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
217 protected $mNewSectionLink = false;
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF
;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
248 private $mRevisionTimestamp = null;
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = [];
263 private $mIndexPolicy = 'index';
264 private $mFollowPolicy = 'follow';
265 private $mVaryHeader = [
266 'Accept-Encoding' => [ 'match=gzip' ],
270 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
275 private $mRedirectedFrom = null;
278 * Additional key => value data
280 private $mProperties = [];
283 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
285 private $mTarget = null;
288 * @var bool Whether parser output should contain table of contents
290 private $mEnableTOC = true;
293 * @var bool Whether parser output should contain section edit links
295 private $mEnableSectionEditLinks = true;
298 * @var string|null The URL to send in a <link> element with rel=copyright
300 private $copyrightUrl;
302 /** @var array Profiling data */
303 private $limitReportJSData = [];
306 * Link: header contents
308 private $mLinkHeader = [];
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
314 * @param IContextSource|null $context
316 function __construct( IContextSource
$context = null ) {
317 if ( $context === null ) {
318 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
319 wfDeprecated( __METHOD__
, '1.18' );
321 $this->setContext( $context );
326 * Redirect to $url rather than displaying the normal page
328 * @param string $url URL
329 * @param string $responsecode HTTP status code
331 public function redirect( $url, $responsecode = '302' ) {
332 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
333 $this->mRedirect
= str_replace( "\n", '', $url );
334 $this->mRedirectCode
= $responsecode;
338 * Get the URL to redirect to, or an empty string if not redirect URL set
342 public function getRedirect() {
343 return $this->mRedirect
;
347 * Set the copyright URL to send with the output.
348 * Empty string to omit, null to reset.
352 * @param string|null $url
354 public function setCopyrightUrl( $url ) {
355 $this->copyrightUrl
= $url;
359 * Set the HTTP status code to send with the output.
361 * @param int $statusCode
363 public function setStatusCode( $statusCode ) {
364 $this->mStatusCode
= $statusCode;
368 * Add a new "<meta>" tag
369 * To add an http-equiv meta tag, precede the name with "http:"
371 * @param string $name Tag name
372 * @param string $val Tag value
374 function addMeta( $name, $val ) {
375 array_push( $this->mMetatags
, [ $name, $val ] );
379 * Returns the current <meta> tags
384 public function getMetaTags() {
385 return $this->mMetatags
;
389 * Add a new \<link\> tag to the page header.
391 * Note: use setCanonicalUrl() for rel=canonical.
393 * @param array $linkarr Associative array of attributes.
395 function addLink( array $linkarr ) {
396 array_push( $this->mLinktags
, $linkarr );
400 * Returns the current <link> tags
405 public function getLinkTags() {
406 return $this->mLinktags
;
410 * Add a new \<link\> with "rel" attribute set to "meta"
412 * @param array $linkarr Associative array mapping attribute names to their
413 * values, both keys and values will be escaped, and the
414 * "rel" attribute will be automatically added
416 function addMetadataLink( array $linkarr ) {
417 $linkarr['rel'] = $this->getMetadataAttribute();
418 $this->addLink( $linkarr );
422 * Set the URL to be used for the <link rel=canonical>. This should be used
423 * in preference to addLink(), to avoid duplicate link tags.
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl
= $url;
431 * Returns the URL to be used for the <link rel=canonical> if
435 * @return bool|string
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl
;
442 * Get the value of the "rel" attribute for metadata links
446 public function getMetadataAttribute() {
447 # note: buggy CC software only reads first "meta" link
448 static $haveMeta = false;
450 return 'alternate meta';
458 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
459 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
462 * @param string $script Raw HTML
464 function addScript( $script ) {
465 $this->mScripts
.= $script;
469 * Register and add a stylesheet from an extension directory.
471 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
472 * @param string $url Path to sheet. Provide either a full url (beginning
473 * with 'http', etc) or a relative path from the document root
474 * (beginning with '/'). Otherwise it behaves identically to
475 * addStyle() and draws from the /skins folder.
477 public function addExtensionStyle( $url ) {
478 wfDeprecated( __METHOD__
, '1.27' );
479 array_push( $this->mExtStyles
, $url );
483 * Get all styles added by extensions
485 * @deprecated since 1.27
488 function getExtStyle() {
489 wfDeprecated( __METHOD__
, '1.27' );
490 return $this->mExtStyles
;
494 * Add a JavaScript file out of skins/common, or a given relative path.
495 * Internal use only. Use OutputPage::addModules() if possible.
497 * @param string $file Filename in skins/common or complete on-server path
499 * @param string $version Style version of the file. Defaults to $wgStyleVersion
501 public function addScriptFile( $file, $version = null ) {
502 // See if $file parameter is an absolute URL or begins with a slash
503 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
506 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
508 if ( is_null( $version ) ) {
509 $version = $this->getConfig()->get( 'StyleVersion' );
511 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
515 * Add a self-contained script tag with the given contents
516 * Internal use only. Use OutputPage::addModules() if possible.
518 * @param string $script JavaScript text, no script tags
520 public function addInlineScript( $script ) {
521 $this->mScripts
.= Html
::inlineScript( $script );
525 * Filter an array of modules to remove insufficiently trustworthy members, and modules
526 * which are no longer registered (eg a page is cached before an extension is disabled)
527 * @param array $modules
528 * @param string|null $position If not null, only return modules with this position
529 * @param string $type
532 protected function filterModules( array $modules, $position = null,
533 $type = ResourceLoaderModule
::TYPE_COMBINED
535 $resourceLoader = $this->getResourceLoader();
536 $filteredModules = [];
537 foreach ( $modules as $val ) {
538 $module = $resourceLoader->getModule( $val );
539 if ( $module instanceof ResourceLoaderModule
540 && $module->getOrigin() <= $this->getAllowedModules( $type )
541 && ( is_null( $position ) ||
$module->getPosition() == $position )
543 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
544 $this->warnModuleTargetFilter( $module->getName() );
547 $filteredModules[] = $val;
550 return $filteredModules;
553 private function warnModuleTargetFilter( $moduleName ) {
554 static $warnings = [];
555 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
558 $warnings[$this->mTarget
][$moduleName] = true;
559 $this->getResourceLoader()->getLogger()->debug(
560 'Module "{module}" not loadable on target "{target}".',
562 'module' => $moduleName,
563 'target' => $this->mTarget
,
569 * Get the list of modules to include on this page
571 * @param bool $filter Whether to filter out insufficiently trustworthy modules
572 * @param string|null $position If not null, only return modules with this position
573 * @param string $param
574 * @return array Array of module names
576 public function getModules( $filter = false, $position = null, $param = 'mModules',
577 $type = ResourceLoaderModule
::TYPE_COMBINED
579 $modules = array_values( array_unique( $this->$param ) );
581 ?
$this->filterModules( $modules, $position, $type )
586 * Add one or more modules recognized by ResourceLoader. Modules added
587 * through this function will be loaded by ResourceLoader when the
590 * @param string|array $modules Module name (string) or array of module names
592 public function addModules( $modules ) {
593 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
597 * Get the list of module JS to include on this page
599 * @param bool $filter
600 * @param string|null $position
601 * @return array Array of module names
603 public function getModuleScripts( $filter = false, $position = null ) {
604 return $this->getModules( $filter, $position, 'mModuleScripts',
605 ResourceLoaderModule
::TYPE_SCRIPTS
610 * Add only JS of one or more modules recognized by ResourceLoader. Module
611 * scripts added through this function will be loaded by ResourceLoader when
614 * @param string|array $modules Module name (string) or array of module names
616 public function addModuleScripts( $modules ) {
617 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
621 * Get the list of module CSS to include on this page
623 * @param bool $filter
624 * @param string|null $position
625 * @return array Array of module names
627 public function getModuleStyles( $filter = false, $position = null ) {
628 return $this->getModules( $filter, $position, 'mModuleStyles',
629 ResourceLoaderModule
::TYPE_STYLES
634 * Add only CSS of one or more modules recognized by ResourceLoader.
636 * Module styles added through this function will be added using standard link CSS
637 * tags, rather than as a combined Javascript and CSS package. Thus, they will
638 * load when JavaScript is disabled (unless CSS also happens to be disabled).
640 * @param string|array $modules Module name (string) or array of module names
642 public function addModuleStyles( $modules ) {
643 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
647 * @return null|string ResourceLoader target
649 public function getTarget() {
650 return $this->mTarget
;
654 * Sets ResourceLoader target for load.php links. If null, will be omitted
656 * @param string|null $target
658 public function setTarget( $target ) {
659 $this->mTarget
= $target;
663 * Get an array of head items
667 function getHeadItemsArray() {
668 return $this->mHeadItems
;
672 * Add or replace a head item to the output
674 * Whenever possible, use more specific options like ResourceLoader modules,
675 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
676 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
677 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
678 * This would be your very LAST fallback.
680 * @param string $name Item name
681 * @param string $value Raw HTML
683 public function addHeadItem( $name, $value ) {
684 $this->mHeadItems
[$name] = $value;
688 * Add one or more head items to the output
691 * @param string|string[] $value Raw HTML
693 public function addHeadItems( $values ) {
694 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
698 * Check if the header item $name is already set
700 * @param string $name Item name
703 public function hasHeadItem( $name ) {
704 return isset( $this->mHeadItems
[$name] );
708 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
711 public function setETag( $tag ) {
715 * Set whether the output should only contain the body of the article,
716 * without any skin, sidebar, etc.
717 * Used e.g. when calling with "action=render".
719 * @param bool $only Whether to output only the body of the article
721 public function setArticleBodyOnly( $only ) {
722 $this->mArticleBodyOnly
= $only;
726 * Return whether the output will contain only the body of the article
730 public function getArticleBodyOnly() {
731 return $this->mArticleBodyOnly
;
735 * Set an additional output property
738 * @param string $name
739 * @param mixed $value
741 public function setProperty( $name, $value ) {
742 $this->mProperties
[$name] = $value;
746 * Get an additional output property
749 * @param string $name
750 * @return mixed Property value or null if not found
752 public function getProperty( $name ) {
753 if ( isset( $this->mProperties
[$name] ) ) {
754 return $this->mProperties
[$name];
761 * checkLastModified tells the client to use the client-cached page if
762 * possible. If successful, the OutputPage is disabled so that
763 * any future call to OutputPage->output() have no effect.
765 * Side effect: sets mLastModified for Last-Modified header
767 * @param string $timestamp
769 * @return bool True if cache-ok headers was sent.
771 public function checkLastModified( $timestamp ) {
772 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
773 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
776 $config = $this->getConfig();
777 if ( !$config->get( 'CachePages' ) ) {
778 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
782 $timestamp = wfTimestamp( TS_MW
, $timestamp );
784 'page' => $timestamp,
785 'user' => $this->getUser()->getTouched(),
786 'epoch' => $config->get( 'CacheEpoch' )
788 if ( $config->get( 'UseSquid' ) ) {
789 // T46570: the core page itself may not change, but resources might
790 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
792 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
794 $maxModified = max( $modifiedTimes );
795 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
797 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
798 if ( $clientHeader === false ) {
799 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
803 # IE sends sizes after the date like this:
804 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
805 # this breaks strtotime().
806 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
808 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
809 $clientHeaderTime = strtotime( $clientHeader );
810 MediaWiki\restoreWarnings
();
811 if ( !$clientHeaderTime ) {
813 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
816 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
820 foreach ( $modifiedTimes as $name => $value ) {
821 if ( $info !== '' ) {
824 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
827 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
828 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
829 wfDebug( __METHOD__
. ": effective Last-Modified: " .
830 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
831 if ( $clientHeaderTime < $maxModified ) {
832 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
837 # Give a 304 Not Modified response code and disable body output
838 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
839 ini_set( 'zlib.output_compression', 0 );
840 $this->getRequest()->response()->statusHeader( 304 );
841 $this->sendCacheControl();
844 // Don't output a compressed blob when using ob_gzhandler;
845 // it's technically against HTTP spec and seems to confuse
846 // Firefox when the response gets split over two packets.
847 wfClearOutputBuffers();
853 * Override the last modified timestamp
855 * @param string $timestamp New timestamp, in a format readable by
858 public function setLastModified( $timestamp ) {
859 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
863 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
865 * @param string $policy The literal string to output as the contents of
866 * the meta tag. Will be parsed according to the spec and output in
870 public function setRobotPolicy( $policy ) {
871 $policy = Article
::formatRobotPolicy( $policy );
873 if ( isset( $policy['index'] ) ) {
874 $this->setIndexPolicy( $policy['index'] );
876 if ( isset( $policy['follow'] ) ) {
877 $this->setFollowPolicy( $policy['follow'] );
882 * Set the index policy for the page, but leave the follow policy un-
885 * @param string $policy Either 'index' or 'noindex'.
888 public function setIndexPolicy( $policy ) {
889 $policy = trim( $policy );
890 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
891 $this->mIndexPolicy
= $policy;
896 * Set the follow policy for the page, but leave the index policy un-
899 * @param string $policy Either 'follow' or 'nofollow'.
902 public function setFollowPolicy( $policy ) {
903 $policy = trim( $policy );
904 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
905 $this->mFollowPolicy
= $policy;
910 * Set the new value of the "action text", this will be added to the
911 * "HTML title", separated from it with " - ".
913 * @param string $text New value of the "action text"
915 public function setPageTitleActionText( $text ) {
916 $this->mPageTitleActionText
= $text;
920 * Get the value of the "action text"
924 public function getPageTitleActionText() {
925 return $this->mPageTitleActionText
;
929 * "HTML title" means the contents of "<title>".
930 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
932 * @param string|Message $name
934 public function setHTMLTitle( $name ) {
935 if ( $name instanceof Message
) {
936 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
938 $this->mHTMLtitle
= $name;
943 * Return the "HTML title", i.e. the content of the "<title>" tag.
947 public function getHTMLTitle() {
948 return $this->mHTMLtitle
;
952 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
956 public function setRedirectedFrom( $t ) {
957 $this->mRedirectedFrom
= $t;
961 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
962 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
963 * but not bad tags like \<script\>. This function automatically sets
964 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
965 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
966 * good tags like \<i\> will be dropped entirely.
968 * @param string|Message $name
970 public function setPageTitle( $name ) {
971 if ( $name instanceof Message
) {
972 $name = $name->setContext( $this->getContext() )->text();
975 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
976 # but leave "<i>foobar</i>" alone
977 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
978 $this->mPagetitle
= $nameWithTags;
980 # change "<i>foo&bar</i>" to "foo&bar"
982 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
983 ->inContentLanguage()
988 * Return the "page title", i.e. the content of the \<h1\> tag.
992 public function getPageTitle() {
993 return $this->mPagetitle
;
997 * Set the Title object to use
1001 public function setTitle( Title
$t ) {
1002 $this->getContext()->setTitle( $t );
1006 * Replace the subtitle with $str
1008 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1010 public function setSubtitle( $str ) {
1011 $this->clearSubtitle();
1012 $this->addSubtitle( $str );
1016 * Add $str to the subtitle
1018 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1020 public function addSubtitle( $str ) {
1021 if ( $str instanceof Message
) {
1022 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1024 $this->mSubtitle
[] = $str;
1029 * Build message object for a subtitle containing a backlink to a page
1031 * @param Title $title Title to link to
1032 * @param array $query Array of additional parameters to include in the link
1036 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1037 if ( $title->isRedirect() ) {
1038 $query['redirect'] = 'no';
1040 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1041 return wfMessage( 'backlinksubtitle' )
1042 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1046 * Add a subtitle containing a backlink to a page
1048 * @param Title $title Title to link to
1049 * @param array $query Array of additional parameters to include in the link
1051 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1052 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1056 * Clear the subtitles
1058 public function clearSubtitle() {
1059 $this->mSubtitle
= [];
1067 public function getSubtitle() {
1068 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1072 * Set the page as printable, i.e. it'll be displayed with all
1073 * print styles included
1075 public function setPrintable() {
1076 $this->mPrintable
= true;
1080 * Return whether the page is "printable"
1084 public function isPrintable() {
1085 return $this->mPrintable
;
1089 * Disable output completely, i.e. calling output() will have no effect
1091 public function disable() {
1092 $this->mDoNothing
= true;
1096 * Return whether the output will be completely disabled
1100 public function isDisabled() {
1101 return $this->mDoNothing
;
1105 * Show an "add new section" link?
1109 public function showNewSectionLink() {
1110 return $this->mNewSectionLink
;
1114 * Forcibly hide the new section link?
1118 public function forceHideNewSectionLink() {
1119 return $this->mHideNewSectionLink
;
1123 * Add or remove feed links in the page header
1124 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1125 * for the new version
1126 * @see addFeedLink()
1128 * @param bool $show True: add default feeds, false: remove all feeds
1130 public function setSyndicated( $show = true ) {
1132 $this->setFeedAppendQuery( false );
1134 $this->mFeedLinks
= [];
1139 * Add default feeds to the page header
1140 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1141 * for the new version
1142 * @see addFeedLink()
1144 * @param string $val Query to append to feed links or false to output
1147 public function setFeedAppendQuery( $val ) {
1148 $this->mFeedLinks
= [];
1150 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1151 $query = "feed=$type";
1152 if ( is_string( $val ) ) {
1153 $query .= '&' . $val;
1155 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1160 * Add a feed link to the page header
1162 * @param string $format Feed type, should be a key of $wgFeedClasses
1163 * @param string $href URL
1165 public function addFeedLink( $format, $href ) {
1166 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1167 $this->mFeedLinks
[$format] = $href;
1172 * Should we output feed links for this page?
1175 public function isSyndicated() {
1176 return count( $this->mFeedLinks
) > 0;
1180 * Return URLs for each supported syndication format for this page.
1181 * @return array Associating format keys with URLs
1183 public function getSyndicationLinks() {
1184 return $this->mFeedLinks
;
1188 * Will currently always return null
1192 public function getFeedAppendQuery() {
1193 return $this->mFeedLinksAppendQuery
;
1197 * Set whether the displayed content is related to the source of the
1198 * corresponding article on the wiki
1199 * Setting true will cause the change "article related" toggle to true
1203 public function setArticleFlag( $v ) {
1204 $this->mIsarticle
= $v;
1206 $this->mIsArticleRelated
= $v;
1211 * Return whether the content displayed page is related to the source of
1212 * the corresponding article on the wiki
1216 public function isArticle() {
1217 return $this->mIsarticle
;
1221 * Set whether this page is related an article on the wiki
1222 * Setting false will cause the change of "article flag" toggle to false
1226 public function setArticleRelated( $v ) {
1227 $this->mIsArticleRelated
= $v;
1229 $this->mIsarticle
= false;
1234 * Return whether this page is related an article on the wiki
1238 public function isArticleRelated() {
1239 return $this->mIsArticleRelated
;
1243 * Add new language links
1245 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1246 * (e.g. 'fr:Test page')
1248 public function addLanguageLinks( array $newLinkArray ) {
1249 $this->mLanguageLinks +
= $newLinkArray;
1253 * Reset the language links and add new language links
1255 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1256 * (e.g. 'fr:Test page')
1258 public function setLanguageLinks( array $newLinkArray ) {
1259 $this->mLanguageLinks
= $newLinkArray;
1263 * Get the list of language links
1265 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1267 public function getLanguageLinks() {
1268 return $this->mLanguageLinks
;
1272 * Add an array of categories, with names in the keys
1274 * @param array $categories Mapping category name => sort key
1276 public function addCategoryLinks( array $categories ) {
1279 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1283 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1285 # Set all the values to 'normal'.
1286 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1288 # Mark hidden categories
1289 foreach ( $res as $row ) {
1290 if ( isset( $row->pp_value
) ) {
1291 $categories[$row->page_title
] = 'hidden';
1295 // Avoid PHP 7.1 warning of passing $this by reference
1296 $outputPage = $this;
1297 # Add the remaining categories to the skin
1299 'OutputPageMakeCategoryLinks',
1300 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1302 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1303 foreach ( $categories as $category => $type ) {
1304 // array keys will cast numeric category names to ints, so cast back to string
1305 $category = (string)$category;
1306 $origcategory = $category;
1307 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1311 $wgContLang->findVariantLink( $category, $title, true );
1312 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1315 $text = $wgContLang->convertHtml( $title->getText() );
1316 $this->mCategories
[$type][] = $title->getText();
1317 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1323 * @param array $categories
1324 * @return bool|ResultWrapper
1326 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1327 # Add the links to a LinkBatch
1328 $arr = [ NS_CATEGORY
=> $categories ];
1329 $lb = new LinkBatch
;
1330 $lb->setArray( $arr );
1332 # Fetch existence plus the hiddencat property
1333 $dbr = wfGetDB( DB_REPLICA
);
1334 $fields = array_merge(
1335 LinkCache
::getSelectFields(),
1336 [ 'page_namespace', 'page_title', 'pp_value' ]
1339 $res = $dbr->select( [ 'page', 'page_props' ],
1341 $lb->constructSet( 'page', $dbr ),
1344 [ 'page_props' => [ 'LEFT JOIN', [
1345 'pp_propname' => 'hiddencat',
1350 # Add the results to the link cache
1351 $lb->addResultToCache( LinkCache
::singleton(), $res );
1357 * Reset the category links (but not the category list) and add $categories
1359 * @param array $categories Mapping category name => sort key
1361 public function setCategoryLinks( array $categories ) {
1362 $this->mCategoryLinks
= [];
1363 $this->addCategoryLinks( $categories );
1367 * Get the list of category links, in a 2-D array with the following format:
1368 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1369 * hidden categories) and $link a HTML fragment with a link to the category
1374 public function getCategoryLinks() {
1375 return $this->mCategoryLinks
;
1379 * Get the list of category names this page belongs to.
1381 * @param string $type The type of categories which should be returned. Possible values:
1382 * * all: all categories of all types
1383 * * hidden: only the hidden categories
1384 * * normal: all categories, except hidden categories
1385 * @return array Array of strings
1387 public function getCategories( $type = 'all' ) {
1388 if ( $type === 'all' ) {
1389 $allCategories = [];
1390 foreach ( $this->mCategories
as $categories ) {
1391 $allCategories = array_merge( $allCategories, $categories );
1393 return $allCategories;
1395 if ( !isset( $this->mCategories
[$type] ) ) {
1396 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1398 return $this->mCategories
[$type];
1402 * Add an array of indicators, with their identifiers as array
1403 * keys and HTML contents as values.
1405 * In case of duplicate keys, existing values are overwritten.
1407 * @param array $indicators
1410 public function setIndicators( array $indicators ) {
1411 $this->mIndicators
= $indicators +
$this->mIndicators
;
1412 // Keep ordered by key
1413 ksort( $this->mIndicators
);
1417 * Get the indicators associated with this page.
1419 * The array will be internally ordered by item keys.
1421 * @return array Keys: identifiers, values: HTML contents
1424 public function getIndicators() {
1425 return $this->mIndicators
;
1429 * Adds help link with an icon via page indicators.
1430 * Link target can be overridden by a local message containing a wikilink:
1431 * the message key is: lowercase action or special page name + '-helppage'.
1432 * @param string $to Target MediaWiki.org page title or encoded URL.
1433 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1436 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1437 $this->addModuleStyles( 'mediawiki.helplink' );
1438 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1440 if ( $overrideBaseUrl ) {
1443 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1444 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1447 $link = Html
::rawElement(
1451 'target' => '_blank',
1452 'class' => 'mw-helplink',
1457 $this->setIndicators( [ 'mw-helplink' => $link ] );
1461 * Do not allow scripts which can be modified by wiki users to load on this page;
1462 * only allow scripts bundled with, or generated by, the software.
1463 * Site-wide styles are controlled by a config setting, since they can be
1464 * used to create a custom skin/theme, but not user-specific ones.
1466 * @todo this should be given a more accurate name
1468 public function disallowUserJs() {
1469 $this->reduceAllowedModules(
1470 ResourceLoaderModule
::TYPE_SCRIPTS
,
1471 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1474 // Site-wide styles are controlled by a config setting, see T73621
1475 // for background on why. User styles are never allowed.
1476 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1477 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1479 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1481 $this->reduceAllowedModules(
1482 ResourceLoaderModule
::TYPE_STYLES
,
1488 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1489 * @see ResourceLoaderModule::$origin
1490 * @param string $type ResourceLoaderModule TYPE_ constant
1491 * @return int ResourceLoaderModule ORIGIN_ class constant
1493 public function getAllowedModules( $type ) {
1494 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1495 return min( array_values( $this->mAllowedModules
) );
1497 return isset( $this->mAllowedModules
[$type] )
1498 ?
$this->mAllowedModules
[$type]
1499 : ResourceLoaderModule
::ORIGIN_ALL
;
1504 * Limit the highest level of CSS/JS untrustworthiness allowed.
1506 * If passed the same or a higher level than the current level of untrustworthiness set, the
1507 * level will remain unchanged.
1509 * @param string $type
1510 * @param int $level ResourceLoaderModule class constant
1512 public function reduceAllowedModules( $type, $level ) {
1513 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1517 * Prepend $text to the body HTML
1519 * @param string $text HTML
1521 public function prependHTML( $text ) {
1522 $this->mBodytext
= $text . $this->mBodytext
;
1526 * Append $text to the body HTML
1528 * @param string $text HTML
1530 public function addHTML( $text ) {
1531 $this->mBodytext
.= $text;
1535 * Shortcut for adding an Html::element via addHTML.
1539 * @param string $element
1540 * @param array $attribs
1541 * @param string $contents
1543 public function addElement( $element, array $attribs = [], $contents = '' ) {
1544 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1548 * Clear the body HTML
1550 public function clearHTML() {
1551 $this->mBodytext
= '';
1557 * @return string HTML
1559 public function getHTML() {
1560 return $this->mBodytext
;
1564 * Get/set the ParserOptions object to use for wikitext parsing
1566 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1567 * current ParserOption object
1568 * @return ParserOptions
1570 public function parserOptions( $options = null ) {
1571 if ( $options !== null && !empty( $options->isBogus
) ) {
1572 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1573 // been changed somehow, and keep it if so.
1574 $anonPO = ParserOptions
::newFromAnon();
1575 $anonPO->setEditSection( false );
1576 $anonPO->setAllowUnsafeRawHtml( false );
1577 if ( !$options->matches( $anonPO ) ) {
1578 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1579 $options->isBogus
= false;
1583 if ( !$this->mParserOptions
) {
1584 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1585 // $wgUser isn't unstubbable yet, so don't try to get a
1586 // ParserOptions for it. And don't cache this ParserOptions
1588 $po = ParserOptions
::newFromAnon();
1589 $po->setEditSection( false );
1590 $po->setAllowUnsafeRawHtml( false );
1591 $po->isBogus
= true;
1592 if ( $options !== null ) {
1593 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1598 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1599 $this->mParserOptions
->setEditSection( false );
1600 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1603 if ( $options !== null && !empty( $options->isBogus
) ) {
1604 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1606 return wfSetVar( $this->mParserOptions
, null, true );
1608 return wfSetVar( $this->mParserOptions
, $options );
1613 * Set the revision ID which will be seen by the wiki text parser
1614 * for things such as embedded {{REVISIONID}} variable use.
1616 * @param int|null $revid An positive integer, or null
1617 * @return mixed Previous value
1619 public function setRevisionId( $revid ) {
1620 $val = is_null( $revid ) ?
null : intval( $revid );
1621 return wfSetVar( $this->mRevisionId
, $val );
1625 * Get the displayed revision ID
1629 public function getRevisionId() {
1630 return $this->mRevisionId
;
1634 * Set the timestamp of the revision which will be displayed. This is used
1635 * to avoid a extra DB call in Skin::lastModified().
1637 * @param string|null $timestamp
1638 * @return mixed Previous value
1640 public function setRevisionTimestamp( $timestamp ) {
1641 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1645 * Get the timestamp of displayed revision.
1646 * This will be null if not filled by setRevisionTimestamp().
1648 * @return string|null
1650 public function getRevisionTimestamp() {
1651 return $this->mRevisionTimestamp
;
1655 * Set the displayed file version
1657 * @param File|bool $file
1658 * @return mixed Previous value
1660 public function setFileVersion( $file ) {
1662 if ( $file instanceof File
&& $file->exists() ) {
1663 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1665 return wfSetVar( $this->mFileVersion
, $val, true );
1669 * Get the displayed file version
1671 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1673 public function getFileVersion() {
1674 return $this->mFileVersion
;
1678 * Get the templates used on this page
1680 * @return array (namespace => dbKey => revId)
1683 public function getTemplateIds() {
1684 return $this->mTemplateIds
;
1688 * Get the files used on this page
1690 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1693 public function getFileSearchOptions() {
1694 return $this->mImageTimeKeys
;
1698 * Convert wikitext to HTML and add it to the buffer
1699 * Default assumes that the current page title will be used.
1701 * @param string $text
1702 * @param bool $linestart Is this the start of a line?
1703 * @param bool $interface Is this text in the user interface language?
1704 * @throws MWException
1706 public function addWikiText( $text, $linestart = true, $interface = true ) {
1707 $title = $this->getTitle(); // Work around E_STRICT
1709 throw new MWException( 'Title is null' );
1711 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1715 * Add wikitext with a custom Title object
1717 * @param string $text Wikitext
1718 * @param Title $title
1719 * @param bool $linestart Is this the start of a line?
1721 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1722 $this->addWikiTextTitle( $text, $title, $linestart );
1726 * Add wikitext with a custom Title object and tidy enabled.
1728 * @param string $text Wikitext
1729 * @param Title $title
1730 * @param bool $linestart Is this the start of a line?
1732 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1733 $this->addWikiTextTitle( $text, $title, $linestart, true );
1737 * Add wikitext with tidy enabled
1739 * @param string $text Wikitext
1740 * @param bool $linestart Is this the start of a line?
1742 public function addWikiTextTidy( $text, $linestart = true ) {
1743 $title = $this->getTitle();
1744 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1748 * Add wikitext with a custom Title object
1750 * @param string $text Wikitext
1751 * @param Title $title
1752 * @param bool $linestart Is this the start of a line?
1753 * @param bool $tidy Whether to use tidy
1754 * @param bool $interface Whether it is an interface message
1755 * (for example disables conversion)
1757 public function addWikiTextTitle( $text, Title
$title, $linestart,
1758 $tidy = false, $interface = false
1762 $popts = $this->parserOptions();
1763 $oldTidy = $popts->setTidy( $tidy );
1764 $popts->setInterfaceMessage( (bool)$interface );
1766 $parserOutput = $wgParser->getFreshParser()->parse(
1767 $text, $title, $popts,
1768 $linestart, true, $this->mRevisionId
1771 $popts->setTidy( $oldTidy );
1773 $this->addParserOutput( $parserOutput );
1777 * Add a ParserOutput object, but without Html.
1779 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1780 * @param ParserOutput $parserOutput
1782 public function addParserOutputNoText( $parserOutput ) {
1783 wfDeprecated( __METHOD__
, '1.24' );
1784 $this->addParserOutputMetadata( $parserOutput );
1788 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1789 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1793 * @param ParserOutput $parserOutput
1795 public function addParserOutputMetadata( $parserOutput ) {
1796 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1797 $this->addCategoryLinks( $parserOutput->getCategories() );
1798 $this->setIndicators( $parserOutput->getIndicators() );
1799 $this->mNewSectionLink
= $parserOutput->getNewSection();
1800 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1802 if ( !$parserOutput->isCacheable() ) {
1803 $this->enableClientCache( false );
1805 $this->mNoGallery
= $parserOutput->getNoGallery();
1806 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1807 $this->addModules( $parserOutput->getModules() );
1808 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1809 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1810 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1811 $this->mPreventClickjacking
= $this->mPreventClickjacking
1812 ||
$parserOutput->preventClickjacking();
1814 // Template versioning...
1815 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1816 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1817 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1819 $this->mTemplateIds
[$ns] = $dbks;
1822 // File versioning...
1823 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1824 $this->mImageTimeKeys
[$dbk] = $data;
1827 // Hooks registered in the object
1828 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1829 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1830 list( $hookName, $data ) = $hookInfo;
1831 if ( isset( $parserOutputHooks[$hookName] ) ) {
1832 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1836 // Enable OOUI if requested via ParserOutput
1837 if ( $parserOutput->getEnableOOUI() ) {
1838 $this->enableOOUI();
1841 // Include parser limit report
1842 if ( !$this->limitReportJSData
) {
1843 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1846 // Link flags are ignored for now, but may in the future be
1847 // used to mark individual language links.
1849 // Avoid PHP 7.1 warning of passing $this by reference
1850 $outputPage = $this;
1851 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1852 Hooks
::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1856 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1857 * ParserOutput object, without any other metadata.
1860 * @param ParserOutput $parserOutput
1862 public function addParserOutputContent( $parserOutput ) {
1863 $this->addParserOutputText( $parserOutput );
1865 $this->addModules( $parserOutput->getModules() );
1866 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1867 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1869 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1873 * Add the HTML associated with a ParserOutput object, without any metadata.
1876 * @param ParserOutput $parserOutput
1878 public function addParserOutputText( $parserOutput ) {
1879 $text = $parserOutput->getText();
1880 // Avoid PHP 7.1 warning of passing $this by reference
1881 $outputPage = $this;
1882 Hooks
::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1883 $this->addHTML( $text );
1887 * Add everything from a ParserOutput object.
1889 * @param ParserOutput $parserOutput
1891 function addParserOutput( $parserOutput ) {
1892 $this->addParserOutputMetadata( $parserOutput );
1893 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1895 // Touch section edit links only if not previously disabled
1896 if ( $parserOutput->getEditSectionTokens() ) {
1897 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1900 $this->addParserOutputText( $parserOutput );
1904 * Add the output of a QuickTemplate to the output buffer
1906 * @param QuickTemplate $template
1908 public function addTemplate( &$template ) {
1909 $this->addHTML( $template->getHTML() );
1913 * Parse wikitext and return the HTML.
1915 * @param string $text
1916 * @param bool $linestart Is this the start of a line?
1917 * @param bool $interface Use interface language ($wgLang instead of
1918 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1919 * This also disables LanguageConverter.
1920 * @param Language $language Target language object, will override $interface
1921 * @throws MWException
1922 * @return string HTML
1924 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1927 if ( is_null( $this->getTitle() ) ) {
1928 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1931 $popts = $this->parserOptions();
1933 $popts->setInterfaceMessage( true );
1935 if ( $language !== null ) {
1936 $oldLang = $popts->setTargetLanguage( $language );
1939 $parserOutput = $wgParser->getFreshParser()->parse(
1940 $text, $this->getTitle(), $popts,
1941 $linestart, true, $this->mRevisionId
1945 $popts->setInterfaceMessage( false );
1947 if ( $language !== null ) {
1948 $popts->setTargetLanguage( $oldLang );
1951 return $parserOutput->getText();
1955 * Parse wikitext, strip paragraphs, and return the HTML.
1957 * @param string $text
1958 * @param bool $linestart Is this the start of a line?
1959 * @param bool $interface Use interface language ($wgLang instead of
1960 * $wgContLang) while parsing language sensitive magic
1961 * words like GRAMMAR and PLURAL
1962 * @return string HTML
1964 public function parseInline( $text, $linestart = true, $interface = false ) {
1965 $parsed = $this->parse( $text, $linestart, $interface );
1966 return Parser
::stripOuterParagraph( $parsed );
1971 * @deprecated since 1.27 Use setCdnMaxage() instead
1973 public function setSquidMaxage( $maxage ) {
1974 $this->setCdnMaxage( $maxage );
1978 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1980 * @param int $maxage Maximum cache time on the CDN, in seconds.
1982 public function setCdnMaxage( $maxage ) {
1983 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1987 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1989 * @param int $maxage Maximum cache time on the CDN, in seconds
1992 public function lowerCdnMaxage( $maxage ) {
1993 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1994 $this->setCdnMaxage( $this->mCdnMaxage
);
1998 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2000 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2001 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2002 * TTL is 90% of the age of the object, subject to the min and max.
2004 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
2005 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
2006 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2007 * @return integer TTL in seconds
2010 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2011 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2012 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2014 if ( $mtime === null ||
$mtime === false ) {
2015 return $minTTL; // entity does not exist
2018 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2019 $adaptiveTTL = max( .9 * $age, $minTTL );
2020 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2022 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2024 return $adaptiveTTL;
2028 * Use enableClientCache(false) to force it to send nocache headers
2030 * @param bool $state
2034 public function enableClientCache( $state ) {
2035 return wfSetVar( $this->mEnableClientCache
, $state );
2039 * Get the list of cookies that will influence on the cache
2043 function getCacheVaryCookies() {
2045 if ( $cookies === null ) {
2046 $config = $this->getConfig();
2047 $cookies = array_merge(
2048 SessionManager
::singleton()->getVaryCookies(),
2052 $config->get( 'CacheVaryCookies' )
2054 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2060 * Check if the request has a cache-varying cookie header
2061 * If it does, it's very important that we don't allow public caching
2065 function haveCacheVaryCookies() {
2066 $request = $this->getRequest();
2067 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2068 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2069 wfDebug( __METHOD__
. ": found $cookieName\n" );
2073 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2078 * Add an HTTP header that will influence on the cache
2080 * @param string $header Header name
2081 * @param string[]|null $option Options for the Key header. See
2082 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2083 * for the list of valid options.
2085 public function addVaryHeader( $header, array $option = null ) {
2086 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2087 $this->mVaryHeader
[$header] = [];
2089 if ( !is_array( $option ) ) {
2092 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2096 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2097 * such as Accept-Encoding or Cookie
2101 public function getVaryHeader() {
2102 // If we vary on cookies, let's make sure it's always included here too.
2103 if ( $this->getCacheVaryCookies() ) {
2104 $this->addVaryHeader( 'Cookie' );
2107 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2108 $this->addVaryHeader( $header, $options );
2110 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2114 * Add an HTTP Link: header
2116 * @param string $header Header value
2118 public function addLinkHeader( $header ) {
2119 $this->mLinkHeader
[] = $header;
2123 * Return a Link: header. Based on the values of $mLinkHeader.
2127 public function getLinkHeader() {
2128 if ( !$this->mLinkHeader
) {
2132 return 'Link: ' . implode( ',', $this->mLinkHeader
);
2136 * Get a complete Key header
2140 public function getKeyHeader() {
2141 $cvCookies = $this->getCacheVaryCookies();
2143 $cookiesOption = [];
2144 foreach ( $cvCookies as $cookieName ) {
2145 $cookiesOption[] = 'param=' . $cookieName;
2147 $this->addVaryHeader( 'Cookie', $cookiesOption );
2149 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2150 $this->addVaryHeader( $header, $options );
2154 foreach ( $this->mVaryHeader
as $header => $option ) {
2155 $newheader = $header;
2156 if ( is_array( $option ) && count( $option ) > 0 ) {
2157 $newheader .= ';' . implode( ';', $option );
2159 $headers[] = $newheader;
2161 $key = 'Key: ' . implode( ',', $headers );
2167 * T23672: Add Accept-Language to Vary and Key headers
2168 * if there's no 'variant' parameter existed in GET.
2171 * /w/index.php?title=Main_page should always be served; but
2172 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2174 function addAcceptLanguage() {
2175 $title = $this->getTitle();
2176 if ( !$title instanceof Title
) {
2180 $lang = $title->getPageLanguage();
2181 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2182 $variants = $lang->getVariants();
2184 foreach ( $variants as $variant ) {
2185 if ( $variant === $lang->getCode() ) {
2188 $aloption[] = 'substr=' . $variant;
2190 // IE and some other browsers use BCP 47 standards in
2191 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2192 // We should handle these too.
2193 $variantBCP47 = wfBCP47( $variant );
2194 if ( $variantBCP47 !== $variant ) {
2195 $aloption[] = 'substr=' . $variantBCP47;
2199 $this->addVaryHeader( 'Accept-Language', $aloption );
2204 * Set a flag which will cause an X-Frame-Options header appropriate for
2205 * edit pages to be sent. The header value is controlled by
2206 * $wgEditPageFrameOptions.
2208 * This is the default for special pages. If you display a CSRF-protected
2209 * form on an ordinary view page, then you need to call this function.
2211 * @param bool $enable
2213 public function preventClickjacking( $enable = true ) {
2214 $this->mPreventClickjacking
= $enable;
2218 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2219 * This can be called from pages which do not contain any CSRF-protected
2222 public function allowClickjacking() {
2223 $this->mPreventClickjacking
= false;
2227 * Get the prevent-clickjacking flag
2232 public function getPreventClickjacking() {
2233 return $this->mPreventClickjacking
;
2237 * Get the X-Frame-Options header value (without the name part), or false
2238 * if there isn't one. This is used by Skin to determine whether to enable
2239 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2241 * @return string|false
2243 public function getFrameOptions() {
2244 $config = $this->getConfig();
2245 if ( $config->get( 'BreakFrames' ) ) {
2247 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2248 return $config->get( 'EditPageFrameOptions' );
2254 * Send cache control HTTP headers
2256 public function sendCacheControl() {
2257 $response = $this->getRequest()->response();
2258 $config = $this->getConfig();
2260 $this->addVaryHeader( 'Cookie' );
2261 $this->addAcceptLanguage();
2263 # don't serve compressed data to clients who can't handle it
2264 # maintain different caches for logged-in users and non-logged in ones
2265 $response->header( $this->getVaryHeader() );
2267 if ( $config->get( 'UseKeyHeader' ) ) {
2268 $response->header( $this->getKeyHeader() );
2271 if ( $this->mEnableClientCache
) {
2273 $config->get( 'UseSquid' ) &&
2274 !$response->hasCookies() &&
2275 !SessionManager
::getGlobalSession()->isPersistent() &&
2276 !$this->isPrintable() &&
2277 $this->mCdnMaxage
!= 0 &&
2278 !$this->haveCacheVaryCookies()
2280 if ( $config->get( 'UseESI' ) ) {
2281 # We'll purge the proxy cache explicitly, but require end user agents
2282 # to revalidate against the proxy on each visit.
2283 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2284 wfDebug( __METHOD__
.
2285 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2286 # start with a shorter timeout for initial testing
2287 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2289 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2290 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2292 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2294 # We'll purge the proxy cache for anons explicitly, but require end user agents
2295 # to revalidate against the proxy on each visit.
2296 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2297 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2298 wfDebug( __METHOD__
.
2299 ": local proxy caching; {$this->mLastModified} **", 'private' );
2300 # start with a shorter timeout for initial testing
2301 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2302 $response->header( "Cache-Control: " .
2303 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2306 # We do want clients to cache if they can, but they *must* check for updates
2307 # on revisiting the page.
2308 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2309 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2310 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2312 if ( $this->mLastModified
) {
2313 $response->header( "Last-Modified: {$this->mLastModified}" );
2316 wfDebug( __METHOD__
. ": no caching **", 'private' );
2318 # In general, the absence of a last modified header should be enough to prevent
2319 # the client from using its cache. We send a few other things just to make sure.
2320 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2321 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2322 $response->header( 'Pragma: no-cache' );
2327 * Finally, all the text has been munged and accumulated into
2328 * the object, let's actually output it:
2330 * @param bool $return Set to true to get the result as a string rather than sending it
2331 * @return string|null
2333 * @throws FatalError
2334 * @throws MWException
2336 public function output( $return = false ) {
2339 if ( $this->mDoNothing
) {
2340 return $return ?
'' : null;
2343 $response = $this->getRequest()->response();
2344 $config = $this->getConfig();
2346 if ( $this->mRedirect
!= '' ) {
2347 # Standards require redirect URLs to be absolute
2348 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2350 $redirect = $this->mRedirect
;
2351 $code = $this->mRedirectCode
;
2353 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2354 if ( $code == '301' ||
$code == '303' ) {
2355 if ( !$config->get( 'DebugRedirects' ) ) {
2356 $response->statusHeader( $code );
2358 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2360 if ( $config->get( 'VaryOnXFP' ) ) {
2361 $this->addVaryHeader( 'X-Forwarded-Proto' );
2363 $this->sendCacheControl();
2365 $response->header( "Content-Type: text/html; charset=utf-8" );
2366 if ( $config->get( 'DebugRedirects' ) ) {
2367 $url = htmlspecialchars( $redirect );
2368 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2369 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2370 print "</body>\n</html>\n";
2372 $response->header( 'Location: ' . $redirect );
2376 return $return ?
'' : null;
2377 } elseif ( $this->mStatusCode
) {
2378 $response->statusHeader( $this->mStatusCode
);
2381 # Buffer output; final headers may depend on later processing
2384 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2385 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2387 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2388 // jQuery etc. can work correctly.
2389 $response->header( 'X-UA-Compatible: IE=Edge' );
2391 $this->addLogoPreloadLinkHeaders();
2392 $linkHeader = $this->getLinkHeader();
2393 if ( $linkHeader ) {
2394 $response->header( $linkHeader );
2397 // Prevent framing, if requested
2398 $frameOptions = $this->getFrameOptions();
2399 if ( $frameOptions ) {
2400 $response->header( "X-Frame-Options: $frameOptions" );
2403 if ( $this->mArticleBodyOnly
) {
2404 echo $this->mBodytext
;
2406 // Enable safe mode if requested
2407 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2408 $this->disallowUserJs();
2411 $sk = $this->getSkin();
2412 // add skin specific modules
2413 $modules = $sk->getDefaultModules();
2415 // Enforce various default modules for all pages and all skins
2417 // Keep this list as small as possible
2419 'mediawiki.page.startup',
2423 // Support for high-density display images if enabled
2424 if ( $config->get( 'ResponsiveImages' ) ) {
2425 $coreModules[] = 'mediawiki.hidpi';
2428 $this->addModules( $coreModules );
2429 foreach ( $modules as $group ) {
2430 $this->addModules( $group );
2432 MWDebug
::addModules( $this );
2434 // Avoid PHP 7.1 warning of passing $this by reference
2435 $outputPage = $this;
2436 // Hook that allows last minute changes to the output page, e.g.
2437 // adding of CSS or Javascript by extensions.
2438 Hooks
::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2442 } catch ( Exception
$e ) {
2443 ob_end_clean(); // bug T129657
2449 // This hook allows last minute changes to final overall output by modifying output buffer
2450 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2451 } catch ( Exception
$e ) {
2452 ob_end_clean(); // bug T129657
2456 $this->sendCacheControl();
2459 return ob_get_clean();
2467 * Prepare this object to display an error page; disable caching and
2468 * indexing, clear the current text and redirect, set the page's title
2469 * and optionally an custom HTML title (content of the "<title>" tag).
2471 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2472 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2473 * optional, if not passed the "<title>" attribute will be
2474 * based on $pageTitle
2476 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2477 $this->setPageTitle( $pageTitle );
2478 if ( $htmlTitle !== false ) {
2479 $this->setHTMLTitle( $htmlTitle );
2481 $this->setRobotPolicy( 'noindex,nofollow' );
2482 $this->setArticleRelated( false );
2483 $this->enableClientCache( false );
2484 $this->mRedirect
= '';
2485 $this->clearSubtitle();
2490 * Output a standard error page
2492 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2493 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2494 * showErrorPage( 'titlemsg', $messageObject );
2495 * showErrorPage( $titleMessageObject, $messageObject );
2497 * @param string|Message $title Message key (string) for page title, or a Message object
2498 * @param string|Message $msg Message key (string) for page text, or a Message object
2499 * @param array $params Message parameters; ignored if $msg is a Message object
2501 public function showErrorPage( $title, $msg, $params = [] ) {
2502 if ( !$title instanceof Message
) {
2503 $title = $this->msg( $title );
2506 $this->prepareErrorPage( $title );
2508 if ( $msg instanceof Message
) {
2509 if ( $params !== [] ) {
2510 trigger_error( 'Argument ignored: $params. The message parameters argument '
2511 . 'is discarded when the $msg argument is a Message object instead of '
2512 . 'a string.', E_USER_NOTICE
);
2514 $this->addHTML( $msg->parseAsBlock() );
2516 $this->addWikiMsgArray( $msg, $params );
2519 $this->returnToMain();
2523 * Output a standard permission error page
2525 * @param array $errors Error message keys or [key, param...] arrays
2526 * @param string $action Action that was denied or null if unknown
2528 public function showPermissionsErrorPage( array $errors, $action = null ) {
2529 foreach ( $errors as $key => $error ) {
2530 $errors[$key] = (array)$error;
2533 // For some action (read, edit, create and upload), display a "login to do this action"
2534 // error if all of the following conditions are met:
2535 // 1. the user is not logged in
2536 // 2. the only error is insufficient permissions (i.e. no block or something else)
2537 // 3. the error can be avoided simply by logging in
2538 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2539 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2540 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2541 && ( User
::groupHasPermission( 'user', $action )
2542 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2544 $displayReturnto = null;
2546 # Due to T34276, if a user does not have read permissions,
2547 # $this->getTitle() will just give Special:Badtitle, which is
2548 # not especially useful as a returnto parameter. Use the title
2549 # from the request instead, if there was one.
2550 $request = $this->getRequest();
2551 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2552 if ( $action == 'edit' ) {
2553 $msg = 'whitelistedittext';
2554 $displayReturnto = $returnto;
2555 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2556 $msg = 'nocreatetext';
2557 } elseif ( $action == 'upload' ) {
2558 $msg = 'uploadnologintext';
2560 $msg = 'loginreqpagetext';
2561 $displayReturnto = Title
::newMainPage();
2567 $query['returnto'] = $returnto->getPrefixedText();
2569 if ( !$request->wasPosted() ) {
2570 $returntoquery = $request->getValues();
2571 unset( $returntoquery['title'] );
2572 unset( $returntoquery['returnto'] );
2573 unset( $returntoquery['returntoquery'] );
2574 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2577 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2578 $loginLink = $linkRenderer->makeKnownLink(
2579 SpecialPage
::getTitleFor( 'Userlogin' ),
2580 $this->msg( 'loginreqlink' )->text(),
2585 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2586 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2588 # Don't return to a page the user can't read otherwise
2589 # we'll end up in a pointless loop
2590 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2591 $this->returnToMain( null, $displayReturnto );
2594 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2595 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2600 * Display an error page indicating that a given version of MediaWiki is
2601 * required to use it
2603 * @param mixed $version The version of MediaWiki needed to use the page
2605 public function versionRequired( $version ) {
2606 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2608 $this->addWikiMsg( 'versionrequiredtext', $version );
2609 $this->returnToMain();
2613 * Format a list of error messages
2615 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2616 * @param string $action Action that was denied or null if unknown
2617 * @return string The wikitext error-messages, formatted into a list.
2619 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2620 if ( $action == null ) {
2621 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2623 $action_desc = $this->msg( "action-$action" )->plain();
2625 'permissionserrorstext-withaction',
2628 )->plain() . "\n\n";
2631 if ( count( $errors ) > 1 ) {
2632 $text .= '<ul class="permissions-errors">' . "\n";
2634 foreach ( $errors as $error ) {
2636 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2641 $text .= "<div class=\"permissions-errors\">\n" .
2642 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2650 * Display a page stating that the Wiki is in read-only mode.
2651 * Should only be called after wfReadOnly() has returned true.
2653 * Historically, this function was used to show the source of the page that the user
2654 * was trying to edit and _also_ permissions error messages. The relevant code was
2655 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2657 * @deprecated since 1.25; throw the exception directly
2658 * @throws ReadOnlyError
2660 public function readOnlyPage() {
2661 if ( func_num_args() > 0 ) {
2662 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2665 throw new ReadOnlyError
;
2669 * Turn off regular page output and return an error response
2670 * for when rate limiting has triggered.
2672 * @deprecated since 1.25; throw the exception directly
2674 public function rateLimited() {
2675 wfDeprecated( __METHOD__
, '1.25' );
2676 throw new ThrottledError
;
2680 * Show a warning about replica DB lag
2682 * If the lag is higher than $wgSlaveLagCritical seconds,
2683 * then the warning is a bit more obvious. If the lag is
2684 * lower than $wgSlaveLagWarning, then no warning is shown.
2686 * @param int $lag Slave lag
2688 public function showLagWarning( $lag ) {
2689 $config = $this->getConfig();
2690 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2691 $lag = floor( $lag ); // floor to avoid nano seconds to display
2692 $message = $lag < $config->get( 'SlaveLagCritical' )
2695 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2696 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2700 public function showFatalError( $message ) {
2701 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2703 $this->addHTML( $message );
2706 public function showUnexpectedValueError( $name, $val ) {
2707 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2710 public function showFileCopyError( $old, $new ) {
2711 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2714 public function showFileRenameError( $old, $new ) {
2715 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2718 public function showFileDeleteError( $name ) {
2719 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2722 public function showFileNotFoundError( $name ) {
2723 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2727 * Add a "return to" link pointing to a specified title
2729 * @param Title $title Title to link
2730 * @param array $query Query string parameters
2731 * @param string $text Text of the link (input is not escaped)
2732 * @param array $options Options array to pass to Linker
2734 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2735 $linkRenderer = MediaWikiServices
::getInstance()
2736 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2737 $link = $this->msg( 'returnto' )->rawParams(
2738 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2739 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2743 * Add a "return to" link pointing to a specified title,
2744 * or the title indicated in the request, or else the main page
2746 * @param mixed $unused
2747 * @param Title|string $returnto Title or String to return to
2748 * @param string $returntoquery Query string for the return to link
2750 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2751 if ( $returnto == null ) {
2752 $returnto = $this->getRequest()->getText( 'returnto' );
2755 if ( $returntoquery == null ) {
2756 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2759 if ( $returnto === '' ) {
2760 $returnto = Title
::newMainPage();
2763 if ( is_object( $returnto ) ) {
2764 $titleObj = $returnto;
2766 $titleObj = Title
::newFromText( $returnto );
2768 // We don't want people to return to external interwiki. That
2769 // might potentially be used as part of a phishing scheme
2770 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2771 $titleObj = Title
::newMainPage();
2774 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2777 private function getRlClientContext() {
2778 if ( !$this->rlClientContext
) {
2779 $query = ResourceLoader
::makeLoaderQuery(
2780 [], // modules; not relevant
2781 $this->getLanguage()->getCode(),
2782 $this->getSkin()->getSkinName(),
2783 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2784 null, // version; not relevant
2785 ResourceLoader
::inDebugMode(),
2786 null, // only; not relevant
2787 $this->isPrintable(),
2788 $this->getRequest()->getBool( 'handheld' )
2790 $this->rlClientContext
= new ResourceLoaderContext(
2791 $this->getResourceLoader(),
2792 new FauxRequest( $query )
2795 return $this->rlClientContext
;
2799 * Call this to freeze the module queue and JS config and create a formatter.
2801 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2802 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2803 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2804 * the module filters retroactively. Skins and extension hooks may also add modules until very
2805 * late in the request lifecycle.
2807 * @return ResourceLoaderClientHtml
2809 public function getRlClient() {
2810 if ( !$this->rlClient
) {
2811 $context = $this->getRlClientContext();
2812 $rl = $this->getResourceLoader();
2813 $this->addModules( [
2817 $this->addModuleStyles( [
2822 $this->getSkin()->setupSkinUserCss( $this );
2824 // Prepare exempt modules for buildExemptModules()
2825 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2827 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2829 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2830 // Separate user-specific batch for improved cache-hit ratio.
2831 $userBatch = [ 'user.styles', 'user' ];
2832 $siteBatch = array_diff( $moduleStyles, $userBatch );
2833 $dbr = wfGetDB( DB_REPLICA
);
2834 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2835 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2837 // Filter out modules handled by buildExemptModules()
2838 $moduleStyles = array_filter( $moduleStyles,
2839 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2840 $module = $rl->getModule( $name );
2842 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2843 $exemptStates[$name] = 'ready';
2844 // Special case in buildExemptModules()
2847 $group = $module->getGroup();
2848 if ( isset( $exemptGroups[$group] ) ) {
2849 $exemptStates[$name] = 'ready';
2850 if ( !$module->isKnownEmpty( $context ) ) {
2851 // E.g. Don't output empty <styles>
2852 $exemptGroups[$group][] = $name;
2860 $this->rlExemptStyleModules
= $exemptGroups;
2862 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2863 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2864 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2865 if ( !$isUserModuleFiltered ) {
2866 // Manually handled by getBottomScripts()
2867 $userModule = $rl->getModule( 'user' );
2868 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2871 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2874 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2875 $rlClient->setConfig( $this->getJSVars() );
2876 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2877 $rlClient->setModuleStyles( $moduleStyles );
2878 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2879 $rlClient->setExemptStates( $exemptStates );
2880 $this->rlClient
= $rlClient;
2882 return $this->rlClient
;
2886 * @param Skin $sk The given Skin
2887 * @param bool $includeStyle Unused
2888 * @return string The doctype, opening "<html>", and head element.
2890 public function headElement( Skin
$sk, $includeStyle = true ) {
2893 $userdir = $this->getLanguage()->getDir();
2894 $sitedir = $wgContLang->getDir();
2897 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2898 $this->getRlClient()->getDocumentAttributes(),
2899 $sk->getHtmlElementAttributes()
2901 $pieces[] = Html
::openElement( 'head' );
2903 if ( $this->getHTMLTitle() == '' ) {
2904 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2907 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2908 // Add <meta charset="UTF-8">
2909 // This should be before <title> since it defines the charset used by
2910 // text including the text inside <title>.
2911 // The spec recommends defining XHTML5's charset using the XML declaration
2913 // Our XML declaration is output by Html::htmlHeader.
2914 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2915 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2916 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2919 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2920 $pieces[] = $this->getRlClient()->getHeadHtml();
2921 $pieces[] = $this->buildExemptModules();
2922 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2923 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2924 $pieces[] = Html
::closeElement( 'head' );
2927 $bodyClasses[] = 'mediawiki';
2929 # Classes for LTR/RTL directionality support
2930 $bodyClasses[] = $userdir;
2931 $bodyClasses[] = "sitedir-$sitedir";
2933 $underline = $this->getUser()->getOption( 'underline' );
2934 if ( $underline < 2 ) {
2935 // The following classes can be used here:
2936 // * mw-underline-always
2937 // * mw-underline-never
2938 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2941 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2942 # A <body> class is probably not the best way to do this . . .
2943 $bodyClasses[] = 'capitalize-all-nouns';
2946 // Parser feature migration class
2947 // The idea is that this will eventually be removed, after the wikitext
2948 // which requires it is cleaned up.
2949 $bodyClasses[] = 'mw-hide-empty-elt';
2951 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2952 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2954 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2957 // While the implode() is not strictly needed, it's used for backwards compatibility
2958 // (this used to be built as a string and hooks likely still expect that).
2959 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2961 // Allow skins and extensions to add body attributes they need
2962 $sk->addToBodyAttributes( $this, $bodyAttrs );
2963 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2965 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2967 return self
::combineWrappedStrings( $pieces );
2971 * Get a ResourceLoader object associated with this OutputPage
2973 * @return ResourceLoader
2975 public function getResourceLoader() {
2976 if ( is_null( $this->mResourceLoader
) ) {
2977 $this->mResourceLoader
= new ResourceLoader(
2979 LoggerFactory
::getInstance( 'resourceloader' )
2982 return $this->mResourceLoader
;
2986 * Explicily load or embed modules on a page.
2988 * @param array|string $modules One or more module names
2989 * @param string $only ResourceLoaderModule TYPE_ class constant
2990 * @param array $extraQuery [optional] Array with extra query parameters for the request
2991 * @return string|WrappedStringList HTML
2993 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2994 // Apply 'target' and 'origin' filters
2995 $modules = $this->filterModules( (array)$modules, null, $only );
2997 return ResourceLoaderClientHtml
::makeLoad(
2998 $this->getRlClientContext(),
3006 * Combine WrappedString chunks and filter out empty ones
3008 * @param array $chunks
3009 * @return string|WrappedStringList HTML
3011 protected static function combineWrappedStrings( array $chunks ) {
3012 // Filter out empty values
3013 $chunks = array_filter( $chunks, 'strlen' );
3014 return WrappedString
::join( "\n", $chunks );
3017 private function isUserJsPreview() {
3018 return $this->getConfig()->get( 'AllowUserJs' )
3019 && $this->getTitle()
3020 && $this->getTitle()->isJsSubpage()
3021 && $this->userCanPreview();
3024 private function isUserCssPreview() {
3025 return $this->getConfig()->get( 'AllowUserCss' )
3026 && $this->getTitle()
3027 && $this->getTitle()->isCssSubpage()
3028 && $this->userCanPreview();
3032 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
3033 * legacy scripts ($this->mScripts), and user JS.
3035 * @return string|WrappedStringList HTML
3037 public function getBottomScripts() {
3039 $chunks[] = $this->getRlClient()->getBodyHtml();
3041 // Legacy non-ResourceLoader scripts
3042 $chunks[] = $this->mScripts
;
3044 // Exempt 'user' module
3045 // - May need excludepages for live preview. (T28283)
3046 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3047 // ensures execution is scheduled after the "site" module.
3048 // - Don't load if module state is already resolved as "ready".
3049 if ( $this->rlUserModuleState
=== 'loading' ) {
3050 if ( $this->isUserJsPreview() ) {
3051 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3052 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3054 $chunks[] = ResourceLoader
::makeInlineScript(
3055 Xml
::encodeJsCall( 'mw.loader.using', [
3059 . Xml
::encodeJsCall( '$.globalEval', [
3060 $this->getRequest()->getText( 'wpTextbox1' )
3066 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3067 // asynchronously and may arrive *after* the inline script here. So the previewed code
3068 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3069 // Similarly, when previewing ./common.js and the user module does arrive first,
3070 // it will arrive without common.js and the inline script runs after.
3071 // Thus running common after the excluded subpage.
3074 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3078 if ( $this->limitReportJSData
) {
3079 $chunks[] = ResourceLoader
::makeInlineScript(
3080 ResourceLoader
::makeConfigSetScript(
3081 [ 'wgPageParseReport' => $this->limitReportJSData
]
3086 return self
::combineWrappedStrings( $chunks );
3090 * Get the javascript config vars to include on this page
3092 * @return array Array of javascript config vars
3095 public function getJsConfigVars() {
3096 return $this->mJsConfigVars
;
3100 * Add one or more variables to be set in mw.config in JavaScript
3102 * @param string|array $keys Key or array of key/value pairs
3103 * @param mixed $value [optional] Value of the configuration variable
3105 public function addJsConfigVars( $keys, $value = null ) {
3106 if ( is_array( $keys ) ) {
3107 foreach ( $keys as $key => $value ) {
3108 $this->mJsConfigVars
[$key] = $value;
3113 $this->mJsConfigVars
[$keys] = $value;
3117 * Get an array containing the variables to be set in mw.config in JavaScript.
3119 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3120 * - in other words, page-independent/site-wide variables (without state).
3121 * You will only be adding bloat to the html page and causing page caches to
3122 * have to be purged on configuration changes.
3125 public function getJSVars() {
3130 $canonicalSpecialPageName = false; # T23115
3132 $title = $this->getTitle();
3133 $ns = $title->getNamespace();
3134 $canonicalNamespace = MWNamespace
::exists( $ns )
3135 ? MWNamespace
::getCanonicalName( $ns )
3136 : $title->getNsText();
3138 $sk = $this->getSkin();
3139 // Get the relevant title so that AJAX features can use the correct page name
3140 // when making API requests from certain special pages (T36972).
3141 $relevantTitle = $sk->getRelevantTitle();
3142 $relevantUser = $sk->getRelevantUser();
3144 if ( $ns == NS_SPECIAL
) {
3145 list( $canonicalSpecialPageName, /*...*/ ) =
3146 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3147 } elseif ( $this->canUseWikiPage() ) {
3148 $wikiPage = $this->getWikiPage();
3149 $curRevisionId = $wikiPage->getLatest();
3150 $articleId = $wikiPage->getId();
3153 $lang = $title->getPageViewLanguage();
3155 // Pre-process information
3156 $separatorTransTable = $lang->separatorTransformTable();
3157 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3158 $compactSeparatorTransTable = [
3159 implode( "\t", array_keys( $separatorTransTable ) ),
3160 implode( "\t", $separatorTransTable ),
3162 $digitTransTable = $lang->digitTransformTable();
3163 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3164 $compactDigitTransTable = [
3165 implode( "\t", array_keys( $digitTransTable ) ),
3166 implode( "\t", $digitTransTable ),
3169 $user = $this->getUser();
3172 'wgCanonicalNamespace' => $canonicalNamespace,
3173 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3174 'wgNamespaceNumber' => $title->getNamespace(),
3175 'wgPageName' => $title->getPrefixedDBkey(),
3176 'wgTitle' => $title->getText(),
3177 'wgCurRevisionId' => $curRevisionId,
3178 'wgRevisionId' => (int)$this->getRevisionId(),
3179 'wgArticleId' => $articleId,
3180 'wgIsArticle' => $this->isArticle(),
3181 'wgIsRedirect' => $title->isRedirect(),
3182 'wgAction' => Action
::getActionName( $this->getContext() ),
3183 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3184 'wgUserGroups' => $user->getEffectiveGroups(),
3185 'wgCategories' => $this->getCategories(),
3186 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3187 'wgPageContentLanguage' => $lang->getCode(),
3188 'wgPageContentModel' => $title->getContentModel(),
3189 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3190 'wgDigitTransformTable' => $compactDigitTransTable,
3191 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3192 'wgMonthNames' => $lang->getMonthNamesArray(),
3193 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3194 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3195 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3196 'wgRequestId' => WebRequest
::getRequestId(),
3199 if ( $user->isLoggedIn() ) {
3200 $vars['wgUserId'] = $user->getId();
3201 $vars['wgUserEditCount'] = $user->getEditCount();
3202 $userReg = $user->getRegistration();
3203 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3204 // Get the revision ID of the oldest new message on the user's talk
3205 // page. This can be used for constructing new message alerts on
3207 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3210 if ( $wgContLang->hasVariants() ) {
3211 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3213 // Same test as SkinTemplate
3214 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3215 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3217 foreach ( $title->getRestrictionTypes() as $type ) {
3218 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3221 if ( $title->isMainPage() ) {
3222 $vars['wgIsMainPage'] = true;
3225 if ( $this->mRedirectedFrom
) {
3226 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3229 if ( $relevantUser ) {
3230 $vars['wgRelevantUserName'] = $relevantUser->getName();
3233 // Allow extensions to add their custom variables to the mw.config map.
3234 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3235 // page-dependant but site-wide (without state).
3236 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3237 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3239 // Merge in variables from addJsConfigVars last
3240 return array_merge( $vars, $this->getJsConfigVars() );
3244 * To make it harder for someone to slip a user a fake
3245 * user-JavaScript or user-CSS preview, a random token
3246 * is associated with the login session. If it's not
3247 * passed back with the preview request, we won't render
3252 public function userCanPreview() {
3253 $request = $this->getRequest();
3255 $request->getVal( 'action' ) !== 'submit' ||
3256 !$request->getCheck( 'wpPreview' ) ||
3257 !$request->wasPosted()
3262 $user = $this->getUser();
3264 if ( !$user->isLoggedIn() ) {
3265 // Anons have predictable edit tokens
3268 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3272 $title = $this->getTitle();
3273 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3276 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3277 // Don't execute another user's CSS or JS on preview (T85855)
3281 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3282 if ( count( $errors ) !== 0 ) {
3290 * @return array Array in format "link name or number => 'link html'".
3292 public function getHeadLinksArray() {
3296 $config = $this->getConfig();
3298 $canonicalUrl = $this->mCanonicalUrl
;
3300 $tags['meta-generator'] = Html
::element( 'meta', [
3301 'name' => 'generator',
3302 'content' => "MediaWiki $wgVersion",
3305 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3306 $tags['meta-referrer'] = Html
::element( 'meta', [
3307 'name' => 'referrer',
3308 'content' => $config->get( 'ReferrerPolicy' )
3312 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3313 if ( $p !== 'index,follow' ) {
3314 // http://www.robotstxt.org/wc/meta-user.html
3315 // Only show if it's different from the default robots policy
3316 $tags['meta-robots'] = Html
::element( 'meta', [
3322 foreach ( $this->mMetatags
as $tag ) {
3323 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3325 $tag[0] = substr( $tag[0], 5 );
3326 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3331 $tagName = "meta-{$tag[0]}";
3332 if ( isset( $tags[$tagName] ) ) {
3333 $tagName .= $tag[1];
3335 $tags[$tagName] = Html
::element( 'meta',
3338 'content' => $tag[1]
3343 foreach ( $this->mLinktags
as $tag ) {
3344 $tags[] = Html
::element( 'link', $tag );
3347 # Universal edit button
3348 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3349 $user = $this->getUser();
3350 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3351 && ( $this->getTitle()->exists() ||
3352 $this->getTitle()->quickUserCan( 'create', $user ) )
3354 // Original UniversalEditButton
3355 $msg = $this->msg( 'edit' )->text();
3356 $tags['universal-edit-button'] = Html
::element( 'link', [
3357 'rel' => 'alternate',
3358 'type' => 'application/x-wiki',
3360 'href' => $this->getTitle()->getEditURL(),
3362 // Alternate edit link
3363 $tags['alternative-edit'] = Html
::element( 'link', [
3366 'href' => $this->getTitle()->getEditURL(),
3371 # Generally the order of the favicon and apple-touch-icon links
3372 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3373 # uses whichever one appears later in the HTML source. Make sure
3374 # apple-touch-icon is specified first to avoid this.
3375 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3376 $tags['apple-touch-icon'] = Html
::element( 'link', [
3377 'rel' => 'apple-touch-icon',
3378 'href' => $config->get( 'AppleTouchIcon' )
3382 if ( $config->get( 'Favicon' ) !== false ) {
3383 $tags['favicon'] = Html
::element( 'link', [
3384 'rel' => 'shortcut icon',
3385 'href' => $config->get( 'Favicon' )
3389 # OpenSearch description link
3390 $tags['opensearch'] = Html
::element( 'link', [
3392 'type' => 'application/opensearchdescription+xml',
3393 'href' => wfScript( 'opensearch_desc' ),
3394 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3397 if ( $config->get( 'EnableAPI' ) ) {
3398 # Real Simple Discovery link, provides auto-discovery information
3399 # for the MediaWiki API (and potentially additional custom API
3400 # support such as WordPress or Twitter-compatible APIs for a
3401 # blogging extension, etc)
3402 $tags['rsd'] = Html
::element( 'link', [
3404 'type' => 'application/rsd+xml',
3405 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3406 // Whether RSD accepts relative or protocol-relative URLs is completely
3407 // undocumented, though.
3408 'href' => wfExpandUrl( wfAppendQuery(
3410 [ 'action' => 'rsd' ] ),
3417 if ( !$config->get( 'DisableLangConversion' ) ) {
3418 $lang = $this->getTitle()->getPageLanguage();
3419 if ( $lang->hasVariants() ) {
3420 $variants = $lang->getVariants();
3421 foreach ( $variants as $variant ) {
3422 $tags["variant-$variant"] = Html
::element( 'link', [
3423 'rel' => 'alternate',
3424 'hreflang' => wfBCP47( $variant ),
3425 'href' => $this->getTitle()->getLocalURL(
3426 [ 'variant' => $variant ] )
3430 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3431 $tags["variant-x-default"] = Html
::element( 'link', [
3432 'rel' => 'alternate',
3433 'hreflang' => 'x-default',
3434 'href' => $this->getTitle()->getLocalURL() ] );
3439 if ( $this->copyrightUrl
!== null ) {
3440 $copyright = $this->copyrightUrl
;
3443 if ( $config->get( 'RightsPage' ) ) {
3444 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3447 $copyright = $copy->getLocalURL();
3451 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3452 $copyright = $config->get( 'RightsUrl' );
3457 $tags['copyright'] = Html
::element( 'link', [
3458 'rel' => 'copyright',
3459 'href' => $copyright ]
3464 if ( $config->get( 'Feed' ) ) {
3467 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3468 # Use the page name for the title. In principle, this could
3469 # lead to issues with having the same name for different feeds
3470 # corresponding to the same page, but we can't avoid that at
3473 $feedLinks[] = $this->feedLink(
3476 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3478 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3483 # Recent changes feed should appear on every page (except recentchanges,
3484 # that would be redundant). Put it after the per-page feed to avoid
3485 # changing existing behavior. It's still available, probably via a
3486 # menu in your browser. Some sites might have a different feed they'd
3487 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3488 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3489 # If so, use it instead.
3490 $sitename = $config->get( 'Sitename' );
3491 if ( $config->get( 'OverrideSiteFeed' ) ) {
3492 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3493 // Note, this->feedLink escapes the url.
3494 $feedLinks[] = $this->feedLink(
3497 $this->msg( "site-{$type}-feed", $sitename )->text()
3500 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3501 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3502 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3503 $feedLinks[] = $this->feedLink(
3505 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3506 # For grep: 'site-rss-feed', 'site-atom-feed'
3507 $this->msg( "site-{$format}-feed", $sitename )->text()
3512 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3513 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3514 # use OutputPage::addFeedLink() instead.
3515 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3517 $tags +
= $feedLinks;
3521 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3522 if ( $canonicalUrl !== false ) {
3523 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3525 if ( $this->isArticleRelated() ) {
3526 // This affects all requests where "setArticleRelated" is true. This is
3527 // typically all requests that show content (query title, curid, oldid, diff),
3528 // and all wikipage actions (edit, delete, purge, info, history etc.).
3529 // It does not apply to File pages and Special pages.
3530 // 'history' and 'info' actions address page metadata rather than the page
3531 // content itself, so they may not be canonicalized to the view page url.
3532 // TODO: this ought to be better encapsulated in the Action class.
3533 $action = Action
::getActionName( $this->getContext() );
3534 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3535 $query = "action={$action}";
3539 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3541 $reqUrl = $this->getRequest()->getRequestURL();
3542 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3546 if ( $canonicalUrl !== false ) {
3547 $tags[] = Html
::element( 'link', [
3548 'rel' => 'canonical',
3549 'href' => $canonicalUrl
3557 * @return string HTML tag links to be put in the header.
3558 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3559 * OutputPage::getHeadLinksArray directly.
3561 public function getHeadLinks() {
3562 wfDeprecated( __METHOD__
, '1.24' );
3563 return implode( "\n", $this->getHeadLinksArray() );
3567 * Generate a "<link rel/>" for a feed.
3569 * @param string $type Feed type
3570 * @param string $url URL to the feed
3571 * @param string $text Value of the "title" attribute
3572 * @return string HTML fragment
3574 private function feedLink( $type, $url, $text ) {
3575 return Html
::element( 'link', [
3576 'rel' => 'alternate',
3577 'type' => "application/$type+xml",
3584 * Add a local or specified stylesheet, with the given media options.
3585 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3587 * @param string $style URL to the file
3588 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3589 * @param string $condition For IE conditional comments, specifying an IE version
3590 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3592 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3595 $options['media'] = $media;
3598 $options['condition'] = $condition;
3601 $options['dir'] = $dir;
3603 $this->styles
[$style] = $options;
3607 * Adds inline CSS styles
3608 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3610 * @param mixed $style_css Inline CSS
3611 * @param string $flip Set to 'flip' to flip the CSS if needed
3613 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3614 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3615 # If wanted, and the interface is right-to-left, flip the CSS
3616 $style_css = CSSJanus
::transform( $style_css, true, false );
3618 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3622 * Build exempt modules and legacy non-ResourceLoader styles.
3624 * @return string|WrappedStringList HTML
3626 protected function buildExemptModules() {
3630 // Things that go after the ResourceLoaderDynamicStyles marker
3633 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3634 if ( $this->isUserCssPreview() ) {
3635 $append[] = $this->makeResourceLoaderLink(
3637 ResourceLoaderModule
::TYPE_STYLES
,
3638 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3641 // Load the previewed CSS. Janus it if needed.
3642 // User-supplied CSS is assumed to in the wiki's content language.
3643 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3644 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3645 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3647 $append[] = Html
::inlineStyle( $previewedCSS );
3650 // We want site, private and user styles to override dynamically added styles from
3651 // general modules, but we want dynamically added styles to override statically added
3652 // style modules. So the order has to be:
3653 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3654 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3655 // - ResourceLoaderDynamicStyles marker
3656 // - site/private/user styles
3658 // Add legacy styles added through addStyle()/addInlineStyle() here
3659 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3661 $chunks[] = Html
::element(
3663 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3666 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3667 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3668 ResourceLoaderModule
::TYPE_STYLES
3672 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3678 public function buildCssLinksArray() {
3681 // Add any extension CSS
3682 foreach ( $this->mExtStyles
as $url ) {
3683 $this->addStyle( $url );
3685 $this->mExtStyles
= [];
3687 foreach ( $this->styles
as $file => $options ) {
3688 $link = $this->styleLink( $file, $options );
3690 $links[$file] = $link;
3697 * Generate \<link\> tags for stylesheets
3699 * @param string $style URL to the file
3700 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3701 * @return string HTML fragment
3703 protected function styleLink( $style, array $options ) {
3704 if ( isset( $options['dir'] ) ) {
3705 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3710 if ( isset( $options['media'] ) ) {
3711 $media = self
::transformCssMedia( $options['media'] );
3712 if ( is_null( $media ) ) {
3719 if ( substr( $style, 0, 1 ) == '/' ||
3720 substr( $style, 0, 5 ) == 'http:' ||
3721 substr( $style, 0, 6 ) == 'https:' ) {
3724 $config = $this->getConfig();
3725 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3726 $config->get( 'StyleVersion' );
3729 $link = Html
::linkedStyle( $url, $media );
3731 if ( isset( $options['condition'] ) ) {
3732 $condition = htmlspecialchars( $options['condition'] );
3733 $link = "<!--[if $condition]>$link<![endif]-->";
3739 * Transform path to web-accessible static resource.
3741 * This is used to add a validation hash as query string.
3742 * This aids various behaviors:
3744 * - Put long Cache-Control max-age headers on responses for improved
3745 * cache performance.
3746 * - Get the correct version of a file as expected by the current page.
3747 * - Instantly get the updated version of a file after deployment.
3749 * Avoid using this for urls included in HTML as otherwise clients may get different
3750 * versions of a resource when navigating the site depending on when the page was cached.
3751 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3752 * an external stylesheet).
3755 * @param Config $config
3756 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3757 * @return string URL
3759 public static function transformResourcePath( Config
$config, $path ) {
3763 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3764 if ( $remotePathPrefix === '' ) {
3765 // The configured base path is required to be empty string for
3766 // wikis in the domain root
3769 $remotePath = $remotePathPrefix;
3771 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3772 // - Path is outside wgResourceBasePath, ignore.
3773 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3776 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3777 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3778 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3779 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3780 $uploadPath = $config->get( 'UploadPath' );
3781 if ( strpos( $path, $uploadPath ) === 0 ) {
3782 $localDir = $config->get( 'UploadDirectory' );
3783 $remotePathPrefix = $remotePath = $uploadPath;
3786 $path = RelPath\
getRelativePath( $path, $remotePath );
3787 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3791 * Utility method for transformResourceFilePath().
3793 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3796 * @param string $remotePath URL path prefix that points to $localPath
3797 * @param string $localPath File directory exposed at $remotePath
3798 * @param string $file Path to target file relative to $localPath
3799 * @return string URL
3801 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3802 $hash = md5_file( "$localPath/$file" );
3803 if ( $hash === false ) {
3804 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3807 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3811 * Transform "media" attribute based on request parameters
3813 * @param string $media Current value of the "media" attribute
3814 * @return string Modified value of the "media" attribute, or null to skip
3817 public static function transformCssMedia( $media ) {
3820 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3821 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3823 // Switch in on-screen display for media testing
3825 'printable' => 'print',
3826 'handheld' => 'handheld',
3828 foreach ( $switches as $switch => $targetMedia ) {
3829 if ( $wgRequest->getBool( $switch ) ) {
3830 if ( $media == $targetMedia ) {
3832 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3833 /* This regex will not attempt to understand a comma-separated media_query_list
3835 * Example supported values for $media:
3836 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3837 * Example NOT supported value for $media:
3838 * '3d-glasses, screen, print and resolution > 90dpi'
3840 * If it's a print request, we never want any kind of screen stylesheets
3841 * If it's a handheld request (currently the only other choice with a switch),
3842 * we don't want simple 'screen' but we might want screen queries that
3843 * have a max-width or something, so we'll pass all others on and let the
3844 * client do the query.
3846 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3857 * Add a wikitext-formatted message to the output.
3858 * This is equivalent to:
3860 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3862 public function addWikiMsg( /*...*/ ) {
3863 $args = func_get_args();
3864 $name = array_shift( $args );
3865 $this->addWikiMsgArray( $name, $args );
3869 * Add a wikitext-formatted message to the output.
3870 * Like addWikiMsg() except the parameters are taken as an array
3871 * instead of a variable argument list.
3873 * @param string $name
3874 * @param array $args
3876 public function addWikiMsgArray( $name, $args ) {
3877 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3881 * This function takes a number of message/argument specifications, wraps them in
3882 * some overall structure, and then parses the result and adds it to the output.
3884 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3885 * and so on. The subsequent arguments may be either
3886 * 1) strings, in which case they are message names, or
3887 * 2) arrays, in which case, within each array, the first element is the message
3888 * name, and subsequent elements are the parameters to that message.
3890 * Don't use this for messages that are not in the user's interface language.
3894 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3898 * $wgOut->addWikiText( "<div class='error'>\n"
3899 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3901 * The newline after the opening div is needed in some wikitext. See T21226.
3903 * @param string $wrap
3905 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3906 $msgSpecs = func_get_args();
3907 array_shift( $msgSpecs );
3908 $msgSpecs = array_values( $msgSpecs );
3910 foreach ( $msgSpecs as $n => $spec ) {
3911 if ( is_array( $spec ) ) {
3913 $name = array_shift( $args );
3914 if ( isset( $args['options'] ) ) {
3915 unset( $args['options'] );
3917 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3925 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3927 $this->addWikiText( $s );
3931 * Enables/disables TOC, doesn't override __NOTOC__
3935 public function enableTOC( $flag = true ) {
3936 $this->mEnableTOC
= $flag;
3943 public function isTOCEnabled() {
3944 return $this->mEnableTOC
;
3948 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3952 public function enableSectionEditLinks( $flag = true ) {
3953 $this->mEnableSectionEditLinks
= $flag;
3960 public function sectionEditLinksEnabled() {
3961 return $this->mEnableSectionEditLinks
;
3965 * Helper function to setup the PHP implementation of OOUI to use in this request.
3968 * @param String $skinName The Skin name to determine the correct OOUI theme
3969 * @param String $dir Language direction
3971 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3972 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3973 // Make keys (skin names) lowercase for case-insensitive matching.
3974 $themes = array_change_key_case( $themes, CASE_LOWER
);
3975 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3976 // For example, 'OOUI\MediaWikiTheme'.
3977 $themeClass = "OOUI\\{$theme}Theme";
3978 OOUI\Theme
::setSingleton( new $themeClass() );
3979 OOUI\Element
::setDefaultDir( $dir );
3983 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3984 * MediaWiki and this OutputPage instance.
3988 public function enableOOUI() {
3990 strtolower( $this->getSkin()->getSkinName() ),
3991 $this->getLanguage()->getDir()
3993 $this->addModuleStyles( [
3994 'oojs-ui-core.styles',
3995 'oojs-ui.styles.icons',
3996 'oojs-ui.styles.indicators',
3997 'oojs-ui.styles.textures',
3998 'mediawiki.widgets.styles',
4003 * Add Link headers for preloading the wiki's logo.
4007 protected function addLogoPreloadLinkHeaders() {
4008 $logo = ResourceLoaderSkinModule
::getLogo( $this->getConfig() );
4014 if ( !is_array( $logo ) ) {
4015 // No media queries required if we only have one variant
4016 $this->addLinkHeader( '<' . $logo . '>;rel=preload;as=image' );
4020 foreach ( $logo as $dppx => $src ) {
4021 // Keys are in this format: "1.5x"
4022 $dppx = substr( $dppx, 0, -1 );
4023 $logosPerDppx[$dppx] = $src;
4026 // Because PHP can't have floats as array keys
4027 uksort( $logosPerDppx, function ( $a , $b ) {
4028 $a = floatval( $a );
4029 $b = floatval( $b );
4034 // Sort from smallest to largest (e.g. 1x, 1.5x, 2x)
4035 return ( $a < $b ) ?
-1 : 1;
4038 foreach ( $logosPerDppx as $dppx => $src ) {
4039 $logos[] = [ 'dppx' => $dppx, 'src' => $src ];
4042 $logosCount = count( $logos );
4043 // Logic must match ResourceLoaderSkinModule:
4044 // - 1x applies to resolution < 1.5dppx
4045 // - 1.5x applies to resolution >= 1.5dppx && < 2dppx
4046 // - 2x applies to resolution >= 2dppx
4047 // Note that min-resolution and max-resolution are both inclusive.
4048 for ( $i = 0; $i < $logosCount; $i++
) {
4051 // min-resolution is ">=" (larger than or equal to)
4052 // "not min-resolution" is essentially "<"
4053 $media_query = 'not all and (min-resolution: ' . $logos[ 1 ]['dppx'] . 'dppx)';
4054 } elseif ( $i !== $logosCount - 1 ) {
4056 // Media query expressions can only apply "not" to the entire expression
4057 // (e.g. can't express ">= 1.5 and not >= 2).
4058 // Workaround: Use <= 1.9999 in place of < 2.
4059 $upper_bound = floatval( $logos[ $i +
1 ]['dppx'] ) - 0.000001;
4060 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] .
4061 'dppx) and (max-resolution: ' . $upper_bound . 'dppx)';
4064 $media_query = '(min-resolution: ' . $logos[ $i ]['dppx'] . 'dppx)';
4067 $this->addLinkHeader(
4068 '<' . $logos[$i]['src'] . '>;rel=preload;as=image;media=' . $media_query