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\Session\SessionManager
;
25 use WrappedString\WrappedString
;
26 use WrappedString\WrappedStringList
;
29 * This class should be covered by a general architecture document which does
30 * not exist as of January 2011. This is one of the Core classes and should
31 * be read at least once by any new developers.
33 * This class is used to prepare the final rendering. A skin is then
34 * applied to the output parameters (links, javascript, html, categories ...).
36 * @todo FIXME: Another class handles sending the whole page to the client.
38 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
43 class OutputPage
extends ContextSource
{
44 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
45 protected $mMetatags = [];
48 protected $mLinktags = [];
51 protected $mCanonicalUrl = false;
54 * @var array Additional stylesheets. Looks like this is for extensions.
55 * Might be replaced by ResourceLoader.
57 protected $mExtStyles = [];
60 * @var string Should be private - has getter and setter. Contains
62 public $mPagetitle = '';
65 * @var string Contains all of the "<body>" content. Should be private we
66 * got set/get accessors and the append() method.
68 public $mBodytext = '';
71 * Holds the debug lines that will be output as comments in page source if
72 * $wgDebugComments is enabled. See also $wgShowDebug.
73 * @deprecated since 1.20; use MWDebug class instead.
75 public $mDebugtext = '';
77 /** @var string Stores contents of "<title>" tag */
78 private $mHTMLtitle = '';
81 * @var bool Is the displayed content related to the source of the
82 * corresponding wiki article.
84 private $mIsarticle = false;
86 /** @var bool Stores "article flag" toggle. */
87 private $mIsArticleRelated = true;
90 * @var bool We have to set isPrintable(). Some pages should
91 * never be printed (ex: redirections).
93 private $mPrintable = false;
96 * @var array Contains the page subtitle. Special pages usually have some
97 * links here. Don't confuse with site subtitle added by skins.
99 private $mSubtitle = [];
102 public $mRedirect = '';
105 protected $mStatusCode;
108 * @var string Used for sending cache control.
109 * The whole caching system should probably be moved into its own class.
111 protected $mLastModified = '';
114 protected $mCategoryLinks = [];
117 protected $mCategories = [];
120 protected $mIndicators = [];
122 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
123 private $mLanguageLinks = [];
126 * Used for JavaScript (predates ResourceLoader)
127 * @todo We should split JS / CSS.
128 * mScripts content is inserted as is in "<head>" by Skin. This might
129 * contain either a link to a stylesheet or inline CSS.
131 private $mScripts = '';
133 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
134 protected $mInlineStyles = '';
137 * @var string Used by skin template.
138 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
140 public $mPageLinkTitle = '';
142 /** @var array Array of elements in "<head>". Parser might add its own headers! */
143 protected $mHeadItems = [];
146 protected $mModules = [];
149 protected $mModuleScripts = [];
152 protected $mModuleStyles = [];
154 /** @var ResourceLoader */
155 protected $mResourceLoader;
157 /** @var ResourceLoaderClientHtml */
160 /** @var ResourceLoaderContext */
161 private $rlClientContext;
164 private $rlUserModuleState;
167 private $rlExemptStyleModules;
170 protected $mJsConfigVars = [];
173 protected $mTemplateIds = [];
176 protected $mImageTimeKeys = [];
179 public $mRedirectCode = '';
181 protected $mFeedLinksAppendQuery = null;
184 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
185 * @see ResourceLoaderModule::$origin
186 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
188 protected $mAllowedModules = [
189 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
192 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
193 protected $mDoNothing = false;
198 protected $mContainsNewMagic = 0;
201 * lazy initialised, use parserOptions()
204 protected $mParserOptions = null;
207 * Handles the Atom / RSS links.
208 * We probably only support Atom in 2011.
209 * @see $wgAdvertisedFeedTypes
211 private $mFeedLinks = [];
213 // Gwicke work on squid caching? Roughly from 2003.
214 protected $mEnableClientCache = true;
216 /** @var bool Flag if output should only contain the body of the article. */
217 private $mArticleBodyOnly = false;
220 protected $mNewSectionLink = false;
223 protected $mHideNewSectionLink = false;
226 * @var bool Comes from the parser. This was probably made to load CSS/JS
227 * only if we had "<gallery>". Used directly in CategoryPage.php.
228 * Looks like ResourceLoader can replace this.
230 public $mNoGallery = false;
233 private $mPageTitleActionText = '';
235 /** @var int Cache stuff. Looks like mEnableClientCache */
236 protected $mCdnMaxage = 0;
237 /** @var int Upper limit on mCdnMaxage */
238 protected $mCdnMaxageLimit = INF
;
241 * @var bool Controls if anti-clickjacking / frame-breaking headers will
242 * be sent. This should be done for pages where edit actions are possible.
243 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
245 protected $mPreventClickjacking = true;
247 /** @var int To include the variable {{REVISIONID}} */
248 private $mRevisionId = null;
251 private $mRevisionTimestamp = null;
254 protected $mFileVersion = null;
257 * @var array An array of stylesheet filenames (relative from skins path),
258 * with options for CSS media, IE conditions, and RTL/LTR direction.
259 * For internal use; add settings in the skin via $this->addStyle()
261 * Style again! This seems like a code duplication since we already have
262 * mStyles. This is what makes Open Source amazing.
264 protected $styles = [];
266 private $mIndexPolicy = 'index';
267 private $mFollowPolicy = 'follow';
268 private $mVaryHeader = [
269 'Accept-Encoding' => [ 'match=gzip' ],
273 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
278 private $mRedirectedFrom = null;
281 * Additional key => value data
283 private $mProperties = [];
286 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
288 private $mTarget = null;
291 * @var bool Whether parser output should contain table of contents
293 private $mEnableTOC = true;
296 * @var bool Whether parser output should contain section edit links
298 private $mEnableSectionEditLinks = true;
301 * @var string|null The URL to send in a <link> element with rel=copyright
303 private $copyrightUrl;
305 /** @var array Profiling data */
306 private $limitReportData = [];
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource|null $context
314 function __construct( IContextSource
$context = null ) {
315 if ( $context === null ) {
316 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
317 wfDeprecated( __METHOD__
, '1.18' );
319 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect
= str_replace( "\n", '', $url );
332 $this->mRedirectCode
= $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
340 public function getRedirect() {
341 return $this->mRedirect
;
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
350 * @param string|null $url
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl
= $url;
357 * Set the HTTP status code to send with the output.
359 * @param int $statusCode
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode
= $statusCode;
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
369 * @param string $name Tag name
370 * @param string $val Tag value
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags
, [ $name, $val ] );
377 * Returns the current <meta> tags
382 public function getMetaTags() {
383 return $this->mMetatags
;
387 * Add a new \<link\> tag to the page header.
389 * Note: use setCanonicalUrl() for rel=canonical.
391 * @param array $linkarr Associative array of attributes.
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags
, $linkarr );
398 * Returns the current <link> tags
403 public function getLinkTags() {
404 return $this->mLinktags
;
408 * Add a new \<link\> with "rel" attribute set to "meta"
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl
= $url;
429 * Returns the URL to be used for the <link rel=canonical> if
433 * @return bool|string
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl
;
440 * Get the value of the "rel" attribute for metadata links
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
448 return 'alternate meta';
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts
.= $script;
467 * Register and add a stylesheet from an extension directory.
469 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
470 * @param string $url Path to sheet. Provide either a full url (beginning
471 * with 'http', etc) or a relative path from the document root
472 * (beginning with '/'). Otherwise it behaves identically to
473 * addStyle() and draws from the /skins folder.
475 public function addExtensionStyle( $url ) {
476 wfDeprecated( __METHOD__
, '1.27' );
477 array_push( $this->mExtStyles
, $url );
481 * Get all styles added by extensions
483 * @deprecated since 1.27
486 function getExtStyle() {
487 wfDeprecated( __METHOD__
, '1.27' );
488 return $this->mExtStyles
;
492 * Add a JavaScript file out of skins/common, or a given relative path.
493 * Internal use only. Use OutputPage::addModules() if possible.
495 * @param string $file Filename in skins/common or complete on-server path
497 * @param string $version Style version of the file. Defaults to $wgStyleVersion
499 public function addScriptFile( $file, $version = null ) {
500 // See if $file parameter is an absolute URL or begins with a slash
501 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
504 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
506 if ( is_null( $version ) ) {
507 $version = $this->getConfig()->get( 'StyleVersion' );
509 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
513 * Add a self-contained script tag with the given contents
514 * Internal use only. Use OutputPage::addModules() if possible.
516 * @param string $script JavaScript text, no script tags
518 public function addInlineScript( $script ) {
519 $this->mScripts
.= Html
::inlineScript( $script );
523 * Filter an array of modules to remove insufficiently trustworthy members, and modules
524 * which are no longer registered (eg a page is cached before an extension is disabled)
525 * @param array $modules
526 * @param string|null $position If not null, only return modules with this position
527 * @param string $type
530 protected function filterModules( array $modules, $position = null,
531 $type = ResourceLoaderModule
::TYPE_COMBINED
533 $resourceLoader = $this->getResourceLoader();
534 $filteredModules = [];
535 foreach ( $modules as $val ) {
536 $module = $resourceLoader->getModule( $val );
537 if ( $module instanceof ResourceLoaderModule
538 && $module->getOrigin() <= $this->getAllowedModules( $type )
539 && ( is_null( $position ) ||
$module->getPosition() == $position )
540 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
542 $filteredModules[] = $val;
545 return $filteredModules;
549 * Get the list of modules to include on this page
551 * @param bool $filter Whether to filter out insufficiently trustworthy modules
552 * @param string|null $position If not null, only return modules with this position
553 * @param string $param
554 * @return array Array of module names
556 public function getModules( $filter = false, $position = null, $param = 'mModules',
557 $type = ResourceLoaderModule
::TYPE_COMBINED
559 $modules = array_values( array_unique( $this->$param ) );
561 ?
$this->filterModules( $modules, $position, $type )
566 * Add one or more modules recognized by ResourceLoader. Modules added
567 * through this function will be loaded by ResourceLoader when the
570 * @param string|array $modules Module name (string) or array of module names
572 public function addModules( $modules ) {
573 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
577 * Get the list of module JS to include on this page
579 * @param bool $filter
580 * @param string|null $position
581 * @return array Array of module names
583 public function getModuleScripts( $filter = false, $position = null ) {
584 return $this->getModules( $filter, $position, 'mModuleScripts',
585 ResourceLoaderModule
::TYPE_SCRIPTS
590 * Add only JS of one or more modules recognized by ResourceLoader. Module
591 * scripts added through this function will be loaded by ResourceLoader when
594 * @param string|array $modules Module name (string) or array of module names
596 public function addModuleScripts( $modules ) {
597 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
601 * Get the list of module CSS to include on this page
603 * @param bool $filter
604 * @param string|null $position
605 * @return array Array of module names
607 public function getModuleStyles( $filter = false, $position = null ) {
608 return $this->getModules( $filter, $position, 'mModuleStyles',
609 ResourceLoaderModule
::TYPE_STYLES
614 * Add only CSS of one or more modules recognized by ResourceLoader.
616 * Module styles added through this function will be added using standard link CSS
617 * tags, rather than as a combined Javascript and CSS package. Thus, they will
618 * load when JavaScript is disabled (unless CSS also happens to be disabled).
620 * @param string|array $modules Module name (string) or array of module names
622 public function addModuleStyles( $modules ) {
623 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
627 * @return null|string ResourceLoader target
629 public function getTarget() {
630 return $this->mTarget
;
634 * Sets ResourceLoader target for load.php links. If null, will be omitted
636 * @param string|null $target
638 public function setTarget( $target ) {
639 $this->mTarget
= $target;
643 * Get an array of head items
647 function getHeadItemsArray() {
648 return $this->mHeadItems
;
652 * Add or replace a head item to the output
654 * Whenever possible, use more specific options like ResourceLoader modules,
655 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
656 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
657 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
658 * This would be your very LAST fallback.
660 * @param string $name Item name
661 * @param string $value Raw HTML
663 public function addHeadItem( $name, $value ) {
664 $this->mHeadItems
[$name] = $value;
668 * Add one or more head items to the output
671 * @param string|string[] $value Raw HTML
673 public function addHeadItems( $values ) {
674 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
678 * Check if the header item $name is already set
680 * @param string $name Item name
683 public function hasHeadItem( $name ) {
684 return isset( $this->mHeadItems
[$name] );
688 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
691 public function setETag( $tag ) {
695 * Set whether the output should only contain the body of the article,
696 * without any skin, sidebar, etc.
697 * Used e.g. when calling with "action=render".
699 * @param bool $only Whether to output only the body of the article
701 public function setArticleBodyOnly( $only ) {
702 $this->mArticleBodyOnly
= $only;
706 * Return whether the output will contain only the body of the article
710 public function getArticleBodyOnly() {
711 return $this->mArticleBodyOnly
;
715 * Set an additional output property
718 * @param string $name
719 * @param mixed $value
721 public function setProperty( $name, $value ) {
722 $this->mProperties
[$name] = $value;
726 * Get an additional output property
729 * @param string $name
730 * @return mixed Property value or null if not found
732 public function getProperty( $name ) {
733 if ( isset( $this->mProperties
[$name] ) ) {
734 return $this->mProperties
[$name];
741 * checkLastModified tells the client to use the client-cached page if
742 * possible. If successful, the OutputPage is disabled so that
743 * any future call to OutputPage->output() have no effect.
745 * Side effect: sets mLastModified for Last-Modified header
747 * @param string $timestamp
749 * @return bool True if cache-ok headers was sent.
751 public function checkLastModified( $timestamp ) {
752 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
753 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
756 $config = $this->getConfig();
757 if ( !$config->get( 'CachePages' ) ) {
758 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
762 $timestamp = wfTimestamp( TS_MW
, $timestamp );
764 'page' => $timestamp,
765 'user' => $this->getUser()->getTouched(),
766 'epoch' => $config->get( 'CacheEpoch' )
768 if ( $config->get( 'UseSquid' ) ) {
769 // bug 44570: the core page itself may not change, but resources might
770 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
772 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
774 $maxModified = max( $modifiedTimes );
775 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
777 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
778 if ( $clientHeader === false ) {
779 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
783 # IE sends sizes after the date like this:
784 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
785 # this breaks strtotime().
786 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
788 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
789 $clientHeaderTime = strtotime( $clientHeader );
790 MediaWiki\restoreWarnings
();
791 if ( !$clientHeaderTime ) {
793 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
796 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
800 foreach ( $modifiedTimes as $name => $value ) {
801 if ( $info !== '' ) {
804 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
807 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
808 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
809 wfDebug( __METHOD__
. ": effective Last-Modified: " .
810 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
811 if ( $clientHeaderTime < $maxModified ) {
812 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
817 # Give a 304 Not Modified response code and disable body output
818 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
819 ini_set( 'zlib.output_compression', 0 );
820 $this->getRequest()->response()->statusHeader( 304 );
821 $this->sendCacheControl();
824 // Don't output a compressed blob when using ob_gzhandler;
825 // it's technically against HTTP spec and seems to confuse
826 // Firefox when the response gets split over two packets.
827 wfClearOutputBuffers();
833 * Override the last modified timestamp
835 * @param string $timestamp New timestamp, in a format readable by
838 public function setLastModified( $timestamp ) {
839 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
843 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
845 * @param string $policy The literal string to output as the contents of
846 * the meta tag. Will be parsed according to the spec and output in
850 public function setRobotPolicy( $policy ) {
851 $policy = Article
::formatRobotPolicy( $policy );
853 if ( isset( $policy['index'] ) ) {
854 $this->setIndexPolicy( $policy['index'] );
856 if ( isset( $policy['follow'] ) ) {
857 $this->setFollowPolicy( $policy['follow'] );
862 * Set the index policy for the page, but leave the follow policy un-
865 * @param string $policy Either 'index' or 'noindex'.
868 public function setIndexPolicy( $policy ) {
869 $policy = trim( $policy );
870 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
871 $this->mIndexPolicy
= $policy;
876 * Set the follow policy for the page, but leave the index policy un-
879 * @param string $policy Either 'follow' or 'nofollow'.
882 public function setFollowPolicy( $policy ) {
883 $policy = trim( $policy );
884 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
885 $this->mFollowPolicy
= $policy;
890 * Set the new value of the "action text", this will be added to the
891 * "HTML title", separated from it with " - ".
893 * @param string $text New value of the "action text"
895 public function setPageTitleActionText( $text ) {
896 $this->mPageTitleActionText
= $text;
900 * Get the value of the "action text"
904 public function getPageTitleActionText() {
905 return $this->mPageTitleActionText
;
909 * "HTML title" means the contents of "<title>".
910 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
912 * @param string|Message $name
914 public function setHTMLTitle( $name ) {
915 if ( $name instanceof Message
) {
916 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
918 $this->mHTMLtitle
= $name;
923 * Return the "HTML title", i.e. the content of the "<title>" tag.
927 public function getHTMLTitle() {
928 return $this->mHTMLtitle
;
932 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
936 public function setRedirectedFrom( $t ) {
937 $this->mRedirectedFrom
= $t;
941 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
942 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
943 * but not bad tags like \<script\>. This function automatically sets
944 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
945 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
946 * good tags like \<i\> will be dropped entirely.
948 * @param string|Message $name
950 public function setPageTitle( $name ) {
951 if ( $name instanceof Message
) {
952 $name = $name->setContext( $this->getContext() )->text();
955 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
956 # but leave "<i>foobar</i>" alone
957 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
958 $this->mPagetitle
= $nameWithTags;
960 # change "<i>foo&bar</i>" to "foo&bar"
962 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
963 ->inContentLanguage()
968 * Return the "page title", i.e. the content of the \<h1\> tag.
972 public function getPageTitle() {
973 return $this->mPagetitle
;
977 * Set the Title object to use
981 public function setTitle( Title
$t ) {
982 $this->getContext()->setTitle( $t );
986 * Replace the subtitle with $str
988 * @param string|Message $str New value of the subtitle. String should be safe HTML.
990 public function setSubtitle( $str ) {
991 $this->clearSubtitle();
992 $this->addSubtitle( $str );
996 * Add $str to the subtitle
998 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1000 public function addSubtitle( $str ) {
1001 if ( $str instanceof Message
) {
1002 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1004 $this->mSubtitle
[] = $str;
1009 * Build message object for a subtitle containing a backlink to a page
1011 * @param Title $title Title to link to
1012 * @param array $query Array of additional parameters to include in the link
1016 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1017 if ( $title->isRedirect() ) {
1018 $query['redirect'] = 'no';
1020 return wfMessage( 'backlinksubtitle' )
1021 ->rawParams( Linker
::link( $title, null, [], $query ) );
1025 * Add a subtitle containing a backlink to a page
1027 * @param Title $title Title to link to
1028 * @param array $query Array of additional parameters to include in the link
1030 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1031 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1035 * Clear the subtitles
1037 public function clearSubtitle() {
1038 $this->mSubtitle
= [];
1046 public function getSubtitle() {
1047 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1051 * Set the page as printable, i.e. it'll be displayed with all
1052 * print styles included
1054 public function setPrintable() {
1055 $this->mPrintable
= true;
1059 * Return whether the page is "printable"
1063 public function isPrintable() {
1064 return $this->mPrintable
;
1068 * Disable output completely, i.e. calling output() will have no effect
1070 public function disable() {
1071 $this->mDoNothing
= true;
1075 * Return whether the output will be completely disabled
1079 public function isDisabled() {
1080 return $this->mDoNothing
;
1084 * Show an "add new section" link?
1088 public function showNewSectionLink() {
1089 return $this->mNewSectionLink
;
1093 * Forcibly hide the new section link?
1097 public function forceHideNewSectionLink() {
1098 return $this->mHideNewSectionLink
;
1102 * Add or remove feed links in the page header
1103 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1104 * for the new version
1105 * @see addFeedLink()
1107 * @param bool $show True: add default feeds, false: remove all feeds
1109 public function setSyndicated( $show = true ) {
1111 $this->setFeedAppendQuery( false );
1113 $this->mFeedLinks
= [];
1118 * Add default feeds to the page header
1119 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1120 * for the new version
1121 * @see addFeedLink()
1123 * @param string $val Query to append to feed links or false to output
1126 public function setFeedAppendQuery( $val ) {
1127 $this->mFeedLinks
= [];
1129 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1130 $query = "feed=$type";
1131 if ( is_string( $val ) ) {
1132 $query .= '&' . $val;
1134 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1139 * Add a feed link to the page header
1141 * @param string $format Feed type, should be a key of $wgFeedClasses
1142 * @param string $href URL
1144 public function addFeedLink( $format, $href ) {
1145 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1146 $this->mFeedLinks
[$format] = $href;
1151 * Should we output feed links for this page?
1154 public function isSyndicated() {
1155 return count( $this->mFeedLinks
) > 0;
1159 * Return URLs for each supported syndication format for this page.
1160 * @return array Associating format keys with URLs
1162 public function getSyndicationLinks() {
1163 return $this->mFeedLinks
;
1167 * Will currently always return null
1171 public function getFeedAppendQuery() {
1172 return $this->mFeedLinksAppendQuery
;
1176 * Set whether the displayed content is related to the source of the
1177 * corresponding article on the wiki
1178 * Setting true will cause the change "article related" toggle to true
1182 public function setArticleFlag( $v ) {
1183 $this->mIsarticle
= $v;
1185 $this->mIsArticleRelated
= $v;
1190 * Return whether the content displayed page is related to the source of
1191 * the corresponding article on the wiki
1195 public function isArticle() {
1196 return $this->mIsarticle
;
1200 * Set whether this page is related an article on the wiki
1201 * Setting false will cause the change of "article flag" toggle to false
1205 public function setArticleRelated( $v ) {
1206 $this->mIsArticleRelated
= $v;
1208 $this->mIsarticle
= false;
1213 * Return whether this page is related an article on the wiki
1217 public function isArticleRelated() {
1218 return $this->mIsArticleRelated
;
1222 * Add new language links
1224 * @param array $newLinkArray Associative array mapping language code to the page
1227 public function addLanguageLinks( array $newLinkArray ) {
1228 $this->mLanguageLinks +
= $newLinkArray;
1232 * Reset the language links and add new language links
1234 * @param array $newLinkArray Associative array mapping language code to the page
1237 public function setLanguageLinks( array $newLinkArray ) {
1238 $this->mLanguageLinks
= $newLinkArray;
1242 * Get the list of language links
1244 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1246 public function getLanguageLinks() {
1247 return $this->mLanguageLinks
;
1251 * Add an array of categories, with names in the keys
1253 * @param array $categories Mapping category name => sort key
1255 public function addCategoryLinks( array $categories ) {
1258 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1262 # Add the links to a LinkBatch
1263 $arr = [ NS_CATEGORY
=> $categories ];
1264 $lb = new LinkBatch
;
1265 $lb->setArray( $arr );
1267 # Fetch existence plus the hiddencat property
1268 $dbr = wfGetDB( DB_SLAVE
);
1269 $fields = array_merge(
1270 LinkCache
::getSelectFields(),
1271 [ 'page_namespace', 'page_title', 'pp_value' ]
1274 $res = $dbr->select( [ 'page', 'page_props' ],
1276 $lb->constructSet( 'page', $dbr ),
1279 [ 'page_props' => [ 'LEFT JOIN', [
1280 'pp_propname' => 'hiddencat',
1285 # Add the results to the link cache
1286 $lb->addResultToCache( LinkCache
::singleton(), $res );
1288 # Set all the values to 'normal'.
1289 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1291 # Mark hidden categories
1292 foreach ( $res as $row ) {
1293 if ( isset( $row->pp_value
) ) {
1294 $categories[$row->page_title
] = 'hidden';
1298 # Add the remaining categories to the skin
1300 'OutputPageMakeCategoryLinks',
1301 [ &$this, $categories, &$this->mCategoryLinks
] )
1303 foreach ( $categories as $category => $type ) {
1304 // array keys will cast numeric category names to ints, so cast back to string
1305 $category = (string)$category;
1306 $origcategory = $category;
1307 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1311 $wgContLang->findVariantLink( $category, $title, true );
1312 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1315 $text = $wgContLang->convertHtml( $title->getText() );
1316 $this->mCategories
[] = $title->getText();
1317 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1323 * Reset the category links (but not the category list) and add $categories
1325 * @param array $categories Mapping category name => sort key
1327 public function setCategoryLinks( array $categories ) {
1328 $this->mCategoryLinks
= [];
1329 $this->addCategoryLinks( $categories );
1333 * Get the list of category links, in a 2-D array with the following format:
1334 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1335 * hidden categories) and $link a HTML fragment with a link to the category
1340 public function getCategoryLinks() {
1341 return $this->mCategoryLinks
;
1345 * Get the list of category names this page belongs to
1347 * @return array Array of strings
1349 public function getCategories() {
1350 return $this->mCategories
;
1354 * Add an array of indicators, with their identifiers as array
1355 * keys and HTML contents as values.
1357 * In case of duplicate keys, existing values are overwritten.
1359 * @param array $indicators
1362 public function setIndicators( array $indicators ) {
1363 $this->mIndicators
= $indicators +
$this->mIndicators
;
1364 // Keep ordered by key
1365 ksort( $this->mIndicators
);
1369 * Get the indicators associated with this page.
1371 * The array will be internally ordered by item keys.
1373 * @return array Keys: identifiers, values: HTML contents
1376 public function getIndicators() {
1377 return $this->mIndicators
;
1381 * Adds help link with an icon via page indicators.
1382 * Link target can be overridden by a local message containing a wikilink:
1383 * the message key is: lowercase action or special page name + '-helppage'.
1384 * @param string $to Target MediaWiki.org page title or encoded URL.
1385 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1388 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1389 $this->addModuleStyles( 'mediawiki.helplink' );
1390 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1392 if ( $overrideBaseUrl ) {
1395 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1396 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1399 $link = Html
::rawElement(
1403 'target' => '_blank',
1404 'class' => 'mw-helplink',
1409 $this->setIndicators( [ 'mw-helplink' => $link ] );
1413 * Do not allow scripts which can be modified by wiki users to load on this page;
1414 * only allow scripts bundled with, or generated by, the software.
1415 * Site-wide styles are controlled by a config setting, since they can be
1416 * used to create a custom skin/theme, but not user-specific ones.
1418 * @todo this should be given a more accurate name
1420 public function disallowUserJs() {
1421 $this->reduceAllowedModules(
1422 ResourceLoaderModule
::TYPE_SCRIPTS
,
1423 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1426 // Site-wide styles are controlled by a config setting, see bug 71621
1427 // for background on why. User styles are never allowed.
1428 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1429 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1431 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1433 $this->reduceAllowedModules(
1434 ResourceLoaderModule
::TYPE_STYLES
,
1440 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1441 * @see ResourceLoaderModule::$origin
1442 * @param string $type ResourceLoaderModule TYPE_ constant
1443 * @return int ResourceLoaderModule ORIGIN_ class constant
1445 public function getAllowedModules( $type ) {
1446 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1447 return min( array_values( $this->mAllowedModules
) );
1449 return isset( $this->mAllowedModules
[$type] )
1450 ?
$this->mAllowedModules
[$type]
1451 : ResourceLoaderModule
::ORIGIN_ALL
;
1456 * Limit the highest level of CSS/JS untrustworthiness allowed.
1458 * If passed the same or a higher level than the current level of untrustworthiness set, the
1459 * level will remain unchanged.
1461 * @param string $type
1462 * @param int $level ResourceLoaderModule class constant
1464 public function reduceAllowedModules( $type, $level ) {
1465 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1469 * Prepend $text to the body HTML
1471 * @param string $text HTML
1473 public function prependHTML( $text ) {
1474 $this->mBodytext
= $text . $this->mBodytext
;
1478 * Append $text to the body HTML
1480 * @param string $text HTML
1482 public function addHTML( $text ) {
1483 $this->mBodytext
.= $text;
1487 * Shortcut for adding an Html::element via addHTML.
1491 * @param string $element
1492 * @param array $attribs
1493 * @param string $contents
1495 public function addElement( $element, array $attribs = [], $contents = '' ) {
1496 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1500 * Clear the body HTML
1502 public function clearHTML() {
1503 $this->mBodytext
= '';
1509 * @return string HTML
1511 public function getHTML() {
1512 return $this->mBodytext
;
1516 * Get/set the ParserOptions object to use for wikitext parsing
1518 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1519 * current ParserOption object
1520 * @return ParserOptions
1522 public function parserOptions( $options = null ) {
1523 if ( $options !== null && !empty( $options->isBogus
) ) {
1524 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1525 // been changed somehow, and keep it if so.
1526 $anonPO = ParserOptions
::newFromAnon();
1527 $anonPO->setEditSection( false );
1528 if ( !$options->matches( $anonPO ) ) {
1529 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1530 $options->isBogus
= false;
1534 if ( !$this->mParserOptions
) {
1535 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1536 // $wgUser isn't unstubbable yet, so don't try to get a
1537 // ParserOptions for it. And don't cache this ParserOptions
1539 $po = ParserOptions
::newFromAnon();
1540 $po->setEditSection( false );
1541 $po->isBogus
= true;
1542 if ( $options !== null ) {
1543 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1548 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1549 $this->mParserOptions
->setEditSection( false );
1552 if ( $options !== null && !empty( $options->isBogus
) ) {
1553 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1555 return wfSetVar( $this->mParserOptions
, null, true );
1557 return wfSetVar( $this->mParserOptions
, $options );
1562 * Set the revision ID which will be seen by the wiki text parser
1563 * for things such as embedded {{REVISIONID}} variable use.
1565 * @param int|null $revid An positive integer, or null
1566 * @return mixed Previous value
1568 public function setRevisionId( $revid ) {
1569 $val = is_null( $revid ) ?
null : intval( $revid );
1570 return wfSetVar( $this->mRevisionId
, $val );
1574 * Get the displayed revision ID
1578 public function getRevisionId() {
1579 return $this->mRevisionId
;
1583 * Set the timestamp of the revision which will be displayed. This is used
1584 * to avoid a extra DB call in Skin::lastModified().
1586 * @param string|null $timestamp
1587 * @return mixed Previous value
1589 public function setRevisionTimestamp( $timestamp ) {
1590 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1594 * Get the timestamp of displayed revision.
1595 * This will be null if not filled by setRevisionTimestamp().
1597 * @return string|null
1599 public function getRevisionTimestamp() {
1600 return $this->mRevisionTimestamp
;
1604 * Set the displayed file version
1606 * @param File|bool $file
1607 * @return mixed Previous value
1609 public function setFileVersion( $file ) {
1611 if ( $file instanceof File
&& $file->exists() ) {
1612 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1614 return wfSetVar( $this->mFileVersion
, $val, true );
1618 * Get the displayed file version
1620 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1622 public function getFileVersion() {
1623 return $this->mFileVersion
;
1627 * Get the templates used on this page
1629 * @return array (namespace => dbKey => revId)
1632 public function getTemplateIds() {
1633 return $this->mTemplateIds
;
1637 * Get the files used on this page
1639 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1642 public function getFileSearchOptions() {
1643 return $this->mImageTimeKeys
;
1647 * Convert wikitext to HTML and add it to the buffer
1648 * Default assumes that the current page title will be used.
1650 * @param string $text
1651 * @param bool $linestart Is this the start of a line?
1652 * @param bool $interface Is this text in the user interface language?
1653 * @throws MWException
1655 public function addWikiText( $text, $linestart = true, $interface = true ) {
1656 $title = $this->getTitle(); // Work around E_STRICT
1658 throw new MWException( 'Title is null' );
1660 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1664 * Add wikitext with a custom Title object
1666 * @param string $text Wikitext
1667 * @param Title $title
1668 * @param bool $linestart Is this the start of a line?
1670 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1671 $this->addWikiTextTitle( $text, $title, $linestart );
1675 * Add wikitext with a custom Title object and tidy enabled.
1677 * @param string $text Wikitext
1678 * @param Title $title
1679 * @param bool $linestart Is this the start of a line?
1681 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1682 $this->addWikiTextTitle( $text, $title, $linestart, true );
1686 * Add wikitext with tidy enabled
1688 * @param string $text Wikitext
1689 * @param bool $linestart Is this the start of a line?
1691 public function addWikiTextTidy( $text, $linestart = true ) {
1692 $title = $this->getTitle();
1693 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1697 * Add wikitext with a custom Title object
1699 * @param string $text Wikitext
1700 * @param Title $title
1701 * @param bool $linestart Is this the start of a line?
1702 * @param bool $tidy Whether to use tidy
1703 * @param bool $interface Whether it is an interface message
1704 * (for example disables conversion)
1706 public function addWikiTextTitle( $text, Title
$title, $linestart,
1707 $tidy = false, $interface = false
1711 $popts = $this->parserOptions();
1712 $oldTidy = $popts->setTidy( $tidy );
1713 $popts->setInterfaceMessage( (bool)$interface );
1715 $parserOutput = $wgParser->getFreshParser()->parse(
1716 $text, $title, $popts,
1717 $linestart, true, $this->mRevisionId
1720 $popts->setTidy( $oldTidy );
1722 $this->addParserOutput( $parserOutput );
1727 * Add a ParserOutput object, but without Html.
1729 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1730 * @param ParserOutput $parserOutput
1732 public function addParserOutputNoText( $parserOutput ) {
1733 wfDeprecated( __METHOD__
, '1.24' );
1734 $this->addParserOutputMetadata( $parserOutput );
1738 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1739 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1743 * @param ParserOutput $parserOutput
1745 public function addParserOutputMetadata( $parserOutput ) {
1746 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1747 $this->addCategoryLinks( $parserOutput->getCategories() );
1748 $this->setIndicators( $parserOutput->getIndicators() );
1749 $this->mNewSectionLink
= $parserOutput->getNewSection();
1750 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1752 if ( !$parserOutput->isCacheable() ) {
1753 $this->enableClientCache( false );
1755 $this->mNoGallery
= $parserOutput->getNoGallery();
1756 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1757 $this->addModules( $parserOutput->getModules() );
1758 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1759 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1760 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1761 $this->mPreventClickjacking
= $this->mPreventClickjacking
1762 ||
$parserOutput->preventClickjacking();
1764 // Template versioning...
1765 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1766 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1767 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1769 $this->mTemplateIds
[$ns] = $dbks;
1772 // File versioning...
1773 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1774 $this->mImageTimeKeys
[$dbk] = $data;
1777 // Hooks registered in the object
1778 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1779 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1780 list( $hookName, $data ) = $hookInfo;
1781 if ( isset( $parserOutputHooks[$hookName] ) ) {
1782 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1786 // Enable OOUI if requested via ParserOutput
1787 if ( $parserOutput->getEnableOOUI() ) {
1788 $this->enableOOUI();
1791 // Include profiling data
1792 $this->setLimitReportData( $parserOutput->getLimitReportData() );
1794 // Link flags are ignored for now, but may in the future be
1795 // used to mark individual language links.
1797 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1798 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1802 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1803 * ParserOutput object, without any other metadata.
1806 * @param ParserOutput $parserOutput
1808 public function addParserOutputContent( $parserOutput ) {
1809 $this->addParserOutputText( $parserOutput );
1811 $this->addModules( $parserOutput->getModules() );
1812 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1813 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1815 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1819 * Add the HTML associated with a ParserOutput object, without any metadata.
1822 * @param ParserOutput $parserOutput
1824 public function addParserOutputText( $parserOutput ) {
1825 $text = $parserOutput->getText();
1826 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1827 $this->addHTML( $text );
1831 * Add everything from a ParserOutput object.
1833 * @param ParserOutput $parserOutput
1835 function addParserOutput( $parserOutput ) {
1836 $this->addParserOutputMetadata( $parserOutput );
1837 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1839 // Touch section edit links only if not previously disabled
1840 if ( $parserOutput->getEditSectionTokens() ) {
1841 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1844 $this->addParserOutputText( $parserOutput );
1848 * Add the output of a QuickTemplate to the output buffer
1850 * @param QuickTemplate $template
1852 public function addTemplate( &$template ) {
1853 $this->addHTML( $template->getHTML() );
1857 * Parse wikitext and return the HTML.
1859 * @param string $text
1860 * @param bool $linestart Is this the start of a line?
1861 * @param bool $interface Use interface language ($wgLang instead of
1862 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1863 * This also disables LanguageConverter.
1864 * @param Language $language Target language object, will override $interface
1865 * @throws MWException
1866 * @return string HTML
1868 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1871 if ( is_null( $this->getTitle() ) ) {
1872 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1875 $popts = $this->parserOptions();
1877 $popts->setInterfaceMessage( true );
1879 if ( $language !== null ) {
1880 $oldLang = $popts->setTargetLanguage( $language );
1883 $parserOutput = $wgParser->getFreshParser()->parse(
1884 $text, $this->getTitle(), $popts,
1885 $linestart, true, $this->mRevisionId
1889 $popts->setInterfaceMessage( false );
1891 if ( $language !== null ) {
1892 $popts->setTargetLanguage( $oldLang );
1895 return $parserOutput->getText();
1899 * Parse wikitext, strip paragraphs, and return the HTML.
1901 * @param string $text
1902 * @param bool $linestart Is this the start of a line?
1903 * @param bool $interface Use interface language ($wgLang instead of
1904 * $wgContLang) while parsing language sensitive magic
1905 * words like GRAMMAR and PLURAL
1906 * @return string HTML
1908 public function parseInline( $text, $linestart = true, $interface = false ) {
1909 $parsed = $this->parse( $text, $linestart, $interface );
1910 return Parser
::stripOuterParagraph( $parsed );
1915 * @deprecated since 1.27 Use setCdnMaxage() instead
1917 public function setSquidMaxage( $maxage ) {
1918 $this->setCdnMaxage( $maxage );
1922 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1924 * @param int $maxage Maximum cache time on the CDN, in seconds.
1926 public function setCdnMaxage( $maxage ) {
1927 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1931 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1933 * @param int $maxage Maximum cache time on the CDN, in seconds
1936 public function lowerCdnMaxage( $maxage ) {
1937 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1938 $this->setCdnMaxage( $this->mCdnMaxage
);
1942 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1944 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1945 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1946 * TTL is 90% of the age of the object, subject to the min and max.
1948 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1949 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1950 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1951 * @return integer TTL in seconds
1954 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1955 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1956 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1958 if ( $mtime === null ||
$mtime === false ) {
1959 return $minTTL; // entity does not exist
1962 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1963 $adaptiveTTL = max( .9 * $age, $minTTL );
1964 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1966 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1968 return $adaptiveTTL;
1972 * Use enableClientCache(false) to force it to send nocache headers
1974 * @param bool $state
1978 public function enableClientCache( $state ) {
1979 return wfSetVar( $this->mEnableClientCache
, $state );
1983 * Get the list of cookies that will influence on the cache
1987 function getCacheVaryCookies() {
1989 if ( $cookies === null ) {
1990 $config = $this->getConfig();
1991 $cookies = array_merge(
1992 SessionManager
::singleton()->getVaryCookies(),
1996 $config->get( 'CacheVaryCookies' )
1998 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2004 * Check if the request has a cache-varying cookie header
2005 * If it does, it's very important that we don't allow public caching
2009 function haveCacheVaryCookies() {
2010 $request = $this->getRequest();
2011 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2012 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2013 wfDebug( __METHOD__
. ": found $cookieName\n" );
2017 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2022 * Add an HTTP header that will influence on the cache
2024 * @param string $header Header name
2025 * @param string[]|null $option Options for the Key header. See
2026 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2027 * for the list of valid options.
2029 public function addVaryHeader( $header, array $option = null ) {
2030 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2031 $this->mVaryHeader
[$header] = [];
2033 if ( !is_array( $option ) ) {
2036 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2040 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2041 * such as Accept-Encoding or Cookie
2045 public function getVaryHeader() {
2046 // If we vary on cookies, let's make sure it's always included here too.
2047 if ( $this->getCacheVaryCookies() ) {
2048 $this->addVaryHeader( 'Cookie' );
2051 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2052 $this->addVaryHeader( $header, $options );
2054 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2058 * Get a complete Key header
2062 public function getKeyHeader() {
2063 $cvCookies = $this->getCacheVaryCookies();
2065 $cookiesOption = [];
2066 foreach ( $cvCookies as $cookieName ) {
2067 $cookiesOption[] = 'param=' . $cookieName;
2069 $this->addVaryHeader( 'Cookie', $cookiesOption );
2071 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2072 $this->addVaryHeader( $header, $options );
2076 foreach ( $this->mVaryHeader
as $header => $option ) {
2077 $newheader = $header;
2078 if ( is_array( $option ) && count( $option ) > 0 ) {
2079 $newheader .= ';' . implode( ';', $option );
2081 $headers[] = $newheader;
2083 $key = 'Key: ' . implode( ',', $headers );
2089 * T23672: Add Accept-Language to Vary and Key headers
2090 * if there's no 'variant' parameter existed in GET.
2093 * /w/index.php?title=Main_page should always be served; but
2094 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2096 function addAcceptLanguage() {
2097 $title = $this->getTitle();
2098 if ( !$title instanceof Title
) {
2102 $lang = $title->getPageLanguage();
2103 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2104 $variants = $lang->getVariants();
2106 foreach ( $variants as $variant ) {
2107 if ( $variant === $lang->getCode() ) {
2110 $aloption[] = 'substr=' . $variant;
2112 // IE and some other browsers use BCP 47 standards in
2113 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2114 // We should handle these too.
2115 $variantBCP47 = wfBCP47( $variant );
2116 if ( $variantBCP47 !== $variant ) {
2117 $aloption[] = 'substr=' . $variantBCP47;
2121 $this->addVaryHeader( 'Accept-Language', $aloption );
2126 * Set a flag which will cause an X-Frame-Options header appropriate for
2127 * edit pages to be sent. The header value is controlled by
2128 * $wgEditPageFrameOptions.
2130 * This is the default for special pages. If you display a CSRF-protected
2131 * form on an ordinary view page, then you need to call this function.
2133 * @param bool $enable
2135 public function preventClickjacking( $enable = true ) {
2136 $this->mPreventClickjacking
= $enable;
2140 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2141 * This can be called from pages which do not contain any CSRF-protected
2144 public function allowClickjacking() {
2145 $this->mPreventClickjacking
= false;
2149 * Get the prevent-clickjacking flag
2154 public function getPreventClickjacking() {
2155 return $this->mPreventClickjacking
;
2159 * Get the X-Frame-Options header value (without the name part), or false
2160 * if there isn't one. This is used by Skin to determine whether to enable
2161 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2165 public function getFrameOptions() {
2166 $config = $this->getConfig();
2167 if ( $config->get( 'BreakFrames' ) ) {
2169 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2170 return $config->get( 'EditPageFrameOptions' );
2176 * Send cache control HTTP headers
2178 public function sendCacheControl() {
2179 $response = $this->getRequest()->response();
2180 $config = $this->getConfig();
2182 $this->addVaryHeader( 'Cookie' );
2183 $this->addAcceptLanguage();
2185 # don't serve compressed data to clients who can't handle it
2186 # maintain different caches for logged-in users and non-logged in ones
2187 $response->header( $this->getVaryHeader() );
2189 if ( $config->get( 'UseKeyHeader' ) ) {
2190 $response->header( $this->getKeyHeader() );
2193 if ( $this->mEnableClientCache
) {
2195 $config->get( 'UseSquid' ) &&
2196 !$response->hasCookies() &&
2197 !SessionManager
::getGlobalSession()->isPersistent() &&
2198 !$this->isPrintable() &&
2199 $this->mCdnMaxage
!= 0 &&
2200 !$this->haveCacheVaryCookies()
2202 if ( $config->get( 'UseESI' ) ) {
2203 # We'll purge the proxy cache explicitly, but require end user agents
2204 # to revalidate against the proxy on each visit.
2205 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2206 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2207 # start with a shorter timeout for initial testing
2208 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2209 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2210 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2211 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2213 # We'll purge the proxy cache for anons explicitly, but require end user agents
2214 # to revalidate against the proxy on each visit.
2215 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2216 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2217 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2218 # start with a shorter timeout for initial testing
2219 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2220 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2221 . ', must-revalidate, max-age=0' );
2224 # We do want clients to cache if they can, but they *must* check for updates
2225 # on revisiting the page.
2226 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2227 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2228 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2230 if ( $this->mLastModified
) {
2231 $response->header( "Last-Modified: {$this->mLastModified}" );
2234 wfDebug( __METHOD__
. ": no caching **", 'private' );
2236 # In general, the absence of a last modified header should be enough to prevent
2237 # the client from using its cache. We send a few other things just to make sure.
2238 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2239 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2240 $response->header( 'Pragma: no-cache' );
2245 * Finally, all the text has been munged and accumulated into
2246 * the object, let's actually output it:
2248 public function output() {
2249 if ( $this->mDoNothing
) {
2253 $response = $this->getRequest()->response();
2254 $config = $this->getConfig();
2256 if ( $this->mRedirect
!= '' ) {
2257 # Standards require redirect URLs to be absolute
2258 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2260 $redirect = $this->mRedirect
;
2261 $code = $this->mRedirectCode
;
2263 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2264 if ( $code == '301' ||
$code == '303' ) {
2265 if ( !$config->get( 'DebugRedirects' ) ) {
2266 $response->statusHeader( $code );
2268 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2270 if ( $config->get( 'VaryOnXFP' ) ) {
2271 $this->addVaryHeader( 'X-Forwarded-Proto' );
2273 $this->sendCacheControl();
2275 $response->header( "Content-Type: text/html; charset=utf-8" );
2276 if ( $config->get( 'DebugRedirects' ) ) {
2277 $url = htmlspecialchars( $redirect );
2278 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2279 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2280 print "</body>\n</html>\n";
2282 $response->header( 'Location: ' . $redirect );
2287 } elseif ( $this->mStatusCode
) {
2288 $response->statusHeader( $this->mStatusCode
);
2291 # Buffer output; final headers may depend on later processing
2294 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2295 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2297 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2298 // jQuery etc. can work correctly.
2299 $response->header( 'X-UA-Compatible: IE=Edge' );
2301 // Prevent framing, if requested
2302 $frameOptions = $this->getFrameOptions();
2303 if ( $frameOptions ) {
2304 $response->header( "X-Frame-Options: $frameOptions" );
2307 if ( $this->mArticleBodyOnly
) {
2308 echo $this->mBodytext
;
2310 $sk = $this->getSkin();
2311 // add skin specific modules
2312 $modules = $sk->getDefaultModules();
2314 // Enforce various default modules for all pages and all skins
2316 // Keep this list as small as possible
2318 'mediawiki.page.startup',
2322 // Support for high-density display images if enabled
2323 if ( $config->get( 'ResponsiveImages' ) ) {
2324 $coreModules[] = 'mediawiki.hidpi';
2327 $this->addModules( $coreModules );
2328 foreach ( $modules as $group ) {
2329 $this->addModules( $group );
2331 MWDebug
::addModules( $this );
2333 // Hook that allows last minute changes to the output page, e.g.
2334 // adding of CSS or Javascript by extensions.
2335 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2336 $this->getSkin()->setupSkinUserCss( $this );
2340 } catch ( Exception
$e ) {
2341 ob_end_clean(); // bug T129657
2347 // This hook allows last minute changes to final overall output by modifying output buffer
2348 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2349 } catch ( Exception
$e ) {
2350 ob_end_clean(); // bug T129657
2354 $this->sendCacheControl();
2361 * Prepare this object to display an error page; disable caching and
2362 * indexing, clear the current text and redirect, set the page's title
2363 * and optionally an custom HTML title (content of the "<title>" tag).
2365 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2366 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2367 * optional, if not passed the "<title>" attribute will be
2368 * based on $pageTitle
2370 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2371 $this->setPageTitle( $pageTitle );
2372 if ( $htmlTitle !== false ) {
2373 $this->setHTMLTitle( $htmlTitle );
2375 $this->setRobotPolicy( 'noindex,nofollow' );
2376 $this->setArticleRelated( false );
2377 $this->enableClientCache( false );
2378 $this->mRedirect
= '';
2379 $this->clearSubtitle();
2384 * Output a standard error page
2386 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2387 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2388 * showErrorPage( 'titlemsg', $messageObject );
2389 * showErrorPage( $titleMessageObject, $messageObject );
2391 * @param string|Message $title Message key (string) for page title, or a Message object
2392 * @param string|Message $msg Message key (string) for page text, or a Message object
2393 * @param array $params Message parameters; ignored if $msg is a Message object
2395 public function showErrorPage( $title, $msg, $params = [] ) {
2396 if ( !$title instanceof Message
) {
2397 $title = $this->msg( $title );
2400 $this->prepareErrorPage( $title );
2402 if ( $msg instanceof Message
) {
2403 if ( $params !== [] ) {
2404 trigger_error( 'Argument ignored: $params. The message parameters argument '
2405 . 'is discarded when the $msg argument is a Message object instead of '
2406 . 'a string.', E_USER_NOTICE
);
2408 $this->addHTML( $msg->parseAsBlock() );
2410 $this->addWikiMsgArray( $msg, $params );
2413 $this->returnToMain();
2417 * Output a standard permission error page
2419 * @param array $errors Error message keys
2420 * @param string $action Action that was denied or null if unknown
2422 public function showPermissionsErrorPage( array $errors, $action = null ) {
2423 // For some action (read, edit, create and upload), display a "login to do this action"
2424 // error if all of the following conditions are met:
2425 // 1. the user is not logged in
2426 // 2. the only error is insufficient permissions (i.e. no block or something else)
2427 // 3. the error can be avoided simply by logging in
2428 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2429 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2430 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2431 && ( User
::groupHasPermission( 'user', $action )
2432 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2434 $displayReturnto = null;
2436 # Due to bug 32276, if a user does not have read permissions,
2437 # $this->getTitle() will just give Special:Badtitle, which is
2438 # not especially useful as a returnto parameter. Use the title
2439 # from the request instead, if there was one.
2440 $request = $this->getRequest();
2441 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2442 if ( $action == 'edit' ) {
2443 $msg = 'whitelistedittext';
2444 $displayReturnto = $returnto;
2445 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2446 $msg = 'nocreatetext';
2447 } elseif ( $action == 'upload' ) {
2448 $msg = 'uploadnologintext';
2450 $msg = 'loginreqpagetext';
2451 $displayReturnto = Title
::newMainPage();
2457 $query['returnto'] = $returnto->getPrefixedText();
2459 if ( !$request->wasPosted() ) {
2460 $returntoquery = $request->getValues();
2461 unset( $returntoquery['title'] );
2462 unset( $returntoquery['returnto'] );
2463 unset( $returntoquery['returntoquery'] );
2464 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2467 $loginLink = Linker
::linkKnown(
2468 SpecialPage
::getTitleFor( 'Userlogin' ),
2469 $this->msg( 'loginreqlink' )->escaped(),
2474 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2475 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2477 # Don't return to a page the user can't read otherwise
2478 # we'll end up in a pointless loop
2479 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2480 $this->returnToMain( null, $displayReturnto );
2483 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2484 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2489 * Display an error page indicating that a given version of MediaWiki is
2490 * required to use it
2492 * @param mixed $version The version of MediaWiki needed to use the page
2494 public function versionRequired( $version ) {
2495 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2497 $this->addWikiMsg( 'versionrequiredtext', $version );
2498 $this->returnToMain();
2502 * Format a list of error messages
2504 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2505 * @param string $action Action that was denied or null if unknown
2506 * @return string The wikitext error-messages, formatted into a list.
2508 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2509 if ( $action == null ) {
2510 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2512 $action_desc = $this->msg( "action-$action" )->plain();
2514 'permissionserrorstext-withaction',
2517 )->plain() . "\n\n";
2520 if ( count( $errors ) > 1 ) {
2521 $text .= '<ul class="permissions-errors">' . "\n";
2523 foreach ( $errors as $error ) {
2525 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2530 $text .= "<div class=\"permissions-errors\">\n" .
2531 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2539 * Display a page stating that the Wiki is in read-only mode.
2540 * Should only be called after wfReadOnly() has returned true.
2542 * Historically, this function was used to show the source of the page that the user
2543 * was trying to edit and _also_ permissions error messages. The relevant code was
2544 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2546 * @deprecated since 1.25; throw the exception directly
2547 * @throws ReadOnlyError
2549 public function readOnlyPage() {
2550 if ( func_num_args() > 0 ) {
2551 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2554 throw new ReadOnlyError
;
2558 * Turn off regular page output and return an error response
2559 * for when rate limiting has triggered.
2561 * @deprecated since 1.25; throw the exception directly
2563 public function rateLimited() {
2564 wfDeprecated( __METHOD__
, '1.25' );
2565 throw new ThrottledError
;
2569 * Show a warning about slave lag
2571 * If the lag is higher than $wgSlaveLagCritical seconds,
2572 * then the warning is a bit more obvious. If the lag is
2573 * lower than $wgSlaveLagWarning, then no warning is shown.
2575 * @param int $lag Slave lag
2577 public function showLagWarning( $lag ) {
2578 $config = $this->getConfig();
2579 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2580 $message = $lag < $config->get( 'SlaveLagCritical' )
2583 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2584 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2588 public function showFatalError( $message ) {
2589 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2591 $this->addHTML( $message );
2594 public function showUnexpectedValueError( $name, $val ) {
2595 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2598 public function showFileCopyError( $old, $new ) {
2599 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2602 public function showFileRenameError( $old, $new ) {
2603 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2606 public function showFileDeleteError( $name ) {
2607 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2610 public function showFileNotFoundError( $name ) {
2611 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2615 * Add a "return to" link pointing to a specified title
2617 * @param Title $title Title to link
2618 * @param array $query Query string parameters
2619 * @param string $text Text of the link (input is not escaped)
2620 * @param array $options Options array to pass to Linker
2622 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2623 $link = $this->msg( 'returnto' )->rawParams(
2624 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2625 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2629 * Add a "return to" link pointing to a specified title,
2630 * or the title indicated in the request, or else the main page
2632 * @param mixed $unused
2633 * @param Title|string $returnto Title or String to return to
2634 * @param string $returntoquery Query string for the return to link
2636 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2637 if ( $returnto == null ) {
2638 $returnto = $this->getRequest()->getText( 'returnto' );
2641 if ( $returntoquery == null ) {
2642 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2645 if ( $returnto === '' ) {
2646 $returnto = Title
::newMainPage();
2649 if ( is_object( $returnto ) ) {
2650 $titleObj = $returnto;
2652 $titleObj = Title
::newFromText( $returnto );
2654 if ( !is_object( $titleObj ) ) {
2655 $titleObj = Title
::newMainPage();
2658 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2661 private function getRlClientContext() {
2662 if ( !$this->rlClientContext
) {
2663 $query = ResourceLoader
::makeLoaderQuery(
2664 [], // modules; not relevant
2665 $this->getLanguage()->getCode(),
2666 $this->getSkin()->getSkinName(),
2667 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2668 null, // version; not relevant
2669 ResourceLoader
::inDebugMode(),
2670 null, // only; not relevant
2671 $this->isPrintable(),
2672 $this->getRequest()->getBool( 'handheld' )
2674 $this->rlClientContext
= new ResourceLoaderContext(
2675 $this->getResourceLoader(),
2676 new FauxRequest( $query )
2679 return $this->rlClientContext
;
2683 * Call this to freeze the module queue and JS config and create a formatter.
2685 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2686 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2687 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2688 * the module filters retroactively. Skins and extension hooks may also add modules until very
2689 * late in the request lifecycle.
2691 * @return ResourceLoaderClientHtml
2693 public function getRlClient() {
2694 if ( !$this->rlClient
) {
2695 $context = $this->getRlClientContext();
2696 $rl = $this->getResourceLoader();
2697 $this->addModules( [
2701 $this->addModuleStyles( [
2708 // Prepare exempt modules for buildExemptModules()
2709 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2711 $moduleStyles = array_filter( $this->getModuleStyles( /*filter*/ true ),
2712 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2713 $module = $rl->getModule( $name );
2715 $group = $module->getGroup();
2716 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2717 $exemptStates[$name] = 'ready';
2718 // Special case in buildExemptModules()
2721 if ( $name === 'site.styles' ) {
2722 // HACK: Technically, 'site.styles' isn't in a separate request group.
2723 // But, in order to ensure its styles are in the right position,
2724 // pretend it's in a group called 'site'.
2727 if ( isset( $exemptGroups[$group] ) ) {
2728 $exemptStates[$name] = 'ready';
2729 if ( !$module->isKnownEmpty( $context ) ) {
2730 // E.g. Don't output empty <styles>
2731 $exemptGroups[$group][] = $name;
2739 $this->rlExemptStyleModules
= $exemptGroups;
2741 // Manually handled by getBottomScripts()
2742 $userModule = $rl->getModule( 'user' );
2743 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2746 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2748 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2749 $rlClient->setConfig( $this->getJSVars() );
2750 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2751 $rlClient->setModuleStyles( $moduleStyles );
2752 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2753 $rlClient->setExemptStates( $exemptStates );
2754 $this->rlClient
= $rlClient;
2756 return $this->rlClient
;
2760 * @param Skin $sk The given Skin
2761 * @param bool $includeStyle Unused
2762 * @return string The doctype, opening "<html>", and head element.
2764 public function headElement( Skin
$sk, $includeStyle = true ) {
2767 $userdir = $this->getLanguage()->getDir();
2768 $sitedir = $wgContLang->getDir();
2771 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2772 $this->getRlClient()->getDocumentAttributes(),
2773 $sk->getHtmlElementAttributes()
2775 $pieces[] = Html
::openElement( 'head' );
2777 if ( $this->getHTMLTitle() == '' ) {
2778 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2781 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2782 // Add <meta charset="UTF-8">
2783 // This should be before <title> since it defines the charset used by
2784 // text including the text inside <title>.
2785 // The spec recommends defining XHTML5's charset using the XML declaration
2787 // Our XML declaration is output by Html::htmlHeader.
2788 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2789 // http://www.whatwg.org/html/semantics.html#charset
2790 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2793 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2794 $pieces[] = $this->getRlClient()->getHeadHtml();
2795 $pieces[] = $this->buildExemptModules();
2796 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2797 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2798 $pieces[] = Html
::closeElement( 'head' );
2801 $bodyClasses[] = 'mediawiki';
2803 # Classes for LTR/RTL directionality support
2804 $bodyClasses[] = $userdir;
2805 $bodyClasses[] = "sitedir-$sitedir";
2807 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2808 # A <body> class is probably not the best way to do this . . .
2809 $bodyClasses[] = 'capitalize-all-nouns';
2812 // Parser feature migration class
2813 // The idea is that this will eventually be removed, after the wikitext
2814 // which requires it is cleaned up.
2815 $bodyClasses[] = 'mw-hide-empty-elt';
2817 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2818 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2820 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2823 // While the implode() is not strictly needed, it's used for backwards compatibility
2824 // (this used to be built as a string and hooks likely still expect that).
2825 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2827 // Allow skins and extensions to add body attributes they need
2828 $sk->addToBodyAttributes( $this, $bodyAttrs );
2829 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2831 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2833 return self
::combineWrappedStrings( $pieces );
2837 * Get a ResourceLoader object associated with this OutputPage
2839 * @return ResourceLoader
2841 public function getResourceLoader() {
2842 if ( is_null( $this->mResourceLoader
) ) {
2843 $this->mResourceLoader
= new ResourceLoader(
2845 LoggerFactory
::getInstance( 'resourceloader' )
2848 return $this->mResourceLoader
;
2852 * Explicily load or embed modules on a page.
2854 * @param array|string $modules One or more module names
2855 * @param string $only ResourceLoaderModule TYPE_ class constant
2856 * @param array $extraQuery [optional] Array with extra query parameters for the request
2857 * @return string|WrappedStringList HTML
2859 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2860 // Apply 'target' and 'origin' filters
2861 $modules = $this->filterModules( (array)$modules, null, $only );
2863 return ResourceLoaderClientHtml
::makeLoad(
2864 $this->getRlClientContext(),
2872 * Combine WrappedString chunks and filter out empty ones
2874 * @param array $chunks
2875 * @return string|WrappedStringList HTML
2877 protected static function combineWrappedStrings( array $chunks ) {
2878 // Filter out empty values
2879 $chunks = array_filter( $chunks, 'strlen' );
2880 return WrappedString
::join( "\n", $chunks );
2883 private function isUserJsPreview() {
2884 return $this->getConfig()->get( 'AllowUserJs' )
2885 && $this->getTitle()
2886 && $this->getTitle()->isJsSubpage()
2887 && $this->userCanPreview();
2890 private function isUserCssPreview() {
2891 return $this->getConfig()->get( 'AllowUserCss' )
2892 && $this->getTitle()
2893 && $this->getTitle()->isCssSubpage()
2894 && $this->userCanPreview();
2898 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2899 * legacy scripts ($this->mScripts), and user JS.
2901 * @return string|WrappedStringList HTML
2903 public function getBottomScripts() {
2905 $chunks[] = $this->getRlClient()->getBodyHtml();
2907 // Legacy non-ResourceLoader scripts
2908 $chunks[] = $this->mScripts
;
2910 // Exempt 'user' module
2911 // - May need excludepages for live preview. (T28283)
2912 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2913 // ensures execution is scheduled after the "site" module.
2914 // - Don't load if module state is already resolved as "ready".
2915 if ( $this->rlUserModuleState
=== 'loading' ) {
2916 if ( $this->isUserJsPreview() ) {
2917 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2918 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2920 $chunks[] = ResourceLoader
::makeInlineScript(
2921 Xml
::encodeJsCall( 'mw.loader.using', [
2925 . Xml
::encodeJsCall( '$.globalEval', [
2926 $this->getRequest()->getText( 'wpTextbox1' )
2932 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2933 // asynchronously and may arrive *after* the inline script here. So the previewed code
2934 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2935 // Similarly, when previewing ./common.js and the user module does arrive first,
2936 // it will arrive without common.js and the inline script runs after.
2937 // Thus running common after the excluded subpage.
2940 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
2944 $chunks[] = ResourceLoader
::makeInlineScript(
2945 ResourceLoader
::makeConfigSetScript(
2946 [ 'wgPageParseReport' => $this->limitReportData
],
2951 return self
::combineWrappedStrings( $chunks );
2955 * Get the javascript config vars to include on this page
2957 * @return array Array of javascript config vars
2960 public function getJsConfigVars() {
2961 return $this->mJsConfigVars
;
2965 * Add one or more variables to be set in mw.config in JavaScript
2967 * @param string|array $keys Key or array of key/value pairs
2968 * @param mixed $value [optional] Value of the configuration variable
2970 public function addJsConfigVars( $keys, $value = null ) {
2971 if ( is_array( $keys ) ) {
2972 foreach ( $keys as $key => $value ) {
2973 $this->mJsConfigVars
[$key] = $value;
2978 $this->mJsConfigVars
[$keys] = $value;
2982 * Get an array containing the variables to be set in mw.config in JavaScript.
2984 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2985 * - in other words, page-independent/site-wide variables (without state).
2986 * You will only be adding bloat to the html page and causing page caches to
2987 * have to be purged on configuration changes.
2990 public function getJSVars() {
2995 $canonicalSpecialPageName = false; # bug 21115
2997 $title = $this->getTitle();
2998 $ns = $title->getNamespace();
2999 $canonicalNamespace = MWNamespace
::exists( $ns )
3000 ? MWNamespace
::getCanonicalName( $ns )
3001 : $title->getNsText();
3003 $sk = $this->getSkin();
3004 // Get the relevant title so that AJAX features can use the correct page name
3005 // when making API requests from certain special pages (bug 34972).
3006 $relevantTitle = $sk->getRelevantTitle();
3007 $relevantUser = $sk->getRelevantUser();
3009 if ( $ns == NS_SPECIAL
) {
3010 list( $canonicalSpecialPageName, /*...*/ ) =
3011 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3012 } elseif ( $this->canUseWikiPage() ) {
3013 $wikiPage = $this->getWikiPage();
3014 $curRevisionId = $wikiPage->getLatest();
3015 $articleId = $wikiPage->getId();
3018 $lang = $title->getPageViewLanguage();
3020 // Pre-process information
3021 $separatorTransTable = $lang->separatorTransformTable();
3022 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3023 $compactSeparatorTransTable = [
3024 implode( "\t", array_keys( $separatorTransTable ) ),
3025 implode( "\t", $separatorTransTable ),
3027 $digitTransTable = $lang->digitTransformTable();
3028 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3029 $compactDigitTransTable = [
3030 implode( "\t", array_keys( $digitTransTable ) ),
3031 implode( "\t", $digitTransTable ),
3034 $user = $this->getUser();
3037 'wgCanonicalNamespace' => $canonicalNamespace,
3038 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3039 'wgNamespaceNumber' => $title->getNamespace(),
3040 'wgPageName' => $title->getPrefixedDBkey(),
3041 'wgTitle' => $title->getText(),
3042 'wgCurRevisionId' => $curRevisionId,
3043 'wgRevisionId' => (int)$this->getRevisionId(),
3044 'wgArticleId' => $articleId,
3045 'wgIsArticle' => $this->isArticle(),
3046 'wgIsRedirect' => $title->isRedirect(),
3047 'wgAction' => Action
::getActionName( $this->getContext() ),
3048 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3049 'wgUserGroups' => $user->getEffectiveGroups(),
3050 'wgCategories' => $this->getCategories(),
3051 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3052 'wgPageContentLanguage' => $lang->getCode(),
3053 'wgPageContentModel' => $title->getContentModel(),
3054 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3055 'wgDigitTransformTable' => $compactDigitTransTable,
3056 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3057 'wgMonthNames' => $lang->getMonthNamesArray(),
3058 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3059 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3060 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3061 'wgRequestId' => WebRequest
::getRequestId(),
3064 if ( $user->isLoggedIn() ) {
3065 $vars['wgUserId'] = $user->getId();
3066 $vars['wgUserEditCount'] = $user->getEditCount();
3067 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3068 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3069 // Get the revision ID of the oldest new message on the user's talk
3070 // page. This can be used for constructing new message alerts on
3072 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3075 if ( $wgContLang->hasVariants() ) {
3076 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3078 // Same test as SkinTemplate
3079 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3080 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3082 foreach ( $title->getRestrictionTypes() as $type ) {
3083 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3086 if ( $title->isMainPage() ) {
3087 $vars['wgIsMainPage'] = true;
3090 if ( $this->mRedirectedFrom
) {
3091 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3094 if ( $relevantUser ) {
3095 $vars['wgRelevantUserName'] = $relevantUser->getName();
3098 // Allow extensions to add their custom variables to the mw.config map.
3099 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3100 // page-dependant but site-wide (without state).
3101 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3102 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3104 // Merge in variables from addJsConfigVars last
3105 return array_merge( $vars, $this->getJsConfigVars() );
3109 * To make it harder for someone to slip a user a fake
3110 * user-JavaScript or user-CSS preview, a random token
3111 * is associated with the login session. If it's not
3112 * passed back with the preview request, we won't render
3117 public function userCanPreview() {
3118 $request = $this->getRequest();
3120 $request->getVal( 'action' ) !== 'submit' ||
3121 !$request->getCheck( 'wpPreview' ) ||
3122 !$request->wasPosted()
3127 $user = $this->getUser();
3129 if ( !$user->isLoggedIn() ) {
3130 // Anons have predictable edit tokens
3133 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3137 $title = $this->getTitle();
3138 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3141 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3142 // Don't execute another user's CSS or JS on preview (T85855)
3146 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3147 if ( count( $errors ) !== 0 ) {
3155 * @return array Array in format "link name or number => 'link html'".
3157 public function getHeadLinksArray() {
3161 $config = $this->getConfig();
3163 $canonicalUrl = $this->mCanonicalUrl
;
3165 $tags['meta-generator'] = Html
::element( 'meta', [
3166 'name' => 'generator',
3167 'content' => "MediaWiki $wgVersion",
3170 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3171 $tags['meta-referrer'] = Html
::element( 'meta', [
3172 'name' => 'referrer',
3173 'content' => $config->get( 'ReferrerPolicy' )
3177 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3178 if ( $p !== 'index,follow' ) {
3179 // http://www.robotstxt.org/wc/meta-user.html
3180 // Only show if it's different from the default robots policy
3181 $tags['meta-robots'] = Html
::element( 'meta', [
3187 foreach ( $this->mMetatags
as $tag ) {
3188 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3190 $tag[0] = substr( $tag[0], 5 );
3194 $tagName = "meta-{$tag[0]}";
3195 if ( isset( $tags[$tagName] ) ) {
3196 $tagName .= $tag[1];
3198 $tags[$tagName] = Html
::element( 'meta',
3201 'content' => $tag[1]
3206 foreach ( $this->mLinktags
as $tag ) {
3207 $tags[] = Html
::element( 'link', $tag );
3210 # Universal edit button
3211 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3212 $user = $this->getUser();
3213 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3214 && ( $this->getTitle()->exists() ||
3215 $this->getTitle()->quickUserCan( 'create', $user ) )
3217 // Original UniversalEditButton
3218 $msg = $this->msg( 'edit' )->text();
3219 $tags['universal-edit-button'] = Html
::element( 'link', [
3220 'rel' => 'alternate',
3221 'type' => 'application/x-wiki',
3223 'href' => $this->getTitle()->getEditURL(),
3225 // Alternate edit link
3226 $tags['alternative-edit'] = Html
::element( 'link', [
3229 'href' => $this->getTitle()->getEditURL(),
3234 # Generally the order of the favicon and apple-touch-icon links
3235 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3236 # uses whichever one appears later in the HTML source. Make sure
3237 # apple-touch-icon is specified first to avoid this.
3238 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3239 $tags['apple-touch-icon'] = Html
::element( 'link', [
3240 'rel' => 'apple-touch-icon',
3241 'href' => $config->get( 'AppleTouchIcon' )
3245 if ( $config->get( 'Favicon' ) !== false ) {
3246 $tags['favicon'] = Html
::element( 'link', [
3247 'rel' => 'shortcut icon',
3248 'href' => $config->get( 'Favicon' )
3252 # OpenSearch description link
3253 $tags['opensearch'] = Html
::element( 'link', [
3255 'type' => 'application/opensearchdescription+xml',
3256 'href' => wfScript( 'opensearch_desc' ),
3257 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3260 if ( $config->get( 'EnableAPI' ) ) {
3261 # Real Simple Discovery link, provides auto-discovery information
3262 # for the MediaWiki API (and potentially additional custom API
3263 # support such as WordPress or Twitter-compatible APIs for a
3264 # blogging extension, etc)
3265 $tags['rsd'] = Html
::element( 'link', [
3267 'type' => 'application/rsd+xml',
3268 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3269 // Whether RSD accepts relative or protocol-relative URLs is completely
3270 // undocumented, though.
3271 'href' => wfExpandUrl( wfAppendQuery(
3273 [ 'action' => 'rsd' ] ),
3280 if ( !$config->get( 'DisableLangConversion' ) ) {
3281 $lang = $this->getTitle()->getPageLanguage();
3282 if ( $lang->hasVariants() ) {
3283 $variants = $lang->getVariants();
3284 foreach ( $variants as $variant ) {
3285 $tags["variant-$variant"] = Html
::element( 'link', [
3286 'rel' => 'alternate',
3287 'hreflang' => wfBCP47( $variant ),
3288 'href' => $this->getTitle()->getLocalURL(
3289 [ 'variant' => $variant ] )
3293 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3294 $tags["variant-x-default"] = Html
::element( 'link', [
3295 'rel' => 'alternate',
3296 'hreflang' => 'x-default',
3297 'href' => $this->getTitle()->getLocalURL() ] );
3302 if ( $this->copyrightUrl
!== null ) {
3303 $copyright = $this->copyrightUrl
;
3306 if ( $config->get( 'RightsPage' ) ) {
3307 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3310 $copyright = $copy->getLocalURL();
3314 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3315 $copyright = $config->get( 'RightsUrl' );
3320 $tags['copyright'] = Html
::element( 'link', [
3321 'rel' => 'copyright',
3322 'href' => $copyright ]
3327 if ( $config->get( 'Feed' ) ) {
3330 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3331 # Use the page name for the title. In principle, this could
3332 # lead to issues with having the same name for different feeds
3333 # corresponding to the same page, but we can't avoid that at
3336 $feedLinks[] = $this->feedLink(
3339 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3341 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3346 # Recent changes feed should appear on every page (except recentchanges,
3347 # that would be redundant). Put it after the per-page feed to avoid
3348 # changing existing behavior. It's still available, probably via a
3349 # menu in your browser. Some sites might have a different feed they'd
3350 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3351 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3352 # If so, use it instead.
3353 $sitename = $config->get( 'Sitename' );
3354 if ( $config->get( 'OverrideSiteFeed' ) ) {
3355 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3356 // Note, this->feedLink escapes the url.
3357 $feedLinks[] = $this->feedLink(
3360 $this->msg( "site-{$type}-feed", $sitename )->text()
3363 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3364 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3365 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3366 $feedLinks[] = $this->feedLink(
3368 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3369 # For grep: 'site-rss-feed', 'site-atom-feed'
3370 $this->msg( "site-{$format}-feed", $sitename )->text()
3375 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3376 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3377 # use OutputPage::addFeedLink() instead.
3378 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3380 $tags +
= $feedLinks;
3384 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3385 if ( $canonicalUrl !== false ) {
3386 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3388 if ( $this->isArticleRelated() ) {
3389 // This affects all requests where "setArticleRelated" is true. This is
3390 // typically all requests that show content (query title, curid, oldid, diff),
3391 // and all wikipage actions (edit, delete, purge, info, history etc.).
3392 // It does not apply to File pages and Special pages.
3393 // 'history' and 'info' actions address page metadata rather than the page
3394 // content itself, so they may not be canonicalized to the view page url.
3395 // TODO: this ought to be better encapsulated in the Action class.
3396 $action = Action
::getActionName( $this->getContext() );
3397 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3398 $query = "action={$action}";
3402 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3404 $reqUrl = $this->getRequest()->getRequestURL();
3405 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3409 if ( $canonicalUrl !== false ) {
3410 $tags[] = Html
::element( 'link', [
3411 'rel' => 'canonical',
3412 'href' => $canonicalUrl
3420 * @return string HTML tag links to be put in the header.
3421 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3422 * OutputPage::getHeadLinksArray directly.
3424 public function getHeadLinks() {
3425 wfDeprecated( __METHOD__
, '1.24' );
3426 return implode( "\n", $this->getHeadLinksArray() );
3430 * Generate a "<link rel/>" for a feed.
3432 * @param string $type Feed type
3433 * @param string $url URL to the feed
3434 * @param string $text Value of the "title" attribute
3435 * @return string HTML fragment
3437 private function feedLink( $type, $url, $text ) {
3438 return Html
::element( 'link', [
3439 'rel' => 'alternate',
3440 'type' => "application/$type+xml",
3447 * Add a local or specified stylesheet, with the given media options.
3448 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3450 * @param string $style URL to the file
3451 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3452 * @param string $condition For IE conditional comments, specifying an IE version
3453 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3455 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3458 $options['media'] = $media;
3461 $options['condition'] = $condition;
3464 $options['dir'] = $dir;
3466 $this->styles
[$style] = $options;
3470 * Adds inline CSS styles
3471 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3473 * @param mixed $style_css Inline CSS
3474 * @param string $flip Set to 'flip' to flip the CSS if needed
3476 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3477 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3478 # If wanted, and the interface is right-to-left, flip the CSS
3479 $style_css = CSSJanus
::transform( $style_css, true, false );
3481 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3485 * Build exempt modules and legacy non-ResourceLoader styles.
3487 * @return string|WrappedStringList HTML
3489 protected function buildExemptModules() {
3492 $resourceLoader = $this->getResourceLoader();
3494 // Things that go after the ResourceLoaderDynamicStyles marker
3497 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3498 if ( $this->isUserCssPreview() ) {
3499 $append[] = $this->makeResourceLoaderLink(
3501 ResourceLoaderModule
::TYPE_STYLES
,
3502 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3505 // Load the previewed CSS. Janus it if needed.
3506 // User-supplied CSS is assumed to in the wiki's content language.
3507 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3508 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3509 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3511 $append[] = Html
::inlineStyle( $previewedCSS );
3514 // We want site, private and user styles to override dynamically added styles from
3515 // general modules, but we want dynamically added styles to override statically added
3516 // style modules. So the order has to be:
3517 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3518 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3519 // - ResourceLoaderDynamicStyles marker
3520 // - site/private/user styles
3522 // Add legacy styles added through addStyle()/addInlineStyle() here
3523 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3525 $chunks[] = Html
::element(
3527 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3530 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3531 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3532 ResourceLoaderModule
::TYPE_STYLES
3536 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3542 public function buildCssLinksArray() {
3545 // Add any extension CSS
3546 foreach ( $this->mExtStyles
as $url ) {
3547 $this->addStyle( $url );
3549 $this->mExtStyles
= [];
3551 foreach ( $this->styles
as $file => $options ) {
3552 $link = $this->styleLink( $file, $options );
3554 $links[$file] = $link;
3561 * Generate \<link\> tags for stylesheets
3563 * @param string $style URL to the file
3564 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3565 * @return string HTML fragment
3567 protected function styleLink( $style, array $options ) {
3568 if ( isset( $options['dir'] ) ) {
3569 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3574 if ( isset( $options['media'] ) ) {
3575 $media = self
::transformCssMedia( $options['media'] );
3576 if ( is_null( $media ) ) {
3583 if ( substr( $style, 0, 1 ) == '/' ||
3584 substr( $style, 0, 5 ) == 'http:' ||
3585 substr( $style, 0, 6 ) == 'https:' ) {
3588 $config = $this->getConfig();
3589 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3590 $config->get( 'StyleVersion' );
3593 $link = Html
::linkedStyle( $url, $media );
3595 if ( isset( $options['condition'] ) ) {
3596 $condition = htmlspecialchars( $options['condition'] );
3597 $link = "<!--[if $condition]>$link<![endif]-->";
3603 * Transform path to web-accessible static resource.
3605 * This is used to add a validation hash as query string.
3606 * This aids various behaviors:
3608 * - Put long Cache-Control max-age headers on responses for improved
3609 * cache performance.
3610 * - Get the correct version of a file as expected by the current page.
3611 * - Instantly get the updated version of a file after deployment.
3613 * Avoid using this for urls included in HTML as otherwise clients may get different
3614 * versions of a resource when navigating the site depending on when the page was cached.
3615 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3616 * an external stylesheet).
3619 * @param Config $config
3620 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3621 * @return string URL
3623 public static function transformResourcePath( Config
$config, $path ) {
3625 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3626 if ( $remotePathPrefix === '' ) {
3627 // The configured base path is required to be empty string for
3628 // wikis in the domain root
3631 $remotePath = $remotePathPrefix;
3633 if ( strpos( $path, $remotePath ) !== 0 ) {
3634 // Path is outside wgResourceBasePath, ignore.
3637 $path = RelPath\
getRelativePath( $path, $remotePath );
3638 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3642 * Utility method for transformResourceFilePath().
3644 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3647 * @param string $remotePath URL path prefix that points to $localPath
3648 * @param string $localPath File directory exposed at $remotePath
3649 * @param string $file Path to target file relative to $localPath
3650 * @return string URL
3652 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3653 $hash = md5_file( "$localPath/$file" );
3654 if ( $hash === false ) {
3655 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3658 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3662 * Transform "media" attribute based on request parameters
3664 * @param string $media Current value of the "media" attribute
3665 * @return string Modified value of the "media" attribute, or null to skip
3668 public static function transformCssMedia( $media ) {
3671 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3672 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3674 // Switch in on-screen display for media testing
3676 'printable' => 'print',
3677 'handheld' => 'handheld',
3679 foreach ( $switches as $switch => $targetMedia ) {
3680 if ( $wgRequest->getBool( $switch ) ) {
3681 if ( $media == $targetMedia ) {
3683 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3684 /* This regex will not attempt to understand a comma-separated media_query_list
3686 * Example supported values for $media:
3687 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3688 * Example NOT supported value for $media:
3689 * '3d-glasses, screen, print and resolution > 90dpi'
3691 * If it's a print request, we never want any kind of screen stylesheets
3692 * If it's a handheld request (currently the only other choice with a switch),
3693 * we don't want simple 'screen' but we might want screen queries that
3694 * have a max-width or something, so we'll pass all others on and let the
3695 * client do the query.
3697 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3708 * Add a wikitext-formatted message to the output.
3709 * This is equivalent to:
3711 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3713 public function addWikiMsg( /*...*/ ) {
3714 $args = func_get_args();
3715 $name = array_shift( $args );
3716 $this->addWikiMsgArray( $name, $args );
3720 * Add a wikitext-formatted message to the output.
3721 * Like addWikiMsg() except the parameters are taken as an array
3722 * instead of a variable argument list.
3724 * @param string $name
3725 * @param array $args
3727 public function addWikiMsgArray( $name, $args ) {
3728 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3732 * This function takes a number of message/argument specifications, wraps them in
3733 * some overall structure, and then parses the result and adds it to the output.
3735 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3736 * and so on. The subsequent arguments may be either
3737 * 1) strings, in which case they are message names, or
3738 * 2) arrays, in which case, within each array, the first element is the message
3739 * name, and subsequent elements are the parameters to that message.
3741 * Don't use this for messages that are not in the user's interface language.
3745 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3749 * $wgOut->addWikiText( "<div class='error'>\n"
3750 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3752 * The newline after the opening div is needed in some wikitext. See bug 19226.
3754 * @param string $wrap
3756 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3757 $msgSpecs = func_get_args();
3758 array_shift( $msgSpecs );
3759 $msgSpecs = array_values( $msgSpecs );
3761 foreach ( $msgSpecs as $n => $spec ) {
3762 if ( is_array( $spec ) ) {
3764 $name = array_shift( $args );
3765 if ( isset( $args['options'] ) ) {
3766 unset( $args['options'] );
3768 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3776 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3778 $this->addWikiText( $s );
3782 * Enables/disables TOC, doesn't override __NOTOC__
3786 public function enableTOC( $flag = true ) {
3787 $this->mEnableTOC
= $flag;
3794 public function isTOCEnabled() {
3795 return $this->mEnableTOC
;
3799 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3803 public function enableSectionEditLinks( $flag = true ) {
3804 $this->mEnableSectionEditLinks
= $flag;
3811 public function sectionEditLinksEnabled() {
3812 return $this->mEnableSectionEditLinks
;
3816 * Helper function to setup the PHP implementation of OOUI to use in this request.
3819 * @param String $skinName The Skin name to determine the correct OOUI theme
3820 * @param String $dir Language direction
3822 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3823 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3824 // Make keys (skin names) lowercase for case-insensitive matching.
3825 $themes = array_change_key_case( $themes, CASE_LOWER
);
3826 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3827 // For example, 'OOUI\MediaWikiTheme'.
3828 $themeClass = "OOUI\\{$theme}Theme";
3829 OOUI\Theme
::setSingleton( new $themeClass() );
3830 OOUI\Element
::setDefaultDir( $dir );
3834 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3835 * MediaWiki and this OutputPage instance.
3839 public function enableOOUI() {
3841 strtolower( $this->getSkin()->getSkinName() ),
3842 $this->getLanguage()->getDir()
3844 $this->addModuleStyles( [
3845 'oojs-ui-core.styles',
3846 'oojs-ui.styles.icons',
3847 'oojs-ui.styles.indicators',
3848 'oojs-ui.styles.textures',
3849 'mediawiki.widgets.styles',
3854 * @param array $data Data from ParserOutput::getLimitReportData()
3857 public function setLimitReportData( array $data ) {
3858 $this->limitReportData
= $data;