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;
303 * Constructor for OutputPage. This should not be called directly.
304 * Instead a new RequestContext should be created and it will implicitly create
305 * a OutputPage tied to that context.
306 * @param IContextSource|null $context
308 function __construct( IContextSource
$context = null ) {
309 if ( $context === null ) {
310 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
311 wfDeprecated( __METHOD__
, '1.18' );
313 $this->setContext( $context );
318 * Redirect to $url rather than displaying the normal page
320 * @param string $url URL
321 * @param string $responsecode HTTP status code
323 public function redirect( $url, $responsecode = '302' ) {
324 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
325 $this->mRedirect
= str_replace( "\n", '', $url );
326 $this->mRedirectCode
= $responsecode;
330 * Get the URL to redirect to, or an empty string if not redirect URL set
334 public function getRedirect() {
335 return $this->mRedirect
;
339 * Set the copyright URL to send with the output.
340 * Empty string to omit, null to reset.
344 * @param string|null $url
346 public function setCopyrightUrl( $url ) {
347 $this->copyrightUrl
= $url;
351 * Set the HTTP status code to send with the output.
353 * @param int $statusCode
355 public function setStatusCode( $statusCode ) {
356 $this->mStatusCode
= $statusCode;
360 * Add a new "<meta>" tag
361 * To add an http-equiv meta tag, precede the name with "http:"
363 * @param string $name Tag name
364 * @param string $val Tag value
366 function addMeta( $name, $val ) {
367 array_push( $this->mMetatags
, [ $name, $val ] );
371 * Returns the current <meta> tags
376 public function getMetaTags() {
377 return $this->mMetatags
;
381 * Add a new \<link\> tag to the page header.
383 * Note: use setCanonicalUrl() for rel=canonical.
385 * @param array $linkarr Associative array of attributes.
387 function addLink( array $linkarr ) {
388 array_push( $this->mLinktags
, $linkarr );
392 * Returns the current <link> tags
397 public function getLinkTags() {
398 return $this->mLinktags
;
402 * Add a new \<link\> with "rel" attribute set to "meta"
404 * @param array $linkarr Associative array mapping attribute names to their
405 * values, both keys and values will be escaped, and the
406 * "rel" attribute will be automatically added
408 function addMetadataLink( array $linkarr ) {
409 $linkarr['rel'] = $this->getMetadataAttribute();
410 $this->addLink( $linkarr );
414 * Set the URL to be used for the <link rel=canonical>. This should be used
415 * in preference to addLink(), to avoid duplicate link tags.
418 function setCanonicalUrl( $url ) {
419 $this->mCanonicalUrl
= $url;
423 * Returns the URL to be used for the <link rel=canonical> if
427 * @return bool|string
429 public function getCanonicalUrl() {
430 return $this->mCanonicalUrl
;
434 * Get the value of the "rel" attribute for metadata links
438 public function getMetadataAttribute() {
439 # note: buggy CC software only reads first "meta" link
440 static $haveMeta = false;
442 return 'alternate meta';
450 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
451 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
454 * @param string $script Raw HTML
456 function addScript( $script ) {
457 $this->mScripts
.= $script;
461 * Register and add a stylesheet from an extension directory.
463 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
464 * @param string $url Path to sheet. Provide either a full url (beginning
465 * with 'http', etc) or a relative path from the document root
466 * (beginning with '/'). Otherwise it behaves identically to
467 * addStyle() and draws from the /skins folder.
469 public function addExtensionStyle( $url ) {
470 wfDeprecated( __METHOD__
, '1.27' );
471 array_push( $this->mExtStyles
, $url );
475 * Get all styles added by extensions
477 * @deprecated since 1.27
480 function getExtStyle() {
481 wfDeprecated( __METHOD__
, '1.27' );
482 return $this->mExtStyles
;
486 * Add a JavaScript file out of skins/common, or a given relative path.
487 * Internal use only. Use OutputPage::addModules() if possible.
489 * @param string $file Filename in skins/common or complete on-server path
491 * @param string $version Style version of the file. Defaults to $wgStyleVersion
493 public function addScriptFile( $file, $version = null ) {
494 // See if $file parameter is an absolute URL or begins with a slash
495 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
498 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
500 if ( is_null( $version ) ) {
501 $version = $this->getConfig()->get( 'StyleVersion' );
503 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
507 * Add a self-contained script tag with the given contents
508 * Internal use only. Use OutputPage::addModules() if possible.
510 * @param string $script JavaScript text, no script tags
512 public function addInlineScript( $script ) {
513 $this->mScripts
.= Html
::inlineScript( $script );
517 * Filter an array of modules to remove insufficiently trustworthy members, and modules
518 * which are no longer registered (eg a page is cached before an extension is disabled)
519 * @param array $modules
520 * @param string|null $position If not null, only return modules with this position
521 * @param string $type
524 protected function filterModules( array $modules, $position = null,
525 $type = ResourceLoaderModule
::TYPE_COMBINED
527 $resourceLoader = $this->getResourceLoader();
528 $filteredModules = [];
529 foreach ( $modules as $val ) {
530 $module = $resourceLoader->getModule( $val );
531 if ( $module instanceof ResourceLoaderModule
532 && $module->getOrigin() <= $this->getAllowedModules( $type )
533 && ( is_null( $position ) ||
$module->getPosition() == $position )
534 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
536 $filteredModules[] = $val;
539 return $filteredModules;
543 * Get the list of modules to include on this page
545 * @param bool $filter Whether to filter out insufficiently trustworthy modules
546 * @param string|null $position If not null, only return modules with this position
547 * @param string $param
548 * @return array Array of module names
550 public function getModules( $filter = false, $position = null, $param = 'mModules',
551 $type = ResourceLoaderModule
::TYPE_COMBINED
553 $modules = array_values( array_unique( $this->$param ) );
555 ?
$this->filterModules( $modules, $position, $type )
560 * Add one or more modules recognized by ResourceLoader. Modules added
561 * through this function will be loaded by ResourceLoader when the
564 * @param string|array $modules Module name (string) or array of module names
566 public function addModules( $modules ) {
567 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
571 * Get the list of module JS to include on this page
573 * @param bool $filter
574 * @param string|null $position
575 * @return array Array of module names
577 public function getModuleScripts( $filter = false, $position = null ) {
578 return $this->getModules( $filter, $position, 'mModuleScripts',
579 ResourceLoaderModule
::TYPE_SCRIPTS
584 * Add only JS of one or more modules recognized by ResourceLoader. Module
585 * scripts added through this function will be loaded by ResourceLoader when
588 * @param string|array $modules Module name (string) or array of module names
590 public function addModuleScripts( $modules ) {
591 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
595 * Get the list of module CSS to include on this page
597 * @param bool $filter
598 * @param string|null $position
599 * @return array Array of module names
601 public function getModuleStyles( $filter = false, $position = null ) {
602 return $this->getModules( $filter, $position, 'mModuleStyles',
603 ResourceLoaderModule
::TYPE_STYLES
608 * Add only CSS of one or more modules recognized by ResourceLoader.
610 * Module styles added through this function will be added using standard link CSS
611 * tags, rather than as a combined Javascript and CSS package. Thus, they will
612 * load when JavaScript is disabled (unless CSS also happens to be disabled).
614 * @param string|array $modules Module name (string) or array of module names
616 public function addModuleStyles( $modules ) {
617 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
621 * @return null|string ResourceLoader target
623 public function getTarget() {
624 return $this->mTarget
;
628 * Sets ResourceLoader target for load.php links. If null, will be omitted
630 * @param string|null $target
632 public function setTarget( $target ) {
633 $this->mTarget
= $target;
637 * Get an array of head items
641 function getHeadItemsArray() {
642 return $this->mHeadItems
;
646 * Add or replace a head item to the output
648 * Whenever possible, use more specific options like ResourceLoader modules,
649 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
650 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
651 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
652 * This would be your very LAST fallback.
654 * @param string $name Item name
655 * @param string $value Raw HTML
657 public function addHeadItem( $name, $value ) {
658 $this->mHeadItems
[$name] = $value;
662 * Add one or more head items to the output
665 * @param string|string[] $value Raw HTML
667 public function addHeadItems( $values ) {
668 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
672 * Check if the header item $name is already set
674 * @param string $name Item name
677 public function hasHeadItem( $name ) {
678 return isset( $this->mHeadItems
[$name] );
682 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
685 public function setETag( $tag ) {
689 * Set whether the output should only contain the body of the article,
690 * without any skin, sidebar, etc.
691 * Used e.g. when calling with "action=render".
693 * @param bool $only Whether to output only the body of the article
695 public function setArticleBodyOnly( $only ) {
696 $this->mArticleBodyOnly
= $only;
700 * Return whether the output will contain only the body of the article
704 public function getArticleBodyOnly() {
705 return $this->mArticleBodyOnly
;
709 * Set an additional output property
712 * @param string $name
713 * @param mixed $value
715 public function setProperty( $name, $value ) {
716 $this->mProperties
[$name] = $value;
720 * Get an additional output property
723 * @param string $name
724 * @return mixed Property value or null if not found
726 public function getProperty( $name ) {
727 if ( isset( $this->mProperties
[$name] ) ) {
728 return $this->mProperties
[$name];
735 * checkLastModified tells the client to use the client-cached page if
736 * possible. If successful, the OutputPage is disabled so that
737 * any future call to OutputPage->output() have no effect.
739 * Side effect: sets mLastModified for Last-Modified header
741 * @param string $timestamp
743 * @return bool True if cache-ok headers was sent.
745 public function checkLastModified( $timestamp ) {
746 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
747 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
750 $config = $this->getConfig();
751 if ( !$config->get( 'CachePages' ) ) {
752 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
756 $timestamp = wfTimestamp( TS_MW
, $timestamp );
758 'page' => $timestamp,
759 'user' => $this->getUser()->getTouched(),
760 'epoch' => $config->get( 'CacheEpoch' )
762 if ( $config->get( 'UseSquid' ) ) {
763 // bug 44570: the core page itself may not change, but resources might
764 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
766 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
768 $maxModified = max( $modifiedTimes );
769 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
771 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
772 if ( $clientHeader === false ) {
773 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
777 # IE sends sizes after the date like this:
778 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
779 # this breaks strtotime().
780 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
782 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
783 $clientHeaderTime = strtotime( $clientHeader );
784 MediaWiki\restoreWarnings
();
785 if ( !$clientHeaderTime ) {
787 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
790 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
794 foreach ( $modifiedTimes as $name => $value ) {
795 if ( $info !== '' ) {
798 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
801 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
802 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
803 wfDebug( __METHOD__
. ": effective Last-Modified: " .
804 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
805 if ( $clientHeaderTime < $maxModified ) {
806 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
811 # Give a 304 Not Modified response code and disable body output
812 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
813 ini_set( 'zlib.output_compression', 0 );
814 $this->getRequest()->response()->statusHeader( 304 );
815 $this->sendCacheControl();
818 // Don't output a compressed blob when using ob_gzhandler;
819 // it's technically against HTTP spec and seems to confuse
820 // Firefox when the response gets split over two packets.
821 wfClearOutputBuffers();
827 * Override the last modified timestamp
829 * @param string $timestamp New timestamp, in a format readable by
832 public function setLastModified( $timestamp ) {
833 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
837 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
839 * @param string $policy The literal string to output as the contents of
840 * the meta tag. Will be parsed according to the spec and output in
844 public function setRobotPolicy( $policy ) {
845 $policy = Article
::formatRobotPolicy( $policy );
847 if ( isset( $policy['index'] ) ) {
848 $this->setIndexPolicy( $policy['index'] );
850 if ( isset( $policy['follow'] ) ) {
851 $this->setFollowPolicy( $policy['follow'] );
856 * Set the index policy for the page, but leave the follow policy un-
859 * @param string $policy Either 'index' or 'noindex'.
862 public function setIndexPolicy( $policy ) {
863 $policy = trim( $policy );
864 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
865 $this->mIndexPolicy
= $policy;
870 * Set the follow policy for the page, but leave the index policy un-
873 * @param string $policy Either 'follow' or 'nofollow'.
876 public function setFollowPolicy( $policy ) {
877 $policy = trim( $policy );
878 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
879 $this->mFollowPolicy
= $policy;
884 * Set the new value of the "action text", this will be added to the
885 * "HTML title", separated from it with " - ".
887 * @param string $text New value of the "action text"
889 public function setPageTitleActionText( $text ) {
890 $this->mPageTitleActionText
= $text;
894 * Get the value of the "action text"
898 public function getPageTitleActionText() {
899 return $this->mPageTitleActionText
;
903 * "HTML title" means the contents of "<title>".
904 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
906 * @param string|Message $name
908 public function setHTMLTitle( $name ) {
909 if ( $name instanceof Message
) {
910 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
912 $this->mHTMLtitle
= $name;
917 * Return the "HTML title", i.e. the content of the "<title>" tag.
921 public function getHTMLTitle() {
922 return $this->mHTMLtitle
;
926 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
930 public function setRedirectedFrom( $t ) {
931 $this->mRedirectedFrom
= $t;
935 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
936 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
937 * but not bad tags like \<script\>. This function automatically sets
938 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
939 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
940 * good tags like \<i\> will be dropped entirely.
942 * @param string|Message $name
944 public function setPageTitle( $name ) {
945 if ( $name instanceof Message
) {
946 $name = $name->setContext( $this->getContext() )->text();
949 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
950 # but leave "<i>foobar</i>" alone
951 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
952 $this->mPagetitle
= $nameWithTags;
954 # change "<i>foo&bar</i>" to "foo&bar"
956 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
957 ->inContentLanguage()
962 * Return the "page title", i.e. the content of the \<h1\> tag.
966 public function getPageTitle() {
967 return $this->mPagetitle
;
971 * Set the Title object to use
975 public function setTitle( Title
$t ) {
976 $this->getContext()->setTitle( $t );
980 * Replace the subtitle with $str
982 * @param string|Message $str New value of the subtitle. String should be safe HTML.
984 public function setSubtitle( $str ) {
985 $this->clearSubtitle();
986 $this->addSubtitle( $str );
990 * Add $str to the subtitle
992 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
994 public function addSubtitle( $str ) {
995 if ( $str instanceof Message
) {
996 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
998 $this->mSubtitle
[] = $str;
1003 * Build message object for a subtitle containing a backlink to a page
1005 * @param Title $title Title to link to
1006 * @param array $query Array of additional parameters to include in the link
1010 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1011 if ( $title->isRedirect() ) {
1012 $query['redirect'] = 'no';
1014 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1015 return wfMessage( 'backlinksubtitle' )
1016 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1020 * Add a subtitle containing a backlink to a page
1022 * @param Title $title Title to link to
1023 * @param array $query Array of additional parameters to include in the link
1025 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1026 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1030 * Clear the subtitles
1032 public function clearSubtitle() {
1033 $this->mSubtitle
= [];
1041 public function getSubtitle() {
1042 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1046 * Set the page as printable, i.e. it'll be displayed with all
1047 * print styles included
1049 public function setPrintable() {
1050 $this->mPrintable
= true;
1054 * Return whether the page is "printable"
1058 public function isPrintable() {
1059 return $this->mPrintable
;
1063 * Disable output completely, i.e. calling output() will have no effect
1065 public function disable() {
1066 $this->mDoNothing
= true;
1070 * Return whether the output will be completely disabled
1074 public function isDisabled() {
1075 return $this->mDoNothing
;
1079 * Show an "add new section" link?
1083 public function showNewSectionLink() {
1084 return $this->mNewSectionLink
;
1088 * Forcibly hide the new section link?
1092 public function forceHideNewSectionLink() {
1093 return $this->mHideNewSectionLink
;
1097 * Add or remove feed links in the page header
1098 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1099 * for the new version
1100 * @see addFeedLink()
1102 * @param bool $show True: add default feeds, false: remove all feeds
1104 public function setSyndicated( $show = true ) {
1106 $this->setFeedAppendQuery( false );
1108 $this->mFeedLinks
= [];
1113 * Add default feeds to the page header
1114 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1115 * for the new version
1116 * @see addFeedLink()
1118 * @param string $val Query to append to feed links or false to output
1121 public function setFeedAppendQuery( $val ) {
1122 $this->mFeedLinks
= [];
1124 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1125 $query = "feed=$type";
1126 if ( is_string( $val ) ) {
1127 $query .= '&' . $val;
1129 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1134 * Add a feed link to the page header
1136 * @param string $format Feed type, should be a key of $wgFeedClasses
1137 * @param string $href URL
1139 public function addFeedLink( $format, $href ) {
1140 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1141 $this->mFeedLinks
[$format] = $href;
1146 * Should we output feed links for this page?
1149 public function isSyndicated() {
1150 return count( $this->mFeedLinks
) > 0;
1154 * Return URLs for each supported syndication format for this page.
1155 * @return array Associating format keys with URLs
1157 public function getSyndicationLinks() {
1158 return $this->mFeedLinks
;
1162 * Will currently always return null
1166 public function getFeedAppendQuery() {
1167 return $this->mFeedLinksAppendQuery
;
1171 * Set whether the displayed content is related to the source of the
1172 * corresponding article on the wiki
1173 * Setting true will cause the change "article related" toggle to true
1177 public function setArticleFlag( $v ) {
1178 $this->mIsarticle
= $v;
1180 $this->mIsArticleRelated
= $v;
1185 * Return whether the content displayed page is related to the source of
1186 * the corresponding article on the wiki
1190 public function isArticle() {
1191 return $this->mIsarticle
;
1195 * Set whether this page is related an article on the wiki
1196 * Setting false will cause the change of "article flag" toggle to false
1200 public function setArticleRelated( $v ) {
1201 $this->mIsArticleRelated
= $v;
1203 $this->mIsarticle
= false;
1208 * Return whether this page is related an article on the wiki
1212 public function isArticleRelated() {
1213 return $this->mIsArticleRelated
;
1217 * Add new language links
1219 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1220 * (e.g. 'fr:Test page')
1222 public function addLanguageLinks( array $newLinkArray ) {
1223 $this->mLanguageLinks +
= $newLinkArray;
1227 * Reset the language links and add new language links
1229 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1230 * (e.g. 'fr:Test page')
1232 public function setLanguageLinks( array $newLinkArray ) {
1233 $this->mLanguageLinks
= $newLinkArray;
1237 * Get the list of language links
1239 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1241 public function getLanguageLinks() {
1242 return $this->mLanguageLinks
;
1246 * Add an array of categories, with names in the keys
1248 * @param array $categories Mapping category name => sort key
1250 public function addCategoryLinks( array $categories ) {
1253 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1257 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1259 # Set all the values to 'normal'.
1260 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1262 # Mark hidden categories
1263 foreach ( $res as $row ) {
1264 if ( isset( $row->pp_value
) ) {
1265 $categories[$row->page_title
] = 'hidden';
1269 # Add the remaining categories to the skin
1271 'OutputPageMakeCategoryLinks',
1272 [ &$this, $categories, &$this->mCategoryLinks
] )
1274 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1275 foreach ( $categories as $category => $type ) {
1276 // array keys will cast numeric category names to ints, so cast back to string
1277 $category = (string)$category;
1278 $origcategory = $category;
1279 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1283 $wgContLang->findVariantLink( $category, $title, true );
1284 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1287 $text = $wgContLang->convertHtml( $title->getText() );
1288 $this->mCategories
[$type][] = $title->getText();
1289 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1295 * @param array $categories
1296 * @return bool|ResultWrapper
1298 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1299 # Add the links to a LinkBatch
1300 $arr = [ NS_CATEGORY
=> $categories ];
1301 $lb = new LinkBatch
;
1302 $lb->setArray( $arr );
1304 # Fetch existence plus the hiddencat property
1305 $dbr = wfGetDB( DB_REPLICA
);
1306 $fields = array_merge(
1307 LinkCache
::getSelectFields(),
1308 [ 'page_namespace', 'page_title', 'pp_value' ]
1311 $res = $dbr->select( [ 'page', 'page_props' ],
1313 $lb->constructSet( 'page', $dbr ),
1316 [ 'page_props' => [ 'LEFT JOIN', [
1317 'pp_propname' => 'hiddencat',
1322 # Add the results to the link cache
1323 $lb->addResultToCache( LinkCache
::singleton(), $res );
1329 * Reset the category links (but not the category list) and add $categories
1331 * @param array $categories Mapping category name => sort key
1333 public function setCategoryLinks( array $categories ) {
1334 $this->mCategoryLinks
= [];
1335 $this->addCategoryLinks( $categories );
1339 * Get the list of category links, in a 2-D array with the following format:
1340 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1341 * hidden categories) and $link a HTML fragment with a link to the category
1346 public function getCategoryLinks() {
1347 return $this->mCategoryLinks
;
1351 * Get the list of category names this page belongs to.
1353 * @param string $type The type of categories which should be returned. Possible values:
1354 * * all: all categories of all types
1355 * * hidden: only the hidden categories
1356 * * normal: all categories, except hidden categories
1357 * @return array Array of strings
1359 public function getCategories( $type = 'all' ) {
1360 if ( $type === 'all' ) {
1361 $allCategories = [];
1362 foreach ( $this->mCategories
as $categories ) {
1363 $allCategories = array_merge( $allCategories, $categories );
1365 return $allCategories;
1367 if ( !isset( $this->mCategories
[$type] ) ) {
1368 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1370 return $this->mCategories
[$type];
1374 * Add an array of indicators, with their identifiers as array
1375 * keys and HTML contents as values.
1377 * In case of duplicate keys, existing values are overwritten.
1379 * @param array $indicators
1382 public function setIndicators( array $indicators ) {
1383 $this->mIndicators
= $indicators +
$this->mIndicators
;
1384 // Keep ordered by key
1385 ksort( $this->mIndicators
);
1389 * Get the indicators associated with this page.
1391 * The array will be internally ordered by item keys.
1393 * @return array Keys: identifiers, values: HTML contents
1396 public function getIndicators() {
1397 return $this->mIndicators
;
1401 * Adds help link with an icon via page indicators.
1402 * Link target can be overridden by a local message containing a wikilink:
1403 * the message key is: lowercase action or special page name + '-helppage'.
1404 * @param string $to Target MediaWiki.org page title or encoded URL.
1405 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1408 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1409 $this->addModuleStyles( 'mediawiki.helplink' );
1410 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1412 if ( $overrideBaseUrl ) {
1415 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1416 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1419 $link = Html
::rawElement(
1423 'target' => '_blank',
1424 'class' => 'mw-helplink',
1429 $this->setIndicators( [ 'mw-helplink' => $link ] );
1433 * Do not allow scripts which can be modified by wiki users to load on this page;
1434 * only allow scripts bundled with, or generated by, the software.
1435 * Site-wide styles are controlled by a config setting, since they can be
1436 * used to create a custom skin/theme, but not user-specific ones.
1438 * @todo this should be given a more accurate name
1440 public function disallowUserJs() {
1441 $this->reduceAllowedModules(
1442 ResourceLoaderModule
::TYPE_SCRIPTS
,
1443 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1446 // Site-wide styles are controlled by a config setting, see bug 71621
1447 // for background on why. User styles are never allowed.
1448 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1449 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1451 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1453 $this->reduceAllowedModules(
1454 ResourceLoaderModule
::TYPE_STYLES
,
1460 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1461 * @see ResourceLoaderModule::$origin
1462 * @param string $type ResourceLoaderModule TYPE_ constant
1463 * @return int ResourceLoaderModule ORIGIN_ class constant
1465 public function getAllowedModules( $type ) {
1466 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1467 return min( array_values( $this->mAllowedModules
) );
1469 return isset( $this->mAllowedModules
[$type] )
1470 ?
$this->mAllowedModules
[$type]
1471 : ResourceLoaderModule
::ORIGIN_ALL
;
1476 * Limit the highest level of CSS/JS untrustworthiness allowed.
1478 * If passed the same or a higher level than the current level of untrustworthiness set, the
1479 * level will remain unchanged.
1481 * @param string $type
1482 * @param int $level ResourceLoaderModule class constant
1484 public function reduceAllowedModules( $type, $level ) {
1485 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1489 * Prepend $text to the body HTML
1491 * @param string $text HTML
1493 public function prependHTML( $text ) {
1494 $this->mBodytext
= $text . $this->mBodytext
;
1498 * Append $text to the body HTML
1500 * @param string $text HTML
1502 public function addHTML( $text ) {
1503 $this->mBodytext
.= $text;
1507 * Shortcut for adding an Html::element via addHTML.
1511 * @param string $element
1512 * @param array $attribs
1513 * @param string $contents
1515 public function addElement( $element, array $attribs = [], $contents = '' ) {
1516 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1520 * Clear the body HTML
1522 public function clearHTML() {
1523 $this->mBodytext
= '';
1529 * @return string HTML
1531 public function getHTML() {
1532 return $this->mBodytext
;
1536 * Get/set the ParserOptions object to use for wikitext parsing
1538 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1539 * current ParserOption object
1540 * @return ParserOptions
1542 public function parserOptions( $options = null ) {
1543 if ( $options !== null && !empty( $options->isBogus
) ) {
1544 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1545 // been changed somehow, and keep it if so.
1546 $anonPO = ParserOptions
::newFromAnon();
1547 $anonPO->setEditSection( false );
1548 if ( !$options->matches( $anonPO ) ) {
1549 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1550 $options->isBogus
= false;
1554 if ( !$this->mParserOptions
) {
1555 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1556 // $wgUser isn't unstubbable yet, so don't try to get a
1557 // ParserOptions for it. And don't cache this ParserOptions
1559 $po = ParserOptions
::newFromAnon();
1560 $po->setEditSection( false );
1561 $po->isBogus
= true;
1562 if ( $options !== null ) {
1563 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1568 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1569 $this->mParserOptions
->setEditSection( false );
1572 if ( $options !== null && !empty( $options->isBogus
) ) {
1573 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1575 return wfSetVar( $this->mParserOptions
, null, true );
1577 return wfSetVar( $this->mParserOptions
, $options );
1582 * Set the revision ID which will be seen by the wiki text parser
1583 * for things such as embedded {{REVISIONID}} variable use.
1585 * @param int|null $revid An positive integer, or null
1586 * @return mixed Previous value
1588 public function setRevisionId( $revid ) {
1589 $val = is_null( $revid ) ?
null : intval( $revid );
1590 return wfSetVar( $this->mRevisionId
, $val );
1594 * Get the displayed revision ID
1598 public function getRevisionId() {
1599 return $this->mRevisionId
;
1603 * Set the timestamp of the revision which will be displayed. This is used
1604 * to avoid a extra DB call in Skin::lastModified().
1606 * @param string|null $timestamp
1607 * @return mixed Previous value
1609 public function setRevisionTimestamp( $timestamp ) {
1610 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1614 * Get the timestamp of displayed revision.
1615 * This will be null if not filled by setRevisionTimestamp().
1617 * @return string|null
1619 public function getRevisionTimestamp() {
1620 return $this->mRevisionTimestamp
;
1624 * Set the displayed file version
1626 * @param File|bool $file
1627 * @return mixed Previous value
1629 public function setFileVersion( $file ) {
1631 if ( $file instanceof File
&& $file->exists() ) {
1632 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1634 return wfSetVar( $this->mFileVersion
, $val, true );
1638 * Get the displayed file version
1640 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1642 public function getFileVersion() {
1643 return $this->mFileVersion
;
1647 * Get the templates used on this page
1649 * @return array (namespace => dbKey => revId)
1652 public function getTemplateIds() {
1653 return $this->mTemplateIds
;
1657 * Get the files used on this page
1659 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1662 public function getFileSearchOptions() {
1663 return $this->mImageTimeKeys
;
1667 * Convert wikitext to HTML and add it to the buffer
1668 * Default assumes that the current page title will be used.
1670 * @param string $text
1671 * @param bool $linestart Is this the start of a line?
1672 * @param bool $interface Is this text in the user interface language?
1673 * @throws MWException
1675 public function addWikiText( $text, $linestart = true, $interface = true ) {
1676 $title = $this->getTitle(); // Work around E_STRICT
1678 throw new MWException( 'Title is null' );
1680 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1684 * Add wikitext with a custom Title object
1686 * @param string $text Wikitext
1687 * @param Title $title
1688 * @param bool $linestart Is this the start of a line?
1690 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1691 $this->addWikiTextTitle( $text, $title, $linestart );
1695 * Add wikitext with a custom Title object and tidy enabled.
1697 * @param string $text Wikitext
1698 * @param Title $title
1699 * @param bool $linestart Is this the start of a line?
1701 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1702 $this->addWikiTextTitle( $text, $title, $linestart, true );
1706 * Add wikitext with tidy enabled
1708 * @param string $text Wikitext
1709 * @param bool $linestart Is this the start of a line?
1711 public function addWikiTextTidy( $text, $linestart = true ) {
1712 $title = $this->getTitle();
1713 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1717 * Add wikitext with a custom Title object
1719 * @param string $text Wikitext
1720 * @param Title $title
1721 * @param bool $linestart Is this the start of a line?
1722 * @param bool $tidy Whether to use tidy
1723 * @param bool $interface Whether it is an interface message
1724 * (for example disables conversion)
1726 public function addWikiTextTitle( $text, Title
$title, $linestart,
1727 $tidy = false, $interface = false
1731 $popts = $this->parserOptions();
1732 $oldTidy = $popts->setTidy( $tidy );
1733 $popts->setInterfaceMessage( (bool)$interface );
1735 $parserOutput = $wgParser->getFreshParser()->parse(
1736 $text, $title, $popts,
1737 $linestart, true, $this->mRevisionId
1740 $popts->setTidy( $oldTidy );
1742 $this->addParserOutput( $parserOutput );
1746 * Add a ParserOutput object, but without Html.
1748 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1749 * @param ParserOutput $parserOutput
1751 public function addParserOutputNoText( $parserOutput ) {
1752 wfDeprecated( __METHOD__
, '1.24' );
1753 $this->addParserOutputMetadata( $parserOutput );
1757 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1758 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1762 * @param ParserOutput $parserOutput
1764 public function addParserOutputMetadata( $parserOutput ) {
1765 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1766 $this->addCategoryLinks( $parserOutput->getCategories() );
1767 $this->setIndicators( $parserOutput->getIndicators() );
1768 $this->mNewSectionLink
= $parserOutput->getNewSection();
1769 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1771 if ( !$parserOutput->isCacheable() ) {
1772 $this->enableClientCache( false );
1774 $this->mNoGallery
= $parserOutput->getNoGallery();
1775 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1776 $this->addModules( $parserOutput->getModules() );
1777 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1778 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1779 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1780 $this->mPreventClickjacking
= $this->mPreventClickjacking
1781 ||
$parserOutput->preventClickjacking();
1783 // Template versioning...
1784 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1785 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1786 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1788 $this->mTemplateIds
[$ns] = $dbks;
1791 // File versioning...
1792 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1793 $this->mImageTimeKeys
[$dbk] = $data;
1796 // Hooks registered in the object
1797 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1798 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1799 list( $hookName, $data ) = $hookInfo;
1800 if ( isset( $parserOutputHooks[$hookName] ) ) {
1801 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1805 // enable OOUI if requested via ParserOutput
1806 if ( $parserOutput->getEnableOOUI() ) {
1807 $this->enableOOUI();
1810 // Link flags are ignored for now, but may in the future be
1811 // used to mark individual language links.
1813 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1814 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1818 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1819 * ParserOutput object, without any other metadata.
1822 * @param ParserOutput $parserOutput
1824 public function addParserOutputContent( $parserOutput ) {
1825 $this->addParserOutputText( $parserOutput );
1827 $this->addModules( $parserOutput->getModules() );
1828 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1829 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1831 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1835 * Add the HTML associated with a ParserOutput object, without any metadata.
1838 * @param ParserOutput $parserOutput
1840 public function addParserOutputText( $parserOutput ) {
1841 $text = $parserOutput->getText();
1842 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1843 $this->addHTML( $text );
1847 * Add everything from a ParserOutput object.
1849 * @param ParserOutput $parserOutput
1851 function addParserOutput( $parserOutput ) {
1852 $this->addParserOutputMetadata( $parserOutput );
1853 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1855 // Touch section edit links only if not previously disabled
1856 if ( $parserOutput->getEditSectionTokens() ) {
1857 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1860 $this->addParserOutputText( $parserOutput );
1864 * Add the output of a QuickTemplate to the output buffer
1866 * @param QuickTemplate $template
1868 public function addTemplate( &$template ) {
1869 $this->addHTML( $template->getHTML() );
1873 * Parse wikitext and return the HTML.
1875 * @param string $text
1876 * @param bool $linestart Is this the start of a line?
1877 * @param bool $interface Use interface language ($wgLang instead of
1878 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1879 * This also disables LanguageConverter.
1880 * @param Language $language Target language object, will override $interface
1881 * @throws MWException
1882 * @return string HTML
1884 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1887 if ( is_null( $this->getTitle() ) ) {
1888 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1891 $popts = $this->parserOptions();
1893 $popts->setInterfaceMessage( true );
1895 if ( $language !== null ) {
1896 $oldLang = $popts->setTargetLanguage( $language );
1899 $parserOutput = $wgParser->getFreshParser()->parse(
1900 $text, $this->getTitle(), $popts,
1901 $linestart, true, $this->mRevisionId
1905 $popts->setInterfaceMessage( false );
1907 if ( $language !== null ) {
1908 $popts->setTargetLanguage( $oldLang );
1911 return $parserOutput->getText();
1915 * Parse wikitext, strip paragraphs, and return the HTML.
1917 * @param string $text
1918 * @param bool $linestart Is this the start of a line?
1919 * @param bool $interface Use interface language ($wgLang instead of
1920 * $wgContLang) while parsing language sensitive magic
1921 * words like GRAMMAR and PLURAL
1922 * @return string HTML
1924 public function parseInline( $text, $linestart = true, $interface = false ) {
1925 $parsed = $this->parse( $text, $linestart, $interface );
1926 return Parser
::stripOuterParagraph( $parsed );
1931 * @deprecated since 1.27 Use setCdnMaxage() instead
1933 public function setSquidMaxage( $maxage ) {
1934 $this->setCdnMaxage( $maxage );
1938 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1940 * @param int $maxage Maximum cache time on the CDN, in seconds.
1942 public function setCdnMaxage( $maxage ) {
1943 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1947 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1949 * @param int $maxage Maximum cache time on the CDN, in seconds
1952 public function lowerCdnMaxage( $maxage ) {
1953 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1954 $this->setCdnMaxage( $this->mCdnMaxage
);
1958 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1960 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1961 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1962 * TTL is 90% of the age of the object, subject to the min and max.
1964 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1965 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1966 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1967 * @return integer TTL in seconds
1970 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1971 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1972 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1974 if ( $mtime === null ||
$mtime === false ) {
1975 return $minTTL; // entity does not exist
1978 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1979 $adaptiveTTL = max( .9 * $age, $minTTL );
1980 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1982 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1984 return $adaptiveTTL;
1988 * Use enableClientCache(false) to force it to send nocache headers
1990 * @param bool $state
1994 public function enableClientCache( $state ) {
1995 return wfSetVar( $this->mEnableClientCache
, $state );
1999 * Get the list of cookies that will influence on the cache
2003 function getCacheVaryCookies() {
2005 if ( $cookies === null ) {
2006 $config = $this->getConfig();
2007 $cookies = array_merge(
2008 SessionManager
::singleton()->getVaryCookies(),
2012 $config->get( 'CacheVaryCookies' )
2014 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2020 * Check if the request has a cache-varying cookie header
2021 * If it does, it's very important that we don't allow public caching
2025 function haveCacheVaryCookies() {
2026 $request = $this->getRequest();
2027 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2028 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2029 wfDebug( __METHOD__
. ": found $cookieName\n" );
2033 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2038 * Add an HTTP header that will influence on the cache
2040 * @param string $header Header name
2041 * @param string[]|null $option Options for the Key header. See
2042 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2043 * for the list of valid options.
2045 public function addVaryHeader( $header, array $option = null ) {
2046 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2047 $this->mVaryHeader
[$header] = [];
2049 if ( !is_array( $option ) ) {
2052 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2056 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2057 * such as Accept-Encoding or Cookie
2061 public function getVaryHeader() {
2062 // If we vary on cookies, let's make sure it's always included here too.
2063 if ( $this->getCacheVaryCookies() ) {
2064 $this->addVaryHeader( 'Cookie' );
2067 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2068 $this->addVaryHeader( $header, $options );
2070 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2074 * Get a complete Key header
2078 public function getKeyHeader() {
2079 $cvCookies = $this->getCacheVaryCookies();
2081 $cookiesOption = [];
2082 foreach ( $cvCookies as $cookieName ) {
2083 $cookiesOption[] = 'param=' . $cookieName;
2085 $this->addVaryHeader( 'Cookie', $cookiesOption );
2087 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2088 $this->addVaryHeader( $header, $options );
2092 foreach ( $this->mVaryHeader
as $header => $option ) {
2093 $newheader = $header;
2094 if ( is_array( $option ) && count( $option ) > 0 ) {
2095 $newheader .= ';' . implode( ';', $option );
2097 $headers[] = $newheader;
2099 $key = 'Key: ' . implode( ',', $headers );
2105 * T23672: Add Accept-Language to Vary and Key headers
2106 * if there's no 'variant' parameter existed in GET.
2109 * /w/index.php?title=Main_page should always be served; but
2110 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2112 function addAcceptLanguage() {
2113 $title = $this->getTitle();
2114 if ( !$title instanceof Title
) {
2118 $lang = $title->getPageLanguage();
2119 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2120 $variants = $lang->getVariants();
2122 foreach ( $variants as $variant ) {
2123 if ( $variant === $lang->getCode() ) {
2126 $aloption[] = 'substr=' . $variant;
2128 // IE and some other browsers use BCP 47 standards in
2129 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2130 // We should handle these too.
2131 $variantBCP47 = wfBCP47( $variant );
2132 if ( $variantBCP47 !== $variant ) {
2133 $aloption[] = 'substr=' . $variantBCP47;
2137 $this->addVaryHeader( 'Accept-Language', $aloption );
2142 * Set a flag which will cause an X-Frame-Options header appropriate for
2143 * edit pages to be sent. The header value is controlled by
2144 * $wgEditPageFrameOptions.
2146 * This is the default for special pages. If you display a CSRF-protected
2147 * form on an ordinary view page, then you need to call this function.
2149 * @param bool $enable
2151 public function preventClickjacking( $enable = true ) {
2152 $this->mPreventClickjacking
= $enable;
2156 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2157 * This can be called from pages which do not contain any CSRF-protected
2160 public function allowClickjacking() {
2161 $this->mPreventClickjacking
= false;
2165 * Get the prevent-clickjacking flag
2170 public function getPreventClickjacking() {
2171 return $this->mPreventClickjacking
;
2175 * Get the X-Frame-Options header value (without the name part), or false
2176 * if there isn't one. This is used by Skin to determine whether to enable
2177 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2181 public function getFrameOptions() {
2182 $config = $this->getConfig();
2183 if ( $config->get( 'BreakFrames' ) ) {
2185 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2186 return $config->get( 'EditPageFrameOptions' );
2192 * Send cache control HTTP headers
2194 public function sendCacheControl() {
2195 $response = $this->getRequest()->response();
2196 $config = $this->getConfig();
2198 $this->addVaryHeader( 'Cookie' );
2199 $this->addAcceptLanguage();
2201 # don't serve compressed data to clients who can't handle it
2202 # maintain different caches for logged-in users and non-logged in ones
2203 $response->header( $this->getVaryHeader() );
2205 if ( $config->get( 'UseKeyHeader' ) ) {
2206 $response->header( $this->getKeyHeader() );
2209 if ( $this->mEnableClientCache
) {
2211 $config->get( 'UseSquid' ) &&
2212 !$response->hasCookies() &&
2213 !SessionManager
::getGlobalSession()->isPersistent() &&
2214 !$this->isPrintable() &&
2215 $this->mCdnMaxage
!= 0 &&
2216 !$this->haveCacheVaryCookies()
2218 if ( $config->get( 'UseESI' ) ) {
2219 # We'll purge the proxy cache explicitly, but require end user agents
2220 # to revalidate against the proxy on each visit.
2221 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2222 wfDebug( __METHOD__
.
2223 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2224 # start with a shorter timeout for initial testing
2225 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2227 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2228 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2230 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2232 # We'll purge the proxy cache for anons explicitly, but require end user agents
2233 # to revalidate against the proxy on each visit.
2234 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2235 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2236 wfDebug( __METHOD__
.
2237 ": local proxy caching; {$this->mLastModified} **", 'private' );
2238 # start with a shorter timeout for initial testing
2239 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2240 $response->header( "Cache-Control: " .
2241 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2244 # We do want clients to cache if they can, but they *must* check for updates
2245 # on revisiting the page.
2246 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2247 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2248 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2250 if ( $this->mLastModified
) {
2251 $response->header( "Last-Modified: {$this->mLastModified}" );
2254 wfDebug( __METHOD__
. ": no caching **", 'private' );
2256 # In general, the absence of a last modified header should be enough to prevent
2257 # the client from using its cache. We send a few other things just to make sure.
2258 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2259 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2260 $response->header( 'Pragma: no-cache' );
2265 * Finally, all the text has been munged and accumulated into
2266 * the object, let's actually output it:
2268 * @param bool $return Set to true to get the result as a string rather than sending it
2269 * @return string|null
2271 * @throws FatalError
2272 * @throws MWException
2274 public function output( $return = false ) {
2277 if ( $this->mDoNothing
) {
2278 return $return ?
'' : null;
2281 $response = $this->getRequest()->response();
2282 $config = $this->getConfig();
2284 if ( $this->mRedirect
!= '' ) {
2285 # Standards require redirect URLs to be absolute
2286 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2288 $redirect = $this->mRedirect
;
2289 $code = $this->mRedirectCode
;
2291 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2292 if ( $code == '301' ||
$code == '303' ) {
2293 if ( !$config->get( 'DebugRedirects' ) ) {
2294 $response->statusHeader( $code );
2296 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2298 if ( $config->get( 'VaryOnXFP' ) ) {
2299 $this->addVaryHeader( 'X-Forwarded-Proto' );
2301 $this->sendCacheControl();
2303 $response->header( "Content-Type: text/html; charset=utf-8" );
2304 if ( $config->get( 'DebugRedirects' ) ) {
2305 $url = htmlspecialchars( $redirect );
2306 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2307 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2308 print "</body>\n</html>\n";
2310 $response->header( 'Location: ' . $redirect );
2314 return $return ?
'' : null;
2315 } elseif ( $this->mStatusCode
) {
2316 $response->statusHeader( $this->mStatusCode
);
2319 # Buffer output; final headers may depend on later processing
2322 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2323 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2325 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2326 // jQuery etc. can work correctly.
2327 $response->header( 'X-UA-Compatible: IE=Edge' );
2329 // Prevent framing, if requested
2330 $frameOptions = $this->getFrameOptions();
2331 if ( $frameOptions ) {
2332 $response->header( "X-Frame-Options: $frameOptions" );
2335 if ( $this->mArticleBodyOnly
) {
2336 echo $this->mBodytext
;
2338 $sk = $this->getSkin();
2339 // add skin specific modules
2340 $modules = $sk->getDefaultModules();
2342 // Enforce various default modules for all pages and all skins
2344 // Keep this list as small as possible
2346 'mediawiki.page.startup',
2350 // Support for high-density display images if enabled
2351 if ( $config->get( 'ResponsiveImages' ) ) {
2352 $coreModules[] = 'mediawiki.hidpi';
2355 $this->addModules( $coreModules );
2356 foreach ( $modules as $group ) {
2357 $this->addModules( $group );
2359 MWDebug
::addModules( $this );
2361 // Hook that allows last minute changes to the output page, e.g.
2362 // adding of CSS or Javascript by extensions.
2363 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2367 } catch ( Exception
$e ) {
2368 ob_end_clean(); // bug T129657
2374 // This hook allows last minute changes to final overall output by modifying output buffer
2375 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2376 } catch ( Exception
$e ) {
2377 ob_end_clean(); // bug T129657
2381 $this->sendCacheControl();
2384 return ob_get_clean();
2392 * Prepare this object to display an error page; disable caching and
2393 * indexing, clear the current text and redirect, set the page's title
2394 * and optionally an custom HTML title (content of the "<title>" tag).
2396 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2397 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2398 * optional, if not passed the "<title>" attribute will be
2399 * based on $pageTitle
2401 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2402 $this->setPageTitle( $pageTitle );
2403 if ( $htmlTitle !== false ) {
2404 $this->setHTMLTitle( $htmlTitle );
2406 $this->setRobotPolicy( 'noindex,nofollow' );
2407 $this->setArticleRelated( false );
2408 $this->enableClientCache( false );
2409 $this->mRedirect
= '';
2410 $this->clearSubtitle();
2415 * Output a standard error page
2417 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2418 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2419 * showErrorPage( 'titlemsg', $messageObject );
2420 * showErrorPage( $titleMessageObject, $messageObject );
2422 * @param string|Message $title Message key (string) for page title, or a Message object
2423 * @param string|Message $msg Message key (string) for page text, or a Message object
2424 * @param array $params Message parameters; ignored if $msg is a Message object
2426 public function showErrorPage( $title, $msg, $params = [] ) {
2427 if ( !$title instanceof Message
) {
2428 $title = $this->msg( $title );
2431 $this->prepareErrorPage( $title );
2433 if ( $msg instanceof Message
) {
2434 if ( $params !== [] ) {
2435 trigger_error( 'Argument ignored: $params. The message parameters argument '
2436 . 'is discarded when the $msg argument is a Message object instead of '
2437 . 'a string.', E_USER_NOTICE
);
2439 $this->addHTML( $msg->parseAsBlock() );
2441 $this->addWikiMsgArray( $msg, $params );
2444 $this->returnToMain();
2448 * Output a standard permission error page
2450 * @param array $errors Error message keys or [key, param...] arrays
2451 * @param string $action Action that was denied or null if unknown
2453 public function showPermissionsErrorPage( array $errors, $action = null ) {
2454 foreach ( $errors as $key => $error ) {
2455 $errors[$key] = (array)$error;
2458 // For some action (read, edit, create and upload), display a "login to do this action"
2459 // error if all of the following conditions are met:
2460 // 1. the user is not logged in
2461 // 2. the only error is insufficient permissions (i.e. no block or something else)
2462 // 3. the error can be avoided simply by logging in
2463 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2464 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2465 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2466 && ( User
::groupHasPermission( 'user', $action )
2467 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2469 $displayReturnto = null;
2471 # Due to bug 32276, if a user does not have read permissions,
2472 # $this->getTitle() will just give Special:Badtitle, which is
2473 # not especially useful as a returnto parameter. Use the title
2474 # from the request instead, if there was one.
2475 $request = $this->getRequest();
2476 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2477 if ( $action == 'edit' ) {
2478 $msg = 'whitelistedittext';
2479 $displayReturnto = $returnto;
2480 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2481 $msg = 'nocreatetext';
2482 } elseif ( $action == 'upload' ) {
2483 $msg = 'uploadnologintext';
2485 $msg = 'loginreqpagetext';
2486 $displayReturnto = Title
::newMainPage();
2492 $query['returnto'] = $returnto->getPrefixedText();
2494 if ( !$request->wasPosted() ) {
2495 $returntoquery = $request->getValues();
2496 unset( $returntoquery['title'] );
2497 unset( $returntoquery['returnto'] );
2498 unset( $returntoquery['returntoquery'] );
2499 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2502 $loginLink = Linker
::linkKnown(
2503 SpecialPage
::getTitleFor( 'Userlogin' ),
2504 $this->msg( 'loginreqlink' )->escaped(),
2509 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2510 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2512 # Don't return to a page the user can't read otherwise
2513 # we'll end up in a pointless loop
2514 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2515 $this->returnToMain( null, $displayReturnto );
2518 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2519 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2524 * Display an error page indicating that a given version of MediaWiki is
2525 * required to use it
2527 * @param mixed $version The version of MediaWiki needed to use the page
2529 public function versionRequired( $version ) {
2530 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2532 $this->addWikiMsg( 'versionrequiredtext', $version );
2533 $this->returnToMain();
2537 * Format a list of error messages
2539 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2540 * @param string $action Action that was denied or null if unknown
2541 * @return string The wikitext error-messages, formatted into a list.
2543 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2544 if ( $action == null ) {
2545 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2547 $action_desc = $this->msg( "action-$action" )->plain();
2549 'permissionserrorstext-withaction',
2552 )->plain() . "\n\n";
2555 if ( count( $errors ) > 1 ) {
2556 $text .= '<ul class="permissions-errors">' . "\n";
2558 foreach ( $errors as $error ) {
2560 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2565 $text .= "<div class=\"permissions-errors\">\n" .
2566 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2574 * Display a page stating that the Wiki is in read-only mode.
2575 * Should only be called after wfReadOnly() has returned true.
2577 * Historically, this function was used to show the source of the page that the user
2578 * was trying to edit and _also_ permissions error messages. The relevant code was
2579 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2581 * @deprecated since 1.25; throw the exception directly
2582 * @throws ReadOnlyError
2584 public function readOnlyPage() {
2585 if ( func_num_args() > 0 ) {
2586 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2589 throw new ReadOnlyError
;
2593 * Turn off regular page output and return an error response
2594 * for when rate limiting has triggered.
2596 * @deprecated since 1.25; throw the exception directly
2598 public function rateLimited() {
2599 wfDeprecated( __METHOD__
, '1.25' );
2600 throw new ThrottledError
;
2604 * Show a warning about replica DB lag
2606 * If the lag is higher than $wgSlaveLagCritical seconds,
2607 * then the warning is a bit more obvious. If the lag is
2608 * lower than $wgSlaveLagWarning, then no warning is shown.
2610 * @param int $lag Slave lag
2612 public function showLagWarning( $lag ) {
2613 $config = $this->getConfig();
2614 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2615 $lag = floor( $lag ); // floor to avoid nano seconds to display
2616 $message = $lag < $config->get( 'SlaveLagCritical' )
2619 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2620 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2624 public function showFatalError( $message ) {
2625 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2627 $this->addHTML( $message );
2630 public function showUnexpectedValueError( $name, $val ) {
2631 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2634 public function showFileCopyError( $old, $new ) {
2635 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2638 public function showFileRenameError( $old, $new ) {
2639 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2642 public function showFileDeleteError( $name ) {
2643 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2646 public function showFileNotFoundError( $name ) {
2647 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2651 * Add a "return to" link pointing to a specified title
2653 * @param Title $title Title to link
2654 * @param array $query Query string parameters
2655 * @param string $text Text of the link (input is not escaped)
2656 * @param array $options Options array to pass to Linker
2658 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2659 $linkRenderer = MediaWikiServices
::getInstance()
2660 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2661 $link = $this->msg( 'returnto' )->rawParams(
2662 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2663 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2667 * Add a "return to" link pointing to a specified title,
2668 * or the title indicated in the request, or else the main page
2670 * @param mixed $unused
2671 * @param Title|string $returnto Title or String to return to
2672 * @param string $returntoquery Query string for the return to link
2674 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2675 if ( $returnto == null ) {
2676 $returnto = $this->getRequest()->getText( 'returnto' );
2679 if ( $returntoquery == null ) {
2680 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2683 if ( $returnto === '' ) {
2684 $returnto = Title
::newMainPage();
2687 if ( is_object( $returnto ) ) {
2688 $titleObj = $returnto;
2690 $titleObj = Title
::newFromText( $returnto );
2692 if ( !is_object( $titleObj ) ) {
2693 $titleObj = Title
::newMainPage();
2696 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2699 private function getRlClientContext() {
2700 if ( !$this->rlClientContext
) {
2701 $query = ResourceLoader
::makeLoaderQuery(
2702 [], // modules; not relevant
2703 $this->getLanguage()->getCode(),
2704 $this->getSkin()->getSkinName(),
2705 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2706 null, // version; not relevant
2707 ResourceLoader
::inDebugMode(),
2708 null, // only; not relevant
2709 $this->isPrintable(),
2710 $this->getRequest()->getBool( 'handheld' )
2712 $this->rlClientContext
= new ResourceLoaderContext(
2713 $this->getResourceLoader(),
2714 new FauxRequest( $query )
2717 return $this->rlClientContext
;
2721 * Call this to freeze the module queue and JS config and create a formatter.
2723 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2724 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2725 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2726 * the module filters retroactively. Skins and extension hooks may also add modules until very
2727 * late in the request lifecycle.
2729 * @return ResourceLoaderClientHtml
2731 public function getRlClient() {
2732 if ( !$this->rlClient
) {
2733 $context = $this->getRlClientContext();
2734 $rl = $this->getResourceLoader();
2735 $this->addModules( [
2739 $this->addModuleStyles( [
2744 $this->getSkin()->setupSkinUserCss( $this );
2746 // Prepare exempt modules for buildExemptModules()
2747 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2749 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2751 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2752 // Separate user-specific batch for improved cache-hit ratio.
2753 $userBatch = [ 'user.styles', 'user' ];
2754 $siteBatch = array_diff( $moduleStyles, $userBatch );
2755 $dbr = wfGetDB( DB_REPLICA
);
2756 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2757 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2759 // Filter out modules handled by buildExemptModules()
2760 $moduleStyles = array_filter( $moduleStyles,
2761 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2762 $module = $rl->getModule( $name );
2764 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2765 $exemptStates[$name] = 'ready';
2766 // Special case in buildExemptModules()
2769 $group = $module->getGroup();
2770 if ( isset( $exemptGroups[$group] ) ) {
2771 $exemptStates[$name] = 'ready';
2772 if ( !$module->isKnownEmpty( $context ) ) {
2773 // E.g. Don't output empty <styles>
2774 $exemptGroups[$group][] = $name;
2782 $this->rlExemptStyleModules
= $exemptGroups;
2784 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2785 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2786 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2787 if ( !$isUserModuleFiltered ) {
2788 // Manually handled by getBottomScripts()
2789 $userModule = $rl->getModule( 'user' );
2790 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2793 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2796 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2797 $rlClient->setConfig( $this->getJSVars() );
2798 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2799 $rlClient->setModuleStyles( $moduleStyles );
2800 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2801 $rlClient->setExemptStates( $exemptStates );
2802 $this->rlClient
= $rlClient;
2804 return $this->rlClient
;
2808 * @param Skin $sk The given Skin
2809 * @param bool $includeStyle Unused
2810 * @return string The doctype, opening "<html>", and head element.
2812 public function headElement( Skin
$sk, $includeStyle = true ) {
2815 $userdir = $this->getLanguage()->getDir();
2816 $sitedir = $wgContLang->getDir();
2819 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2820 $this->getRlClient()->getDocumentAttributes(),
2821 $sk->getHtmlElementAttributes()
2823 $pieces[] = Html
::openElement( 'head' );
2825 if ( $this->getHTMLTitle() == '' ) {
2826 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2829 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2830 // Add <meta charset="UTF-8">
2831 // This should be before <title> since it defines the charset used by
2832 // text including the text inside <title>.
2833 // The spec recommends defining XHTML5's charset using the XML declaration
2835 // Our XML declaration is output by Html::htmlHeader.
2836 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2837 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2838 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2841 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2842 $pieces[] = $this->getRlClient()->getHeadHtml();
2843 $pieces[] = $this->buildExemptModules();
2844 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2845 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2846 $pieces[] = Html
::closeElement( 'head' );
2849 $bodyClasses[] = 'mediawiki';
2851 # Classes for LTR/RTL directionality support
2852 $bodyClasses[] = $userdir;
2853 $bodyClasses[] = "sitedir-$sitedir";
2855 $underline = $this->getUser()->getOption( 'underline' );
2856 if ( $underline < 2 ) {
2857 // The following classes can be used here:
2858 // * mw-underline-always
2859 // * mw-underline-never
2860 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2863 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2864 # A <body> class is probably not the best way to do this . . .
2865 $bodyClasses[] = 'capitalize-all-nouns';
2868 // Parser feature migration class
2869 // The idea is that this will eventually be removed, after the wikitext
2870 // which requires it is cleaned up.
2871 $bodyClasses[] = 'mw-hide-empty-elt';
2873 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2874 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2876 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2879 // While the implode() is not strictly needed, it's used for backwards compatibility
2880 // (this used to be built as a string and hooks likely still expect that).
2881 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2883 // Allow skins and extensions to add body attributes they need
2884 $sk->addToBodyAttributes( $this, $bodyAttrs );
2885 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2887 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2889 return self
::combineWrappedStrings( $pieces );
2893 * Get a ResourceLoader object associated with this OutputPage
2895 * @return ResourceLoader
2897 public function getResourceLoader() {
2898 if ( is_null( $this->mResourceLoader
) ) {
2899 $this->mResourceLoader
= new ResourceLoader(
2901 LoggerFactory
::getInstance( 'resourceloader' )
2904 return $this->mResourceLoader
;
2908 * Explicily load or embed modules on a page.
2910 * @param array|string $modules One or more module names
2911 * @param string $only ResourceLoaderModule TYPE_ class constant
2912 * @param array $extraQuery [optional] Array with extra query parameters for the request
2913 * @return string|WrappedStringList HTML
2915 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2916 // Apply 'target' and 'origin' filters
2917 $modules = $this->filterModules( (array)$modules, null, $only );
2919 return ResourceLoaderClientHtml
::makeLoad(
2920 $this->getRlClientContext(),
2928 * Combine WrappedString chunks and filter out empty ones
2930 * @param array $chunks
2931 * @return string|WrappedStringList HTML
2933 protected static function combineWrappedStrings( array $chunks ) {
2934 // Filter out empty values
2935 $chunks = array_filter( $chunks, 'strlen' );
2936 return WrappedString
::join( "\n", $chunks );
2939 private function isUserJsPreview() {
2940 return $this->getConfig()->get( 'AllowUserJs' )
2941 && $this->getTitle()
2942 && $this->getTitle()->isJsSubpage()
2943 && $this->userCanPreview();
2946 private function isUserCssPreview() {
2947 return $this->getConfig()->get( 'AllowUserCss' )
2948 && $this->getTitle()
2949 && $this->getTitle()->isCssSubpage()
2950 && $this->userCanPreview();
2954 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2955 * legacy scripts ($this->mScripts), and user JS.
2957 * @return string|WrappedStringList HTML
2959 public function getBottomScripts() {
2961 $chunks[] = $this->getRlClient()->getBodyHtml();
2963 // Legacy non-ResourceLoader scripts
2964 $chunks[] = $this->mScripts
;
2966 // Exempt 'user' module
2967 // - May need excludepages for live preview. (T28283)
2968 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2969 // ensures execution is scheduled after the "site" module.
2970 // - Don't load if module state is already resolved as "ready".
2971 if ( $this->rlUserModuleState
=== 'loading' ) {
2972 if ( $this->isUserJsPreview() ) {
2973 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2974 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2976 $chunks[] = ResourceLoader
::makeInlineScript(
2977 Xml
::encodeJsCall( 'mw.loader.using', [
2981 . Xml
::encodeJsCall( '$.globalEval', [
2982 $this->getRequest()->getText( 'wpTextbox1' )
2988 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2989 // asynchronously and may arrive *after* the inline script here. So the previewed code
2990 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2991 // Similarly, when previewing ./common.js and the user module does arrive first,
2992 // it will arrive without common.js and the inline script runs after.
2993 // Thus running common after the excluded subpage.
2996 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3000 return self
::combineWrappedStrings( $chunks );
3004 * Get the javascript config vars to include on this page
3006 * @return array Array of javascript config vars
3009 public function getJsConfigVars() {
3010 return $this->mJsConfigVars
;
3014 * Add one or more variables to be set in mw.config in JavaScript
3016 * @param string|array $keys Key or array of key/value pairs
3017 * @param mixed $value [optional] Value of the configuration variable
3019 public function addJsConfigVars( $keys, $value = null ) {
3020 if ( is_array( $keys ) ) {
3021 foreach ( $keys as $key => $value ) {
3022 $this->mJsConfigVars
[$key] = $value;
3027 $this->mJsConfigVars
[$keys] = $value;
3031 * Get an array containing the variables to be set in mw.config in JavaScript.
3033 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3034 * - in other words, page-independent/site-wide variables (without state).
3035 * You will only be adding bloat to the html page and causing page caches to
3036 * have to be purged on configuration changes.
3039 public function getJSVars() {
3044 $canonicalSpecialPageName = false; # bug 21115
3046 $title = $this->getTitle();
3047 $ns = $title->getNamespace();
3048 $canonicalNamespace = MWNamespace
::exists( $ns )
3049 ? MWNamespace
::getCanonicalName( $ns )
3050 : $title->getNsText();
3052 $sk = $this->getSkin();
3053 // Get the relevant title so that AJAX features can use the correct page name
3054 // when making API requests from certain special pages (bug 34972).
3055 $relevantTitle = $sk->getRelevantTitle();
3056 $relevantUser = $sk->getRelevantUser();
3058 if ( $ns == NS_SPECIAL
) {
3059 list( $canonicalSpecialPageName, /*...*/ ) =
3060 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3061 } elseif ( $this->canUseWikiPage() ) {
3062 $wikiPage = $this->getWikiPage();
3063 $curRevisionId = $wikiPage->getLatest();
3064 $articleId = $wikiPage->getId();
3067 $lang = $title->getPageViewLanguage();
3069 // Pre-process information
3070 $separatorTransTable = $lang->separatorTransformTable();
3071 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3072 $compactSeparatorTransTable = [
3073 implode( "\t", array_keys( $separatorTransTable ) ),
3074 implode( "\t", $separatorTransTable ),
3076 $digitTransTable = $lang->digitTransformTable();
3077 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3078 $compactDigitTransTable = [
3079 implode( "\t", array_keys( $digitTransTable ) ),
3080 implode( "\t", $digitTransTable ),
3083 $user = $this->getUser();
3086 'wgCanonicalNamespace' => $canonicalNamespace,
3087 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3088 'wgNamespaceNumber' => $title->getNamespace(),
3089 'wgPageName' => $title->getPrefixedDBkey(),
3090 'wgTitle' => $title->getText(),
3091 'wgCurRevisionId' => $curRevisionId,
3092 'wgRevisionId' => (int)$this->getRevisionId(),
3093 'wgArticleId' => $articleId,
3094 'wgIsArticle' => $this->isArticle(),
3095 'wgIsRedirect' => $title->isRedirect(),
3096 'wgAction' => Action
::getActionName( $this->getContext() ),
3097 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3098 'wgUserGroups' => $user->getEffectiveGroups(),
3099 'wgCategories' => $this->getCategories(),
3100 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3101 'wgPageContentLanguage' => $lang->getCode(),
3102 'wgPageContentModel' => $title->getContentModel(),
3103 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3104 'wgDigitTransformTable' => $compactDigitTransTable,
3105 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3106 'wgMonthNames' => $lang->getMonthNamesArray(),
3107 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3108 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3109 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3110 'wgRequestId' => WebRequest
::getRequestId(),
3113 if ( $user->isLoggedIn() ) {
3114 $vars['wgUserId'] = $user->getId();
3115 $vars['wgUserEditCount'] = $user->getEditCount();
3116 $userReg = $user->getRegistration();
3117 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3118 // Get the revision ID of the oldest new message on the user's talk
3119 // page. This can be used for constructing new message alerts on
3121 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3124 if ( $wgContLang->hasVariants() ) {
3125 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3127 // Same test as SkinTemplate
3128 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3129 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3131 foreach ( $title->getRestrictionTypes() as $type ) {
3132 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3135 if ( $title->isMainPage() ) {
3136 $vars['wgIsMainPage'] = true;
3139 if ( $this->mRedirectedFrom
) {
3140 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3143 if ( $relevantUser ) {
3144 $vars['wgRelevantUserName'] = $relevantUser->getName();
3147 // Allow extensions to add their custom variables to the mw.config map.
3148 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3149 // page-dependant but site-wide (without state).
3150 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3151 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3153 // Merge in variables from addJsConfigVars last
3154 return array_merge( $vars, $this->getJsConfigVars() );
3158 * To make it harder for someone to slip a user a fake
3159 * user-JavaScript or user-CSS preview, a random token
3160 * is associated with the login session. If it's not
3161 * passed back with the preview request, we won't render
3166 public function userCanPreview() {
3167 $request = $this->getRequest();
3169 $request->getVal( 'action' ) !== 'submit' ||
3170 !$request->getCheck( 'wpPreview' ) ||
3171 !$request->wasPosted()
3176 $user = $this->getUser();
3178 if ( !$user->isLoggedIn() ) {
3179 // Anons have predictable edit tokens
3182 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3186 $title = $this->getTitle();
3187 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3190 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3191 // Don't execute another user's CSS or JS on preview (T85855)
3195 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3196 if ( count( $errors ) !== 0 ) {
3204 * @return array Array in format "link name or number => 'link html'".
3206 public function getHeadLinksArray() {
3210 $config = $this->getConfig();
3212 $canonicalUrl = $this->mCanonicalUrl
;
3214 $tags['meta-generator'] = Html
::element( 'meta', [
3215 'name' => 'generator',
3216 'content' => "MediaWiki $wgVersion",
3219 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3220 $tags['meta-referrer'] = Html
::element( 'meta', [
3221 'name' => 'referrer',
3222 'content' => $config->get( 'ReferrerPolicy' )
3226 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3227 if ( $p !== 'index,follow' ) {
3228 // http://www.robotstxt.org/wc/meta-user.html
3229 // Only show if it's different from the default robots policy
3230 $tags['meta-robots'] = Html
::element( 'meta', [
3236 foreach ( $this->mMetatags
as $tag ) {
3237 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3239 $tag[0] = substr( $tag[0], 5 );
3243 $tagName = "meta-{$tag[0]}";
3244 if ( isset( $tags[$tagName] ) ) {
3245 $tagName .= $tag[1];
3247 $tags[$tagName] = Html
::element( 'meta',
3250 'content' => $tag[1]
3255 foreach ( $this->mLinktags
as $tag ) {
3256 $tags[] = Html
::element( 'link', $tag );
3259 # Universal edit button
3260 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3261 $user = $this->getUser();
3262 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3263 && ( $this->getTitle()->exists() ||
3264 $this->getTitle()->quickUserCan( 'create', $user ) )
3266 // Original UniversalEditButton
3267 $msg = $this->msg( 'edit' )->text();
3268 $tags['universal-edit-button'] = Html
::element( 'link', [
3269 'rel' => 'alternate',
3270 'type' => 'application/x-wiki',
3272 'href' => $this->getTitle()->getEditURL(),
3274 // Alternate edit link
3275 $tags['alternative-edit'] = Html
::element( 'link', [
3278 'href' => $this->getTitle()->getEditURL(),
3283 # Generally the order of the favicon and apple-touch-icon links
3284 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3285 # uses whichever one appears later in the HTML source. Make sure
3286 # apple-touch-icon is specified first to avoid this.
3287 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3288 $tags['apple-touch-icon'] = Html
::element( 'link', [
3289 'rel' => 'apple-touch-icon',
3290 'href' => $config->get( 'AppleTouchIcon' )
3294 if ( $config->get( 'Favicon' ) !== false ) {
3295 $tags['favicon'] = Html
::element( 'link', [
3296 'rel' => 'shortcut icon',
3297 'href' => $config->get( 'Favicon' )
3301 # OpenSearch description link
3302 $tags['opensearch'] = Html
::element( 'link', [
3304 'type' => 'application/opensearchdescription+xml',
3305 'href' => wfScript( 'opensearch_desc' ),
3306 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3309 if ( $config->get( 'EnableAPI' ) ) {
3310 # Real Simple Discovery link, provides auto-discovery information
3311 # for the MediaWiki API (and potentially additional custom API
3312 # support such as WordPress or Twitter-compatible APIs for a
3313 # blogging extension, etc)
3314 $tags['rsd'] = Html
::element( 'link', [
3316 'type' => 'application/rsd+xml',
3317 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3318 // Whether RSD accepts relative or protocol-relative URLs is completely
3319 // undocumented, though.
3320 'href' => wfExpandUrl( wfAppendQuery(
3322 [ 'action' => 'rsd' ] ),
3329 if ( !$config->get( 'DisableLangConversion' ) ) {
3330 $lang = $this->getTitle()->getPageLanguage();
3331 if ( $lang->hasVariants() ) {
3332 $variants = $lang->getVariants();
3333 foreach ( $variants as $variant ) {
3334 $tags["variant-$variant"] = Html
::element( 'link', [
3335 'rel' => 'alternate',
3336 'hreflang' => wfBCP47( $variant ),
3337 'href' => $this->getTitle()->getLocalURL(
3338 [ 'variant' => $variant ] )
3342 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3343 $tags["variant-x-default"] = Html
::element( 'link', [
3344 'rel' => 'alternate',
3345 'hreflang' => 'x-default',
3346 'href' => $this->getTitle()->getLocalURL() ] );
3351 if ( $this->copyrightUrl
!== null ) {
3352 $copyright = $this->copyrightUrl
;
3355 if ( $config->get( 'RightsPage' ) ) {
3356 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3359 $copyright = $copy->getLocalURL();
3363 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3364 $copyright = $config->get( 'RightsUrl' );
3369 $tags['copyright'] = Html
::element( 'link', [
3370 'rel' => 'copyright',
3371 'href' => $copyright ]
3376 if ( $config->get( 'Feed' ) ) {
3379 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3380 # Use the page name for the title. In principle, this could
3381 # lead to issues with having the same name for different feeds
3382 # corresponding to the same page, but we can't avoid that at
3385 $feedLinks[] = $this->feedLink(
3388 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3390 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3395 # Recent changes feed should appear on every page (except recentchanges,
3396 # that would be redundant). Put it after the per-page feed to avoid
3397 # changing existing behavior. It's still available, probably via a
3398 # menu in your browser. Some sites might have a different feed they'd
3399 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3400 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3401 # If so, use it instead.
3402 $sitename = $config->get( 'Sitename' );
3403 if ( $config->get( 'OverrideSiteFeed' ) ) {
3404 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3405 // Note, this->feedLink escapes the url.
3406 $feedLinks[] = $this->feedLink(
3409 $this->msg( "site-{$type}-feed", $sitename )->text()
3412 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3413 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3414 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3415 $feedLinks[] = $this->feedLink(
3417 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3418 # For grep: 'site-rss-feed', 'site-atom-feed'
3419 $this->msg( "site-{$format}-feed", $sitename )->text()
3424 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3425 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3426 # use OutputPage::addFeedLink() instead.
3427 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3429 $tags +
= $feedLinks;
3433 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3434 if ( $canonicalUrl !== false ) {
3435 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3437 if ( $this->isArticleRelated() ) {
3438 // This affects all requests where "setArticleRelated" is true. This is
3439 // typically all requests that show content (query title, curid, oldid, diff),
3440 // and all wikipage actions (edit, delete, purge, info, history etc.).
3441 // It does not apply to File pages and Special pages.
3442 // 'history' and 'info' actions address page metadata rather than the page
3443 // content itself, so they may not be canonicalized to the view page url.
3444 // TODO: this ought to be better encapsulated in the Action class.
3445 $action = Action
::getActionName( $this->getContext() );
3446 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3447 $query = "action={$action}";
3451 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3453 $reqUrl = $this->getRequest()->getRequestURL();
3454 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3458 if ( $canonicalUrl !== false ) {
3459 $tags[] = Html
::element( 'link', [
3460 'rel' => 'canonical',
3461 'href' => $canonicalUrl
3469 * @return string HTML tag links to be put in the header.
3470 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3471 * OutputPage::getHeadLinksArray directly.
3473 public function getHeadLinks() {
3474 wfDeprecated( __METHOD__
, '1.24' );
3475 return implode( "\n", $this->getHeadLinksArray() );
3479 * Generate a "<link rel/>" for a feed.
3481 * @param string $type Feed type
3482 * @param string $url URL to the feed
3483 * @param string $text Value of the "title" attribute
3484 * @return string HTML fragment
3486 private function feedLink( $type, $url, $text ) {
3487 return Html
::element( 'link', [
3488 'rel' => 'alternate',
3489 'type' => "application/$type+xml",
3496 * Add a local or specified stylesheet, with the given media options.
3497 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3499 * @param string $style URL to the file
3500 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3501 * @param string $condition For IE conditional comments, specifying an IE version
3502 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3504 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3507 $options['media'] = $media;
3510 $options['condition'] = $condition;
3513 $options['dir'] = $dir;
3515 $this->styles
[$style] = $options;
3519 * Adds inline CSS styles
3520 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3522 * @param mixed $style_css Inline CSS
3523 * @param string $flip Set to 'flip' to flip the CSS if needed
3525 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3526 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3527 # If wanted, and the interface is right-to-left, flip the CSS
3528 $style_css = CSSJanus
::transform( $style_css, true, false );
3530 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3534 * Build exempt modules and legacy non-ResourceLoader styles.
3536 * @return string|WrappedStringList HTML
3538 protected function buildExemptModules() {
3541 $resourceLoader = $this->getResourceLoader();
3543 // Things that go after the ResourceLoaderDynamicStyles marker
3546 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3547 if ( $this->isUserCssPreview() ) {
3548 $append[] = $this->makeResourceLoaderLink(
3550 ResourceLoaderModule
::TYPE_STYLES
,
3551 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3554 // Load the previewed CSS. Janus it if needed.
3555 // User-supplied CSS is assumed to in the wiki's content language.
3556 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3557 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3558 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3560 $append[] = Html
::inlineStyle( $previewedCSS );
3563 // We want site, private and user styles to override dynamically added styles from
3564 // general modules, but we want dynamically added styles to override statically added
3565 // style modules. So the order has to be:
3566 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3567 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3568 // - ResourceLoaderDynamicStyles marker
3569 // - site/private/user styles
3571 // Add legacy styles added through addStyle()/addInlineStyle() here
3572 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3574 $chunks[] = Html
::element(
3576 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3579 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3580 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3581 ResourceLoaderModule
::TYPE_STYLES
3585 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3591 public function buildCssLinksArray() {
3594 // Add any extension CSS
3595 foreach ( $this->mExtStyles
as $url ) {
3596 $this->addStyle( $url );
3598 $this->mExtStyles
= [];
3600 foreach ( $this->styles
as $file => $options ) {
3601 $link = $this->styleLink( $file, $options );
3603 $links[$file] = $link;
3610 * Generate \<link\> tags for stylesheets
3612 * @param string $style URL to the file
3613 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3614 * @return string HTML fragment
3616 protected function styleLink( $style, array $options ) {
3617 if ( isset( $options['dir'] ) ) {
3618 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3623 if ( isset( $options['media'] ) ) {
3624 $media = self
::transformCssMedia( $options['media'] );
3625 if ( is_null( $media ) ) {
3632 if ( substr( $style, 0, 1 ) == '/' ||
3633 substr( $style, 0, 5 ) == 'http:' ||
3634 substr( $style, 0, 6 ) == 'https:' ) {
3637 $config = $this->getConfig();
3638 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3639 $config->get( 'StyleVersion' );
3642 $link = Html
::linkedStyle( $url, $media );
3644 if ( isset( $options['condition'] ) ) {
3645 $condition = htmlspecialchars( $options['condition'] );
3646 $link = "<!--[if $condition]>$link<![endif]-->";
3652 * Transform path to web-accessible static resource.
3654 * This is used to add a validation hash as query string.
3655 * This aids various behaviors:
3657 * - Put long Cache-Control max-age headers on responses for improved
3658 * cache performance.
3659 * - Get the correct version of a file as expected by the current page.
3660 * - Instantly get the updated version of a file after deployment.
3662 * Avoid using this for urls included in HTML as otherwise clients may get different
3663 * versions of a resource when navigating the site depending on when the page was cached.
3664 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3665 * an external stylesheet).
3668 * @param Config $config
3669 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3670 * @return string URL
3672 public static function transformResourcePath( Config
$config, $path ) {
3674 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3675 if ( $remotePathPrefix === '' ) {
3676 // The configured base path is required to be empty string for
3677 // wikis in the domain root
3680 $remotePath = $remotePathPrefix;
3682 if ( strpos( $path, $remotePath ) !== 0 ) {
3683 // Path is outside wgResourceBasePath, ignore.
3686 $path = RelPath\
getRelativePath( $path, $remotePath );
3687 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3691 * Utility method for transformResourceFilePath().
3693 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3696 * @param string $remotePath URL path prefix that points to $localPath
3697 * @param string $localPath File directory exposed at $remotePath
3698 * @param string $file Path to target file relative to $localPath
3699 * @return string URL
3701 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3702 $hash = md5_file( "$localPath/$file" );
3703 if ( $hash === false ) {
3704 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3707 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3711 * Transform "media" attribute based on request parameters
3713 * @param string $media Current value of the "media" attribute
3714 * @return string Modified value of the "media" attribute, or null to skip
3717 public static function transformCssMedia( $media ) {
3720 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3721 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3723 // Switch in on-screen display for media testing
3725 'printable' => 'print',
3726 'handheld' => 'handheld',
3728 foreach ( $switches as $switch => $targetMedia ) {
3729 if ( $wgRequest->getBool( $switch ) ) {
3730 if ( $media == $targetMedia ) {
3732 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3733 /* This regex will not attempt to understand a comma-separated media_query_list
3735 * Example supported values for $media:
3736 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3737 * Example NOT supported value for $media:
3738 * '3d-glasses, screen, print and resolution > 90dpi'
3740 * If it's a print request, we never want any kind of screen stylesheets
3741 * If it's a handheld request (currently the only other choice with a switch),
3742 * we don't want simple 'screen' but we might want screen queries that
3743 * have a max-width or something, so we'll pass all others on and let the
3744 * client do the query.
3746 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3757 * Add a wikitext-formatted message to the output.
3758 * This is equivalent to:
3760 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3762 public function addWikiMsg( /*...*/ ) {
3763 $args = func_get_args();
3764 $name = array_shift( $args );
3765 $this->addWikiMsgArray( $name, $args );
3769 * Add a wikitext-formatted message to the output.
3770 * Like addWikiMsg() except the parameters are taken as an array
3771 * instead of a variable argument list.
3773 * @param string $name
3774 * @param array $args
3776 public function addWikiMsgArray( $name, $args ) {
3777 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3781 * This function takes a number of message/argument specifications, wraps them in
3782 * some overall structure, and then parses the result and adds it to the output.
3784 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3785 * and so on. The subsequent arguments may be either
3786 * 1) strings, in which case they are message names, or
3787 * 2) arrays, in which case, within each array, the first element is the message
3788 * name, and subsequent elements are the parameters to that message.
3790 * Don't use this for messages that are not in the user's interface language.
3794 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3798 * $wgOut->addWikiText( "<div class='error'>\n"
3799 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3801 * The newline after the opening div is needed in some wikitext. See bug 19226.
3803 * @param string $wrap
3805 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3806 $msgSpecs = func_get_args();
3807 array_shift( $msgSpecs );
3808 $msgSpecs = array_values( $msgSpecs );
3810 foreach ( $msgSpecs as $n => $spec ) {
3811 if ( is_array( $spec ) ) {
3813 $name = array_shift( $args );
3814 if ( isset( $args['options'] ) ) {
3815 unset( $args['options'] );
3817 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3825 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3827 $this->addWikiText( $s );
3831 * Enables/disables TOC, doesn't override __NOTOC__
3835 public function enableTOC( $flag = true ) {
3836 $this->mEnableTOC
= $flag;
3843 public function isTOCEnabled() {
3844 return $this->mEnableTOC
;
3848 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3852 public function enableSectionEditLinks( $flag = true ) {
3853 $this->mEnableSectionEditLinks
= $flag;
3860 public function sectionEditLinksEnabled() {
3861 return $this->mEnableSectionEditLinks
;
3865 * Helper function to setup the PHP implementation of OOUI to use in this request.
3868 * @param String $skinName The Skin name to determine the correct OOUI theme
3869 * @param String $dir Language direction
3871 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3872 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3873 // Make keys (skin names) lowercase for case-insensitive matching.
3874 $themes = array_change_key_case( $themes, CASE_LOWER
);
3875 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3876 // For example, 'OOUI\MediaWikiTheme'.
3877 $themeClass = "OOUI\\{$theme}Theme";
3878 OOUI\Theme
::setSingleton( new $themeClass() );
3879 OOUI\Element
::setDefaultDir( $dir );
3883 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3884 * MediaWiki and this OutputPage instance.
3888 public function enableOOUI() {
3890 strtolower( $this->getSkin()->getSkinName() ),
3891 $this->getLanguage()->getDir()
3893 $this->addModuleStyles( [
3894 'oojs-ui-core.styles',
3895 'oojs-ui.styles.icons',
3896 'oojs-ui.styles.indicators',
3897 'oojs-ui.styles.textures',
3898 'mediawiki.widgets.styles',