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
;
28 * This class should be covered by a general architecture document which does
29 * not exist as of January 2011. This is one of the Core classes and should
30 * be read at least once by any new developers.
32 * This class is used to prepare the final rendering. A skin is then
33 * applied to the output parameters (links, javascript, html, categories ...).
35 * @todo FIXME: Another class handles sending the whole page to the client.
37 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
42 class OutputPage
extends ContextSource
{
43 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
44 protected $mMetatags = [];
47 protected $mLinktags = [];
50 protected $mCanonicalUrl = false;
53 * @var array Additional stylesheets. Looks like this is for extensions.
54 * Might be replaced by ResourceLoader.
56 protected $mExtStyles = [];
59 * @var string Should be private - has getter and setter. Contains
61 public $mPagetitle = '';
64 * @var string Contains all of the "<body>" content. Should be private we
65 * got set/get accessors and the append() method.
67 public $mBodytext = '';
70 * Holds the debug lines that will be output as comments in page source if
71 * $wgDebugComments is enabled. See also $wgShowDebug.
72 * @deprecated since 1.20; use MWDebug class instead.
74 public $mDebugtext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsarticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
89 * @var bool We have to set isPrintable(). Some pages should
90 * never be printed (ex: redirections).
92 private $mPrintable = false;
95 * @var array Contains the page subtitle. Special pages usually have some
96 * links here. Don't confuse with site subtitle added by skins.
98 private $mSubtitle = [];
101 public $mRedirect = '';
104 protected $mStatusCode;
107 * @var string Used for sending cache control.
108 * The whole caching system should probably be moved into its own class.
110 protected $mLastModified = '';
113 protected $mCategoryLinks = [];
116 protected $mCategories = [];
119 protected $mIndicators = [];
121 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
122 private $mLanguageLinks = [];
125 * Used for JavaScript (predates ResourceLoader)
126 * @todo We should split JS / CSS.
127 * mScripts content is inserted as is in "<head>" by Skin. This might
128 * contain either a link to a stylesheet or inline CSS.
130 private $mScripts = '';
132 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
133 protected $mInlineStyles = '';
136 * @var string Used by skin template.
137 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
139 public $mPageLinkTitle = '';
141 /** @var array Array of elements in "<head>". Parser might add its own headers! */
142 protected $mHeadItems = [];
145 protected $mModules = [];
148 protected $mModuleScripts = [];
151 protected $mModuleStyles = [];
153 /** @var ResourceLoader */
154 protected $mResourceLoader;
157 protected $mJsConfigVars = [];
160 protected $mTemplateIds = [];
163 protected $mImageTimeKeys = [];
166 public $mRedirectCode = '';
168 protected $mFeedLinksAppendQuery = null;
171 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
172 * @see ResourceLoaderModule::$origin
173 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
175 protected $mAllowedModules = [
176 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
179 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
180 protected $mDoNothing = false;
185 protected $mContainsNewMagic = 0;
188 * lazy initialised, use parserOptions()
191 protected $mParserOptions = null;
194 * Handles the Atom / RSS links.
195 * We probably only support Atom in 2011.
196 * @see $wgAdvertisedFeedTypes
198 private $mFeedLinks = [];
200 // Gwicke work on squid caching? Roughly from 2003.
201 protected $mEnableClientCache = true;
203 /** @var bool Flag if output should only contain the body of the article. */
204 private $mArticleBodyOnly = false;
207 protected $mNewSectionLink = false;
210 protected $mHideNewSectionLink = false;
213 * @var bool Comes from the parser. This was probably made to load CSS/JS
214 * only if we had "<gallery>". Used directly in CategoryPage.php.
215 * Looks like ResourceLoader can replace this.
217 public $mNoGallery = false;
220 private $mPageTitleActionText = '';
222 /** @var int Cache stuff. Looks like mEnableClientCache */
223 protected $mCdnMaxage = 0;
224 /** @var int Upper limit on mCdnMaxage */
225 protected $mCdnMaxageLimit = INF
;
228 * @var bool Controls if anti-clickjacking / frame-breaking headers will
229 * be sent. This should be done for pages where edit actions are possible.
230 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
232 protected $mPreventClickjacking = true;
234 /** @var int To include the variable {{REVISIONID}} */
235 private $mRevisionId = null;
238 private $mRevisionTimestamp = null;
241 protected $mFileVersion = null;
244 * @var array An array of stylesheet filenames (relative from skins path),
245 * with options for CSS media, IE conditions, and RTL/LTR direction.
246 * For internal use; add settings in the skin via $this->addStyle()
248 * Style again! This seems like a code duplication since we already have
249 * mStyles. This is what makes Open Source amazing.
251 protected $styles = [];
254 * Whether jQuery is already handled.
256 protected $mJQueryDone = false;
258 private $mIndexPolicy = 'index';
259 private $mFollowPolicy = 'follow';
260 private $mVaryHeader = [
261 'Accept-Encoding' => [ 'match=gzip' ],
265 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
270 private $mRedirectedFrom = null;
273 * Additional key => value data
275 private $mProperties = [];
278 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
280 private $mTarget = null;
283 * @var bool Whether parser output should contain table of contents
285 private $mEnableTOC = true;
288 * @var bool Whether parser output should contain section edit links
290 private $mEnableSectionEditLinks = true;
293 * @var string|null The URL to send in a <link> element with rel=copyright
295 private $copyrightUrl;
298 * Constructor for OutputPage. This should not be called directly.
299 * Instead a new RequestContext should be created and it will implicitly create
300 * a OutputPage tied to that context.
301 * @param IContextSource|null $context
303 function __construct( IContextSource
$context = null ) {
304 if ( $context === null ) {
305 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
306 wfDeprecated( __METHOD__
, '1.18' );
308 $this->setContext( $context );
313 * Redirect to $url rather than displaying the normal page
315 * @param string $url URL
316 * @param string $responsecode HTTP status code
318 public function redirect( $url, $responsecode = '302' ) {
319 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
320 $this->mRedirect
= str_replace( "\n", '', $url );
321 $this->mRedirectCode
= $responsecode;
325 * Get the URL to redirect to, or an empty string if not redirect URL set
329 public function getRedirect() {
330 return $this->mRedirect
;
334 * Set the copyright URL to send with the output.
335 * Empty string to omit, null to reset.
339 * @param string|null $url
341 public function setCopyrightUrl( $url ) {
342 $this->copyrightUrl
= $url;
346 * Set the HTTP status code to send with the output.
348 * @param int $statusCode
350 public function setStatusCode( $statusCode ) {
351 $this->mStatusCode
= $statusCode;
355 * Add a new "<meta>" tag
356 * To add an http-equiv meta tag, precede the name with "http:"
358 * @param string $name Tag name
359 * @param string $val Tag value
361 function addMeta( $name, $val ) {
362 array_push( $this->mMetatags
, [ $name, $val ] );
366 * Returns the current <meta> tags
371 public function getMetaTags() {
372 return $this->mMetatags
;
376 * Add a new \<link\> tag to the page header.
378 * Note: use setCanonicalUrl() for rel=canonical.
380 * @param array $linkarr Associative array of attributes.
382 function addLink( array $linkarr ) {
383 array_push( $this->mLinktags
, $linkarr );
387 * Returns the current <link> tags
392 public function getLinkTags() {
393 return $this->mLinktags
;
397 * Add a new \<link\> with "rel" attribute set to "meta"
399 * @param array $linkarr Associative array mapping attribute names to their
400 * values, both keys and values will be escaped, and the
401 * "rel" attribute will be automatically added
403 function addMetadataLink( array $linkarr ) {
404 $linkarr['rel'] = $this->getMetadataAttribute();
405 $this->addLink( $linkarr );
409 * Set the URL to be used for the <link rel=canonical>. This should be used
410 * in preference to addLink(), to avoid duplicate link tags.
413 function setCanonicalUrl( $url ) {
414 $this->mCanonicalUrl
= $url;
418 * Returns the URL to be used for the <link rel=canonical> if
422 * @return bool|string
424 public function getCanonicalUrl() {
425 return $this->mCanonicalUrl
;
429 * Get the value of the "rel" attribute for metadata links
433 public function getMetadataAttribute() {
434 # note: buggy CC software only reads first "meta" link
435 static $haveMeta = false;
437 return 'alternate meta';
445 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
446 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
449 * @param string $script Raw HTML
451 function addScript( $script ) {
452 $this->mScripts
.= $script;
456 * Register and add a stylesheet from an extension directory.
458 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
459 * @param string $url Path to sheet. Provide either a full url (beginning
460 * with 'http', etc) or a relative path from the document root
461 * (beginning with '/'). Otherwise it behaves identically to
462 * addStyle() and draws from the /skins folder.
464 public function addExtensionStyle( $url ) {
465 wfDeprecated( __METHOD__
, '1.27' );
466 array_push( $this->mExtStyles
, $url );
470 * Get all styles added by extensions
472 * @deprecated since 1.27
475 function getExtStyle() {
476 wfDeprecated( __METHOD__
, '1.27' );
477 return $this->mExtStyles
;
481 * Add a JavaScript file out of skins/common, or a given relative path.
482 * Internal use only. Use OutputPage::addModules() if possible.
484 * @param string $file Filename in skins/common or complete on-server path
486 * @param string $version Style version of the file. Defaults to $wgStyleVersion
488 public function addScriptFile( $file, $version = null ) {
489 // See if $file parameter is an absolute URL or begins with a slash
490 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
493 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
495 if ( is_null( $version ) ) {
496 $version = $this->getConfig()->get( 'StyleVersion' );
498 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
502 * Add a self-contained script tag with the given contents
503 * Internal use only. Use OutputPage::addModules() if possible.
505 * @param string $script JavaScript text, no "<script>" tags
507 public function addInlineScript( $script ) {
508 $this->mScripts
.= Html
::inlineScript( $script );
512 * Filter an array of modules to remove insufficiently trustworthy members, and modules
513 * which are no longer registered (eg a page is cached before an extension is disabled)
514 * @param array $modules
515 * @param string|null $position If not null, only return modules with this position
516 * @param string $type
519 protected function filterModules( array $modules, $position = null,
520 $type = ResourceLoaderModule
::TYPE_COMBINED
522 $resourceLoader = $this->getResourceLoader();
523 $filteredModules = [];
524 foreach ( $modules as $val ) {
525 $module = $resourceLoader->getModule( $val );
526 if ( $module instanceof ResourceLoaderModule
527 && $module->getOrigin() <= $this->getAllowedModules( $type )
528 && ( is_null( $position ) ||
$module->getPosition() == $position )
529 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
531 $filteredModules[] = $val;
534 return $filteredModules;
538 * Get the list of modules to include on this page
540 * @param bool $filter Whether to filter out insufficiently trustworthy modules
541 * @param string|null $position If not null, only return modules with this position
542 * @param string $param
543 * @return array Array of module names
545 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
546 $modules = array_values( array_unique( $this->$param ) );
548 ?
$this->filterModules( $modules, $position )
553 * Add one or more modules recognized by ResourceLoader. Modules added
554 * through this function will be loaded by ResourceLoader when the
557 * @param string|array $modules Module name (string) or array of module names
559 public function addModules( $modules ) {
560 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
564 * Get the list of module JS to include on this page
566 * @param bool $filter
567 * @param string|null $position
569 * @return array Array of module names
571 public function getModuleScripts( $filter = false, $position = null ) {
572 return $this->getModules( $filter, $position, 'mModuleScripts' );
576 * Add only JS of one or more modules recognized by ResourceLoader. Module
577 * scripts added through this function will be loaded by ResourceLoader when
580 * @param string|array $modules Module name (string) or array of module names
582 public function addModuleScripts( $modules ) {
583 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
587 * Get the list of module CSS to include on this page
589 * @param bool $filter
590 * @param string|null $position
592 * @return array Array of module names
594 public function getModuleStyles( $filter = false, $position = null ) {
595 return $this->getModules( $filter, $position, 'mModuleStyles' );
599 * Add only CSS of one or more modules recognized by ResourceLoader.
601 * Module styles added through this function will be added using standard link CSS
602 * tags, rather than as a combined Javascript and CSS package. Thus, they will
603 * load when JavaScript is disabled (unless CSS also happens to be disabled).
605 * @param string|array $modules Module name (string) or array of module names
607 public function addModuleStyles( $modules ) {
608 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
612 * Get the list of module messages to include on this page
614 * @deprecated since 1.26 Obsolete
615 * @param bool $filter
616 * @param string|null $position
617 * @return array Array of module names
619 public function getModuleMessages( $filter = false, $position = null ) {
620 wfDeprecated( __METHOD__
, '1.26' );
625 * Load messages of one or more ResourceLoader modules.
627 * @deprecated since 1.26 Use addModules() instead
628 * @param string|array $modules Module name (string) or array of module names
630 public function addModuleMessages( $modules ) {
631 wfDeprecated( __METHOD__
, '1.26' );
635 * @return null|string ResourceLoader target
637 public function getTarget() {
638 return $this->mTarget
;
642 * Sets ResourceLoader target for load.php links. If null, will be omitted
644 * @param string|null $target
646 public function setTarget( $target ) {
647 $this->mTarget
= $target;
651 * Get an array of head items
655 function getHeadItemsArray() {
656 return $this->mHeadItems
;
660 * Add or replace an header item to the output
662 * Whenever possible, use more specific options like ResourceLoader modules,
663 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
664 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
665 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
666 * This would be your very LAST fallback.
668 * @param string $name Item name
669 * @param string $value Raw HTML
671 public function addHeadItem( $name, $value ) {
672 $this->mHeadItems
[$name] = $value;
676 * Check if the header item $name is already set
678 * @param string $name Item name
681 public function hasHeadItem( $name ) {
682 return isset( $this->mHeadItems
[$name] );
686 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
689 public function setETag( $tag ) {
693 * Set whether the output should only contain the body of the article,
694 * without any skin, sidebar, etc.
695 * Used e.g. when calling with "action=render".
697 * @param bool $only Whether to output only the body of the article
699 public function setArticleBodyOnly( $only ) {
700 $this->mArticleBodyOnly
= $only;
704 * Return whether the output will contain only the body of the article
708 public function getArticleBodyOnly() {
709 return $this->mArticleBodyOnly
;
713 * Set an additional output property
716 * @param string $name
717 * @param mixed $value
719 public function setProperty( $name, $value ) {
720 $this->mProperties
[$name] = $value;
724 * Get an additional output property
727 * @param string $name
728 * @return mixed Property value or null if not found
730 public function getProperty( $name ) {
731 if ( isset( $this->mProperties
[$name] ) ) {
732 return $this->mProperties
[$name];
739 * checkLastModified tells the client to use the client-cached page if
740 * possible. If successful, the OutputPage is disabled so that
741 * any future call to OutputPage->output() have no effect.
743 * Side effect: sets mLastModified for Last-Modified header
745 * @param string $timestamp
747 * @return bool True if cache-ok headers was sent.
749 public function checkLastModified( $timestamp ) {
750 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
751 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
754 $config = $this->getConfig();
755 if ( !$config->get( 'CachePages' ) ) {
756 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
760 $timestamp = wfTimestamp( TS_MW
, $timestamp );
762 'page' => $timestamp,
763 'user' => $this->getUser()->getTouched(),
764 'epoch' => $config->get( 'CacheEpoch' )
766 if ( $config->get( 'UseSquid' ) ) {
767 // bug 44570: the core page itself may not change, but resources might
768 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
770 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
772 $maxModified = max( $modifiedTimes );
773 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
775 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
776 if ( $clientHeader === false ) {
777 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
781 # IE sends sizes after the date like this:
782 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
783 # this breaks strtotime().
784 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
786 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
787 $clientHeaderTime = strtotime( $clientHeader );
788 MediaWiki\restoreWarnings
();
789 if ( !$clientHeaderTime ) {
791 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
794 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
798 foreach ( $modifiedTimes as $name => $value ) {
799 if ( $info !== '' ) {
802 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
805 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
806 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
807 wfDebug( __METHOD__
. ": effective Last-Modified: " .
808 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
809 if ( $clientHeaderTime < $maxModified ) {
810 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
815 # Give a 304 Not Modified response code and disable body output
816 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
817 ini_set( 'zlib.output_compression', 0 );
818 $this->getRequest()->response()->statusHeader( 304 );
819 $this->sendCacheControl();
822 // Don't output a compressed blob when using ob_gzhandler;
823 // it's technically against HTTP spec and seems to confuse
824 // Firefox when the response gets split over two packets.
825 wfClearOutputBuffers();
831 * Override the last modified timestamp
833 * @param string $timestamp New timestamp, in a format readable by
836 public function setLastModified( $timestamp ) {
837 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
841 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
843 * @param string $policy The literal string to output as the contents of
844 * the meta tag. Will be parsed according to the spec and output in
848 public function setRobotPolicy( $policy ) {
849 $policy = Article
::formatRobotPolicy( $policy );
851 if ( isset( $policy['index'] ) ) {
852 $this->setIndexPolicy( $policy['index'] );
854 if ( isset( $policy['follow'] ) ) {
855 $this->setFollowPolicy( $policy['follow'] );
860 * Set the index policy for the page, but leave the follow policy un-
863 * @param string $policy Either 'index' or 'noindex'.
866 public function setIndexPolicy( $policy ) {
867 $policy = trim( $policy );
868 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
869 $this->mIndexPolicy
= $policy;
874 * Set the follow policy for the page, but leave the index policy un-
877 * @param string $policy Either 'follow' or 'nofollow'.
880 public function setFollowPolicy( $policy ) {
881 $policy = trim( $policy );
882 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
883 $this->mFollowPolicy
= $policy;
888 * Set the new value of the "action text", this will be added to the
889 * "HTML title", separated from it with " - ".
891 * @param string $text New value of the "action text"
893 public function setPageTitleActionText( $text ) {
894 $this->mPageTitleActionText
= $text;
898 * Get the value of the "action text"
902 public function getPageTitleActionText() {
903 return $this->mPageTitleActionText
;
907 * "HTML title" means the contents of "<title>".
908 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
910 * @param string|Message $name
912 public function setHTMLTitle( $name ) {
913 if ( $name instanceof Message
) {
914 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
916 $this->mHTMLtitle
= $name;
921 * Return the "HTML title", i.e. the content of the "<title>" tag.
925 public function getHTMLTitle() {
926 return $this->mHTMLtitle
;
930 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
934 public function setRedirectedFrom( $t ) {
935 $this->mRedirectedFrom
= $t;
939 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
940 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
941 * but not bad tags like \<script\>. This function automatically sets
942 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
943 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
944 * good tags like \<i\> will be dropped entirely.
946 * @param string|Message $name
948 public function setPageTitle( $name ) {
949 if ( $name instanceof Message
) {
950 $name = $name->setContext( $this->getContext() )->text();
953 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
954 # but leave "<i>foobar</i>" alone
955 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
956 $this->mPagetitle
= $nameWithTags;
958 # change "<i>foo&bar</i>" to "foo&bar"
960 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
961 ->inContentLanguage()
966 * Return the "page title", i.e. the content of the \<h1\> tag.
970 public function getPageTitle() {
971 return $this->mPagetitle
;
975 * Set the Title object to use
979 public function setTitle( Title
$t ) {
980 $this->getContext()->setTitle( $t );
984 * Replace the subtitle with $str
986 * @param string|Message $str New value of the subtitle. String should be safe HTML.
988 public function setSubtitle( $str ) {
989 $this->clearSubtitle();
990 $this->addSubtitle( $str );
994 * Add $str to the subtitle
996 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
998 public function addSubtitle( $str ) {
999 if ( $str instanceof Message
) {
1000 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1002 $this->mSubtitle
[] = $str;
1007 * Build message object for a subtitle containing a backlink to a page
1009 * @param Title $title Title to link to
1010 * @param array $query Array of additional parameters to include in the link
1014 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1015 if ( $title->isRedirect() ) {
1016 $query['redirect'] = 'no';
1018 return wfMessage( 'backlinksubtitle' )
1019 ->rawParams( Linker
::link( $title, null, [], $query ) );
1023 * Add a subtitle containing a backlink to a page
1025 * @param Title $title Title to link to
1026 * @param array $query Array of additional parameters to include in the link
1028 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1029 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1033 * Clear the subtitles
1035 public function clearSubtitle() {
1036 $this->mSubtitle
= [];
1044 public function getSubtitle() {
1045 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1049 * Set the page as printable, i.e. it'll be displayed with all
1050 * print styles included
1052 public function setPrintable() {
1053 $this->mPrintable
= true;
1057 * Return whether the page is "printable"
1061 public function isPrintable() {
1062 return $this->mPrintable
;
1066 * Disable output completely, i.e. calling output() will have no effect
1068 public function disable() {
1069 $this->mDoNothing
= true;
1073 * Return whether the output will be completely disabled
1077 public function isDisabled() {
1078 return $this->mDoNothing
;
1082 * Show an "add new section" link?
1086 public function showNewSectionLink() {
1087 return $this->mNewSectionLink
;
1091 * Forcibly hide the new section link?
1095 public function forceHideNewSectionLink() {
1096 return $this->mHideNewSectionLink
;
1100 * Add or remove feed links in the page header
1101 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1102 * for the new version
1103 * @see addFeedLink()
1105 * @param bool $show True: add default feeds, false: remove all feeds
1107 public function setSyndicated( $show = true ) {
1109 $this->setFeedAppendQuery( false );
1111 $this->mFeedLinks
= [];
1116 * Add default feeds to the page header
1117 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1118 * for the new version
1119 * @see addFeedLink()
1121 * @param string $val Query to append to feed links or false to output
1124 public function setFeedAppendQuery( $val ) {
1125 $this->mFeedLinks
= [];
1127 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1128 $query = "feed=$type";
1129 if ( is_string( $val ) ) {
1130 $query .= '&' . $val;
1132 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1137 * Add a feed link to the page header
1139 * @param string $format Feed type, should be a key of $wgFeedClasses
1140 * @param string $href URL
1142 public function addFeedLink( $format, $href ) {
1143 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1144 $this->mFeedLinks
[$format] = $href;
1149 * Should we output feed links for this page?
1152 public function isSyndicated() {
1153 return count( $this->mFeedLinks
) > 0;
1157 * Return URLs for each supported syndication format for this page.
1158 * @return array Associating format keys with URLs
1160 public function getSyndicationLinks() {
1161 return $this->mFeedLinks
;
1165 * Will currently always return null
1169 public function getFeedAppendQuery() {
1170 return $this->mFeedLinksAppendQuery
;
1174 * Set whether the displayed content is related to the source of the
1175 * corresponding article on the wiki
1176 * Setting true will cause the change "article related" toggle to true
1180 public function setArticleFlag( $v ) {
1181 $this->mIsarticle
= $v;
1183 $this->mIsArticleRelated
= $v;
1188 * Return whether the content displayed page is related to the source of
1189 * the corresponding article on the wiki
1193 public function isArticle() {
1194 return $this->mIsarticle
;
1198 * Set whether this page is related an article on the wiki
1199 * Setting false will cause the change of "article flag" toggle to false
1203 public function setArticleRelated( $v ) {
1204 $this->mIsArticleRelated
= $v;
1206 $this->mIsarticle
= false;
1211 * Return whether this page is related an article on the wiki
1215 public function isArticleRelated() {
1216 return $this->mIsArticleRelated
;
1220 * Add new language links
1222 * @param array $newLinkArray Associative array mapping language code to the page
1225 public function addLanguageLinks( array $newLinkArray ) {
1226 $this->mLanguageLinks +
= $newLinkArray;
1230 * Reset the language links and add new language links
1232 * @param array $newLinkArray Associative array mapping language code to the page
1235 public function setLanguageLinks( array $newLinkArray ) {
1236 $this->mLanguageLinks
= $newLinkArray;
1240 * Get the list of language links
1242 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1244 public function getLanguageLinks() {
1245 return $this->mLanguageLinks
;
1249 * Add an array of categories, with names in the keys
1251 * @param array $categories Mapping category name => sort key
1253 public function addCategoryLinks( array $categories ) {
1256 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1260 # Add the links to a LinkBatch
1261 $arr = [ NS_CATEGORY
=> $categories ];
1262 $lb = new LinkBatch
;
1263 $lb->setArray( $arr );
1265 # Fetch existence plus the hiddencat property
1266 $dbr = wfGetDB( DB_SLAVE
);
1267 $fields = array_merge(
1268 LinkCache
::getSelectFields(),
1269 [ 'page_namespace', 'page_title', 'pp_value' ]
1272 $res = $dbr->select( [ 'page', 'page_props' ],
1274 $lb->constructSet( 'page', $dbr ),
1277 [ 'page_props' => [ 'LEFT JOIN', [
1278 'pp_propname' => 'hiddencat',
1283 # Add the results to the link cache
1284 $lb->addResultToCache( LinkCache
::singleton(), $res );
1286 # Set all the values to 'normal'.
1287 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1289 # Mark hidden categories
1290 foreach ( $res as $row ) {
1291 if ( isset( $row->pp_value
) ) {
1292 $categories[$row->page_title
] = 'hidden';
1296 # Add the remaining categories to the skin
1298 'OutputPageMakeCategoryLinks',
1299 [ &$this, $categories, &$this->mCategoryLinks
] )
1301 foreach ( $categories as $category => $type ) {
1302 // array keys will cast numeric category names to ints, so cast back to string
1303 $category = (string)$category;
1304 $origcategory = $category;
1305 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1309 $wgContLang->findVariantLink( $category, $title, true );
1310 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1313 $text = $wgContLang->convertHtml( $title->getText() );
1314 $this->mCategories
[] = $title->getText();
1315 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1321 * Reset the category links (but not the category list) and add $categories
1323 * @param array $categories Mapping category name => sort key
1325 public function setCategoryLinks( array $categories ) {
1326 $this->mCategoryLinks
= [];
1327 $this->addCategoryLinks( $categories );
1331 * Get the list of category links, in a 2-D array with the following format:
1332 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1333 * hidden categories) and $link a HTML fragment with a link to the category
1338 public function getCategoryLinks() {
1339 return $this->mCategoryLinks
;
1343 * Get the list of category names this page belongs to
1345 * @return array Array of strings
1347 public function getCategories() {
1348 return $this->mCategories
;
1352 * Add an array of indicators, with their identifiers as array
1353 * keys and HTML contents as values.
1355 * In case of duplicate keys, existing values are overwritten.
1357 * @param array $indicators
1360 public function setIndicators( array $indicators ) {
1361 $this->mIndicators
= $indicators +
$this->mIndicators
;
1362 // Keep ordered by key
1363 ksort( $this->mIndicators
);
1367 * Get the indicators associated with this page.
1369 * The array will be internally ordered by item keys.
1371 * @return array Keys: identifiers, values: HTML contents
1374 public function getIndicators() {
1375 return $this->mIndicators
;
1379 * Adds help link with an icon via page indicators.
1380 * Link target can be overridden by a local message containing a wikilink:
1381 * the message key is: lowercase action or special page name + '-helppage'.
1382 * @param string $to Target MediaWiki.org page title or encoded URL.
1383 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1386 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1387 $this->addModuleStyles( 'mediawiki.helplink' );
1388 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1390 if ( $overrideBaseUrl ) {
1393 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1394 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1397 $link = Html
::rawElement(
1401 'target' => '_blank',
1402 'class' => 'mw-helplink',
1407 $this->setIndicators( [ 'mw-helplink' => $link ] );
1411 * Do not allow scripts which can be modified by wiki users to load on this page;
1412 * only allow scripts bundled with, or generated by, the software.
1413 * Site-wide styles are controlled by a config setting, since they can be
1414 * used to create a custom skin/theme, but not user-specific ones.
1416 * @todo this should be given a more accurate name
1418 public function disallowUserJs() {
1419 $this->reduceAllowedModules(
1420 ResourceLoaderModule
::TYPE_SCRIPTS
,
1421 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1424 // Site-wide styles are controlled by a config setting, see bug 71621
1425 // for background on why. User styles are never allowed.
1426 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1427 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1429 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1431 $this->reduceAllowedModules(
1432 ResourceLoaderModule
::TYPE_STYLES
,
1438 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1439 * @see ResourceLoaderModule::$origin
1440 * @param string $type ResourceLoaderModule TYPE_ constant
1441 * @return int ResourceLoaderModule ORIGIN_ class constant
1443 public function getAllowedModules( $type ) {
1444 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1445 return min( array_values( $this->mAllowedModules
) );
1447 return isset( $this->mAllowedModules
[$type] )
1448 ?
$this->mAllowedModules
[$type]
1449 : ResourceLoaderModule
::ORIGIN_ALL
;
1454 * Limit the highest level of CSS/JS untrustworthiness allowed.
1456 * If passed the same or a higher level than the current level of untrustworthiness set, the
1457 * level will remain unchanged.
1459 * @param string $type
1460 * @param int $level ResourceLoaderModule class constant
1462 public function reduceAllowedModules( $type, $level ) {
1463 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1467 * Prepend $text to the body HTML
1469 * @param string $text HTML
1471 public function prependHTML( $text ) {
1472 $this->mBodytext
= $text . $this->mBodytext
;
1476 * Append $text to the body HTML
1478 * @param string $text HTML
1480 public function addHTML( $text ) {
1481 $this->mBodytext
.= $text;
1485 * Shortcut for adding an Html::element via addHTML.
1489 * @param string $element
1490 * @param array $attribs
1491 * @param string $contents
1493 public function addElement( $element, array $attribs = [], $contents = '' ) {
1494 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1498 * Clear the body HTML
1500 public function clearHTML() {
1501 $this->mBodytext
= '';
1507 * @return string HTML
1509 public function getHTML() {
1510 return $this->mBodytext
;
1514 * Get/set the ParserOptions object to use for wikitext parsing
1516 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1517 * current ParserOption object
1518 * @return ParserOptions
1520 public function parserOptions( $options = null ) {
1521 if ( $options !== null && !empty( $options->isBogus
) ) {
1522 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1523 // been changed somehow, and keep it if so.
1524 $anonPO = ParserOptions
::newFromAnon();
1525 $anonPO->setEditSection( false );
1526 if ( !$options->matches( $anonPO ) ) {
1527 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1528 $options->isBogus
= false;
1532 if ( !$this->mParserOptions
) {
1533 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1534 // $wgUser isn't unstubbable yet, so don't try to get a
1535 // ParserOptions for it. And don't cache this ParserOptions
1537 $po = ParserOptions
::newFromAnon();
1538 $po->setEditSection( false );
1539 $po->isBogus
= true;
1540 if ( $options !== null ) {
1541 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1546 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1547 $this->mParserOptions
->setEditSection( false );
1550 if ( $options !== null && !empty( $options->isBogus
) ) {
1551 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1553 return wfSetVar( $this->mParserOptions
, null, true );
1555 return wfSetVar( $this->mParserOptions
, $options );
1560 * Set the revision ID which will be seen by the wiki text parser
1561 * for things such as embedded {{REVISIONID}} variable use.
1563 * @param int|null $revid An positive integer, or null
1564 * @return mixed Previous value
1566 public function setRevisionId( $revid ) {
1567 $val = is_null( $revid ) ?
null : intval( $revid );
1568 return wfSetVar( $this->mRevisionId
, $val );
1572 * Get the displayed revision ID
1576 public function getRevisionId() {
1577 return $this->mRevisionId
;
1581 * Set the timestamp of the revision which will be displayed. This is used
1582 * to avoid a extra DB call in Skin::lastModified().
1584 * @param string|null $timestamp
1585 * @return mixed Previous value
1587 public function setRevisionTimestamp( $timestamp ) {
1588 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1592 * Get the timestamp of displayed revision.
1593 * This will be null if not filled by setRevisionTimestamp().
1595 * @return string|null
1597 public function getRevisionTimestamp() {
1598 return $this->mRevisionTimestamp
;
1602 * Set the displayed file version
1604 * @param File|bool $file
1605 * @return mixed Previous value
1607 public function setFileVersion( $file ) {
1609 if ( $file instanceof File
&& $file->exists() ) {
1610 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1612 return wfSetVar( $this->mFileVersion
, $val, true );
1616 * Get the displayed file version
1618 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1620 public function getFileVersion() {
1621 return $this->mFileVersion
;
1625 * Get the templates used on this page
1627 * @return array (namespace => dbKey => revId)
1630 public function getTemplateIds() {
1631 return $this->mTemplateIds
;
1635 * Get the files used on this page
1637 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1640 public function getFileSearchOptions() {
1641 return $this->mImageTimeKeys
;
1645 * Convert wikitext to HTML and add it to the buffer
1646 * Default assumes that the current page title will be used.
1648 * @param string $text
1649 * @param bool $linestart Is this the start of a line?
1650 * @param bool $interface Is this text in the user interface language?
1651 * @throws MWException
1653 public function addWikiText( $text, $linestart = true, $interface = true ) {
1654 $title = $this->getTitle(); // Work around E_STRICT
1656 throw new MWException( 'Title is null' );
1658 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1662 * Add wikitext with a custom Title object
1664 * @param string $text Wikitext
1665 * @param Title $title
1666 * @param bool $linestart Is this the start of a line?
1668 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1669 $this->addWikiTextTitle( $text, $title, $linestart );
1673 * Add wikitext with a custom Title object and tidy enabled.
1675 * @param string $text Wikitext
1676 * @param Title $title
1677 * @param bool $linestart Is this the start of a line?
1679 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1680 $this->addWikiTextTitle( $text, $title, $linestart, true );
1684 * Add wikitext with tidy enabled
1686 * @param string $text Wikitext
1687 * @param bool $linestart Is this the start of a line?
1689 public function addWikiTextTidy( $text, $linestart = true ) {
1690 $title = $this->getTitle();
1691 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1695 * Add wikitext with a custom Title object
1697 * @param string $text Wikitext
1698 * @param Title $title
1699 * @param bool $linestart Is this the start of a line?
1700 * @param bool $tidy Whether to use tidy
1701 * @param bool $interface Whether it is an interface message
1702 * (for example disables conversion)
1704 public function addWikiTextTitle( $text, Title
$title, $linestart,
1705 $tidy = false, $interface = false
1709 $popts = $this->parserOptions();
1710 $oldTidy = $popts->setTidy( $tidy );
1711 $popts->setInterfaceMessage( (bool)$interface );
1713 $parserOutput = $wgParser->getFreshParser()->parse(
1714 $text, $title, $popts,
1715 $linestart, true, $this->mRevisionId
1718 $popts->setTidy( $oldTidy );
1720 $this->addParserOutput( $parserOutput );
1725 * Add a ParserOutput object, but without Html.
1727 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1728 * @param ParserOutput $parserOutput
1730 public function addParserOutputNoText( $parserOutput ) {
1731 wfDeprecated( __METHOD__
, '1.24' );
1732 $this->addParserOutputMetadata( $parserOutput );
1736 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1737 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1741 * @param ParserOutput $parserOutput
1743 public function addParserOutputMetadata( $parserOutput ) {
1744 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1745 $this->addCategoryLinks( $parserOutput->getCategories() );
1746 $this->setIndicators( $parserOutput->getIndicators() );
1747 $this->mNewSectionLink
= $parserOutput->getNewSection();
1748 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1750 if ( !$parserOutput->isCacheable() ) {
1751 $this->enableClientCache( false );
1753 $this->mNoGallery
= $parserOutput->getNoGallery();
1754 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1755 $this->addModules( $parserOutput->getModules() );
1756 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1757 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1758 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1759 $this->mPreventClickjacking
= $this->mPreventClickjacking
1760 ||
$parserOutput->preventClickjacking();
1762 // Template versioning...
1763 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1764 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1765 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1767 $this->mTemplateIds
[$ns] = $dbks;
1770 // File versioning...
1771 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1772 $this->mImageTimeKeys
[$dbk] = $data;
1775 // Hooks registered in the object
1776 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1777 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1778 list( $hookName, $data ) = $hookInfo;
1779 if ( isset( $parserOutputHooks[$hookName] ) ) {
1780 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1784 // enable OOUI if requested via ParserOutput
1785 if ( $parserOutput->getEnableOOUI() ) {
1786 $this->enableOOUI();
1789 // Link flags are ignored for now, but may in the future be
1790 // used to mark individual language links.
1792 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1793 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1797 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1798 * ParserOutput object, without any other metadata.
1801 * @param ParserOutput $parserOutput
1803 public function addParserOutputContent( $parserOutput ) {
1804 $this->addParserOutputText( $parserOutput );
1806 $this->addModules( $parserOutput->getModules() );
1807 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1808 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1810 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1814 * Add the HTML associated with a ParserOutput object, without any metadata.
1817 * @param ParserOutput $parserOutput
1819 public function addParserOutputText( $parserOutput ) {
1820 $text = $parserOutput->getText();
1821 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1822 $this->addHTML( $text );
1826 * Add everything from a ParserOutput object.
1828 * @param ParserOutput $parserOutput
1830 function addParserOutput( $parserOutput ) {
1831 $this->addParserOutputMetadata( $parserOutput );
1832 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1834 // Touch section edit links only if not previously disabled
1835 if ( $parserOutput->getEditSectionTokens() ) {
1836 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1839 $this->addParserOutputText( $parserOutput );
1843 * Add the output of a QuickTemplate to the output buffer
1845 * @param QuickTemplate $template
1847 public function addTemplate( &$template ) {
1848 $this->addHTML( $template->getHTML() );
1852 * Parse wikitext and return the HTML.
1854 * @param string $text
1855 * @param bool $linestart Is this the start of a line?
1856 * @param bool $interface Use interface language ($wgLang instead of
1857 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1858 * This also disables LanguageConverter.
1859 * @param Language $language Target language object, will override $interface
1860 * @throws MWException
1861 * @return string HTML
1863 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1866 if ( is_null( $this->getTitle() ) ) {
1867 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1870 $popts = $this->parserOptions();
1872 $popts->setInterfaceMessage( true );
1874 if ( $language !== null ) {
1875 $oldLang = $popts->setTargetLanguage( $language );
1878 $parserOutput = $wgParser->getFreshParser()->parse(
1879 $text, $this->getTitle(), $popts,
1880 $linestart, true, $this->mRevisionId
1884 $popts->setInterfaceMessage( false );
1886 if ( $language !== null ) {
1887 $popts->setTargetLanguage( $oldLang );
1890 return $parserOutput->getText();
1894 * Parse wikitext, strip paragraphs, and return the HTML.
1896 * @param string $text
1897 * @param bool $linestart Is this the start of a line?
1898 * @param bool $interface Use interface language ($wgLang instead of
1899 * $wgContLang) while parsing language sensitive magic
1900 * words like GRAMMAR and PLURAL
1901 * @return string HTML
1903 public function parseInline( $text, $linestart = true, $interface = false ) {
1904 $parsed = $this->parse( $text, $linestart, $interface );
1905 return Parser
::stripOuterParagraph( $parsed );
1910 * @deprecated since 1.27 Use setCdnMaxage() instead
1912 public function setSquidMaxage( $maxage ) {
1913 $this->setCdnMaxage( $maxage );
1917 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1919 * @param int $maxage Maximum cache time on the CDN, in seconds.
1921 public function setCdnMaxage( $maxage ) {
1922 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1926 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1928 * @param int $maxage Maximum cache time on the CDN, in seconds
1931 public function lowerCdnMaxage( $maxage ) {
1932 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1933 $this->setCdnMaxage( $this->mCdnMaxage
);
1937 * Use enableClientCache(false) to force it to send nocache headers
1939 * @param bool $state
1943 public function enableClientCache( $state ) {
1944 return wfSetVar( $this->mEnableClientCache
, $state );
1948 * Get the list of cookies that will influence on the cache
1952 function getCacheVaryCookies() {
1954 if ( $cookies === null ) {
1955 $config = $this->getConfig();
1956 $cookies = array_merge(
1957 SessionManager
::singleton()->getVaryCookies(),
1961 $config->get( 'CacheVaryCookies' )
1963 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
1969 * Check if the request has a cache-varying cookie header
1970 * If it does, it's very important that we don't allow public caching
1974 function haveCacheVaryCookies() {
1975 $request = $this->getRequest();
1976 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
1977 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
1978 wfDebug( __METHOD__
. ": found $cookieName\n" );
1982 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1987 * Add an HTTP header that will influence on the cache
1989 * @param string $header Header name
1990 * @param string[]|null $option Options for the Key header. See
1991 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
1992 * for the list of valid options.
1994 public function addVaryHeader( $header, array $option = null ) {
1995 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1996 $this->mVaryHeader
[$header] = [];
1998 if ( !is_array( $option ) ) {
2001 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2005 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2006 * such as Accept-Encoding or Cookie
2010 public function getVaryHeader() {
2011 // If we vary on cookies, let's make sure it's always included here too.
2012 if ( $this->getCacheVaryCookies() ) {
2013 $this->addVaryHeader( 'Cookie' );
2016 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2017 $this->addVaryHeader( $header, $options );
2019 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2023 * Get a complete Key header
2027 public function getKeyHeader() {
2028 $cvCookies = $this->getCacheVaryCookies();
2030 $cookiesOption = [];
2031 foreach ( $cvCookies as $cookieName ) {
2032 $cookiesOption[] = 'param=' . $cookieName;
2034 $this->addVaryHeader( 'Cookie', $cookiesOption );
2036 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2037 $this->addVaryHeader( $header, $options );
2041 foreach ( $this->mVaryHeader
as $header => $option ) {
2042 $newheader = $header;
2043 if ( is_array( $option ) && count( $option ) > 0 ) {
2044 $newheader .= ';' . implode( ';', $option );
2046 $headers[] = $newheader;
2048 $key = 'Key: ' . implode( ',', $headers );
2054 * T23672: Add Accept-Language to Vary and Key headers
2055 * if there's no 'variant' parameter existed in GET.
2058 * /w/index.php?title=Main_page should always be served; but
2059 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2061 function addAcceptLanguage() {
2062 $title = $this->getTitle();
2063 if ( !$title instanceof Title
) {
2067 $lang = $title->getPageLanguage();
2068 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2069 $variants = $lang->getVariants();
2071 foreach ( $variants as $variant ) {
2072 if ( $variant === $lang->getCode() ) {
2075 $aloption[] = 'substr=' . $variant;
2077 // IE and some other browsers use BCP 47 standards in
2078 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2079 // We should handle these too.
2080 $variantBCP47 = wfBCP47( $variant );
2081 if ( $variantBCP47 !== $variant ) {
2082 $aloption[] = 'substr=' . $variantBCP47;
2086 $this->addVaryHeader( 'Accept-Language', $aloption );
2091 * Set a flag which will cause an X-Frame-Options header appropriate for
2092 * edit pages to be sent. The header value is controlled by
2093 * $wgEditPageFrameOptions.
2095 * This is the default for special pages. If you display a CSRF-protected
2096 * form on an ordinary view page, then you need to call this function.
2098 * @param bool $enable
2100 public function preventClickjacking( $enable = true ) {
2101 $this->mPreventClickjacking
= $enable;
2105 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2106 * This can be called from pages which do not contain any CSRF-protected
2109 public function allowClickjacking() {
2110 $this->mPreventClickjacking
= false;
2114 * Get the prevent-clickjacking flag
2119 public function getPreventClickjacking() {
2120 return $this->mPreventClickjacking
;
2124 * Get the X-Frame-Options header value (without the name part), or false
2125 * if there isn't one. This is used by Skin to determine whether to enable
2126 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2130 public function getFrameOptions() {
2131 $config = $this->getConfig();
2132 if ( $config->get( 'BreakFrames' ) ) {
2134 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2135 return $config->get( 'EditPageFrameOptions' );
2141 * Send cache control HTTP headers
2143 public function sendCacheControl() {
2144 $response = $this->getRequest()->response();
2145 $config = $this->getConfig();
2147 $this->addVaryHeader( 'Cookie' );
2148 $this->addAcceptLanguage();
2150 # don't serve compressed data to clients who can't handle it
2151 # maintain different caches for logged-in users and non-logged in ones
2152 $response->header( $this->getVaryHeader() );
2154 if ( $config->get( 'UseKeyHeader' ) ) {
2155 $response->header( $this->getKeyHeader() );
2158 if ( $this->mEnableClientCache
) {
2160 $config->get( 'UseSquid' ) &&
2161 !$response->hasCookies() &&
2162 !SessionManager
::getGlobalSession()->isPersistent() &&
2163 !$this->isPrintable() &&
2164 $this->mCdnMaxage
!= 0 &&
2165 !$this->haveCacheVaryCookies()
2167 if ( $config->get( 'UseESI' ) ) {
2168 # We'll purge the proxy cache explicitly, but require end user agents
2169 # to revalidate against the proxy on each visit.
2170 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2171 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2172 # start with a shorter timeout for initial testing
2173 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2174 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2175 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2176 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2178 # We'll purge the proxy cache for anons explicitly, but require end user agents
2179 # to revalidate against the proxy on each visit.
2180 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2181 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2182 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2183 # start with a shorter timeout for initial testing
2184 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2185 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2186 . ', must-revalidate, max-age=0' );
2189 # We do want clients to cache if they can, but they *must* check for updates
2190 # on revisiting the page.
2191 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2192 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2193 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2195 if ( $this->mLastModified
) {
2196 $response->header( "Last-Modified: {$this->mLastModified}" );
2199 wfDebug( __METHOD__
. ": no caching **", 'private' );
2201 # In general, the absence of a last modified header should be enough to prevent
2202 # the client from using its cache. We send a few other things just to make sure.
2203 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2204 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2205 $response->header( 'Pragma: no-cache' );
2210 * Finally, all the text has been munged and accumulated into
2211 * the object, let's actually output it:
2213 public function output() {
2214 if ( $this->mDoNothing
) {
2218 $response = $this->getRequest()->response();
2219 $config = $this->getConfig();
2221 if ( $this->mRedirect
!= '' ) {
2222 # Standards require redirect URLs to be absolute
2223 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2225 $redirect = $this->mRedirect
;
2226 $code = $this->mRedirectCode
;
2228 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2229 if ( $code == '301' ||
$code == '303' ) {
2230 if ( !$config->get( 'DebugRedirects' ) ) {
2231 $response->statusHeader( $code );
2233 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2235 if ( $config->get( 'VaryOnXFP' ) ) {
2236 $this->addVaryHeader( 'X-Forwarded-Proto' );
2238 $this->sendCacheControl();
2240 $response->header( "Content-Type: text/html; charset=utf-8" );
2241 if ( $config->get( 'DebugRedirects' ) ) {
2242 $url = htmlspecialchars( $redirect );
2243 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2244 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2245 print "</body>\n</html>\n";
2247 $response->header( 'Location: ' . $redirect );
2252 } elseif ( $this->mStatusCode
) {
2253 $response->statusHeader( $this->mStatusCode
);
2256 # Buffer output; final headers may depend on later processing
2259 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2260 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2262 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2263 // jQuery etc. can work correctly.
2264 $response->header( 'X-UA-Compatible: IE=Edge' );
2266 // Prevent framing, if requested
2267 $frameOptions = $this->getFrameOptions();
2268 if ( $frameOptions ) {
2269 $response->header( "X-Frame-Options: $frameOptions" );
2272 if ( $this->mArticleBodyOnly
) {
2273 echo $this->mBodytext
;
2275 $sk = $this->getSkin();
2276 // add skin specific modules
2277 $modules = $sk->getDefaultModules();
2279 // Enforce various default modules for all skins
2281 // Keep this list as small as possible
2283 'mediawiki.page.startup',
2287 // Support for high-density display images if enabled
2288 if ( $config->get( 'ResponsiveImages' ) ) {
2289 $coreModules[] = 'mediawiki.hidpi';
2292 $this->addModules( $coreModules );
2293 foreach ( $modules as $group ) {
2294 $this->addModules( $group );
2296 MWDebug
::addModules( $this );
2298 // Hook that allows last minute changes to the output page, e.g.
2299 // adding of CSS or Javascript by extensions.
2300 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2304 } catch ( Exception
$e ) {
2305 ob_end_clean(); // bug T129657
2311 // This hook allows last minute changes to final overall output by modifying output buffer
2312 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2313 } catch ( Exception
$e ) {
2314 ob_end_clean(); // bug T129657
2318 $this->sendCacheControl();
2325 * Prepare this object to display an error page; disable caching and
2326 * indexing, clear the current text and redirect, set the page's title
2327 * and optionally an custom HTML title (content of the "<title>" tag).
2329 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2330 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2331 * optional, if not passed the "<title>" attribute will be
2332 * based on $pageTitle
2334 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2335 $this->setPageTitle( $pageTitle );
2336 if ( $htmlTitle !== false ) {
2337 $this->setHTMLTitle( $htmlTitle );
2339 $this->setRobotPolicy( 'noindex,nofollow' );
2340 $this->setArticleRelated( false );
2341 $this->enableClientCache( false );
2342 $this->mRedirect
= '';
2343 $this->clearSubtitle();
2348 * Output a standard error page
2350 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2351 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2352 * showErrorPage( 'titlemsg', $messageObject );
2353 * showErrorPage( $titleMessageObject, $messageObject );
2355 * @param string|Message $title Message key (string) for page title, or a Message object
2356 * @param string|Message $msg Message key (string) for page text, or a Message object
2357 * @param array $params Message parameters; ignored if $msg is a Message object
2359 public function showErrorPage( $title, $msg, $params = [] ) {
2360 if ( !$title instanceof Message
) {
2361 $title = $this->msg( $title );
2364 $this->prepareErrorPage( $title );
2366 if ( $msg instanceof Message
) {
2367 if ( $params !== [] ) {
2368 trigger_error( 'Argument ignored: $params. The message parameters argument '
2369 . 'is discarded when the $msg argument is a Message object instead of '
2370 . 'a string.', E_USER_NOTICE
);
2372 $this->addHTML( $msg->parseAsBlock() );
2374 $this->addWikiMsgArray( $msg, $params );
2377 $this->returnToMain();
2381 * Output a standard permission error page
2383 * @param array $errors Error message keys
2384 * @param string $action Action that was denied or null if unknown
2386 public function showPermissionsErrorPage( array $errors, $action = null ) {
2387 // For some action (read, edit, create and upload), display a "login to do this action"
2388 // error if all of the following conditions are met:
2389 // 1. the user is not logged in
2390 // 2. the only error is insufficient permissions (i.e. no block or something else)
2391 // 3. the error can be avoided simply by logging in
2392 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2393 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2394 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2395 && ( User
::groupHasPermission( 'user', $action )
2396 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2398 $displayReturnto = null;
2400 # Due to bug 32276, if a user does not have read permissions,
2401 # $this->getTitle() will just give Special:Badtitle, which is
2402 # not especially useful as a returnto parameter. Use the title
2403 # from the request instead, if there was one.
2404 $request = $this->getRequest();
2405 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2406 if ( $action == 'edit' ) {
2407 $msg = 'whitelistedittext';
2408 $displayReturnto = $returnto;
2409 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2410 $msg = 'nocreatetext';
2411 } elseif ( $action == 'upload' ) {
2412 $msg = 'uploadnologintext';
2414 $msg = 'loginreqpagetext';
2415 $displayReturnto = Title
::newMainPage();
2421 $query['returnto'] = $returnto->getPrefixedText();
2423 if ( !$request->wasPosted() ) {
2424 $returntoquery = $request->getValues();
2425 unset( $returntoquery['title'] );
2426 unset( $returntoquery['returnto'] );
2427 unset( $returntoquery['returntoquery'] );
2428 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2431 $loginLink = Linker
::linkKnown(
2432 SpecialPage
::getTitleFor( 'Userlogin' ),
2433 $this->msg( 'loginreqlink' )->escaped(),
2438 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2439 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2441 # Don't return to a page the user can't read otherwise
2442 # we'll end up in a pointless loop
2443 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2444 $this->returnToMain( null, $displayReturnto );
2447 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2448 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2453 * Display an error page indicating that a given version of MediaWiki is
2454 * required to use it
2456 * @param mixed $version The version of MediaWiki needed to use the page
2458 public function versionRequired( $version ) {
2459 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2461 $this->addWikiMsg( 'versionrequiredtext', $version );
2462 $this->returnToMain();
2466 * Format a list of error messages
2468 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2469 * @param string $action Action that was denied or null if unknown
2470 * @return string The wikitext error-messages, formatted into a list.
2472 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2473 if ( $action == null ) {
2474 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2476 $action_desc = $this->msg( "action-$action" )->plain();
2478 'permissionserrorstext-withaction',
2481 )->plain() . "\n\n";
2484 if ( count( $errors ) > 1 ) {
2485 $text .= '<ul class="permissions-errors">' . "\n";
2487 foreach ( $errors as $error ) {
2489 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2494 $text .= "<div class=\"permissions-errors\">\n" .
2495 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2503 * Display a page stating that the Wiki is in read-only mode.
2504 * Should only be called after wfReadOnly() has returned true.
2506 * Historically, this function was used to show the source of the page that the user
2507 * was trying to edit and _also_ permissions error messages. The relevant code was
2508 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2510 * @deprecated since 1.25; throw the exception directly
2511 * @throws ReadOnlyError
2513 public function readOnlyPage() {
2514 if ( func_num_args() > 0 ) {
2515 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2518 throw new ReadOnlyError
;
2522 * Turn off regular page output and return an error response
2523 * for when rate limiting has triggered.
2525 * @deprecated since 1.25; throw the exception directly
2527 public function rateLimited() {
2528 wfDeprecated( __METHOD__
, '1.25' );
2529 throw new ThrottledError
;
2533 * Show a warning about slave lag
2535 * If the lag is higher than $wgSlaveLagCritical seconds,
2536 * then the warning is a bit more obvious. If the lag is
2537 * lower than $wgSlaveLagWarning, then no warning is shown.
2539 * @param int $lag Slave lag
2541 public function showLagWarning( $lag ) {
2542 $config = $this->getConfig();
2543 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2544 $message = $lag < $config->get( 'SlaveLagCritical' )
2547 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2548 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2552 public function showFatalError( $message ) {
2553 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2555 $this->addHTML( $message );
2558 public function showUnexpectedValueError( $name, $val ) {
2559 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2562 public function showFileCopyError( $old, $new ) {
2563 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2566 public function showFileRenameError( $old, $new ) {
2567 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2570 public function showFileDeleteError( $name ) {
2571 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2574 public function showFileNotFoundError( $name ) {
2575 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2579 * Add a "return to" link pointing to a specified title
2581 * @param Title $title Title to link
2582 * @param array $query Query string parameters
2583 * @param string $text Text of the link (input is not escaped)
2584 * @param array $options Options array to pass to Linker
2586 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2587 $link = $this->msg( 'returnto' )->rawParams(
2588 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2589 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2593 * Add a "return to" link pointing to a specified title,
2594 * or the title indicated in the request, or else the main page
2596 * @param mixed $unused
2597 * @param Title|string $returnto Title or String to return to
2598 * @param string $returntoquery Query string for the return to link
2600 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2601 if ( $returnto == null ) {
2602 $returnto = $this->getRequest()->getText( 'returnto' );
2605 if ( $returntoquery == null ) {
2606 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2609 if ( $returnto === '' ) {
2610 $returnto = Title
::newMainPage();
2613 if ( is_object( $returnto ) ) {
2614 $titleObj = $returnto;
2616 $titleObj = Title
::newFromText( $returnto );
2618 if ( !is_object( $titleObj ) ) {
2619 $titleObj = Title
::newMainPage();
2622 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2626 * @param Skin $sk The given Skin
2627 * @param bool $includeStyle Unused
2628 * @return string The doctype, opening "<html>", and head element.
2630 public function headElement( Skin
$sk, $includeStyle = true ) {
2633 $userdir = $this->getLanguage()->getDir();
2634 $sitedir = $wgContLang->getDir();
2636 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2638 if ( $this->getHTMLTitle() == '' ) {
2639 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2642 $openHead = Html
::openElement( 'head' );
2644 # Don't bother with the newline if $head == ''
2645 $ret .= "$openHead\n";
2648 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2649 // Add <meta charset="UTF-8">
2650 // This should be before <title> since it defines the charset used by
2651 // text including the text inside <title>.
2652 // The spec recommends defining XHTML5's charset using the XML declaration
2654 // Our XML declaration is output by Html::htmlHeader.
2655 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2656 // http://www.whatwg.org/html/semantics.html#charset
2657 $ret .= Html
::element( 'meta', [ 'charset' => 'UTF-8' ] ) . "\n";
2660 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2661 $ret .= $this->getInlineHeadScripts() . "\n";
2662 $ret .= $this->buildCssLinks() . "\n";
2663 $ret .= $this->getExternalHeadScripts() . "\n";
2665 foreach ( $this->getHeadLinksArray() as $item ) {
2666 $ret .= $item . "\n";
2669 foreach ( $this->mHeadItems
as $item ) {
2670 $ret .= $item . "\n";
2673 $closeHead = Html
::closeElement( 'head' );
2675 $ret .= "$closeHead\n";
2679 $bodyClasses[] = 'mediawiki';
2681 # Classes for LTR/RTL directionality support
2682 $bodyClasses[] = $userdir;
2683 $bodyClasses[] = "sitedir-$sitedir";
2685 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2686 # A <body> class is probably not the best way to do this . . .
2687 $bodyClasses[] = 'capitalize-all-nouns';
2690 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2691 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2693 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2696 // While the implode() is not strictly needed, it's used for backwards compatibility
2697 // (this used to be built as a string and hooks likely still expect that).
2698 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2700 // Allow skins and extensions to add body attributes they need
2701 $sk->addToBodyAttributes( $this, $bodyAttrs );
2702 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2704 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2710 * Get a ResourceLoader object associated with this OutputPage
2712 * @return ResourceLoader
2714 public function getResourceLoader() {
2715 if ( is_null( $this->mResourceLoader
) ) {
2716 $this->mResourceLoader
= new ResourceLoader(
2718 LoggerFactory
::getInstance( 'resourceloader' )
2721 return $this->mResourceLoader
;
2725 * Construct neccecary html and loader preset states to load modules on a page.
2727 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2729 * @param array|string $modules One or more module names
2730 * @param string $only ResourceLoaderModule TYPE_ class constant
2731 * @param array $extraQuery [optional] Array with extra query parameters for the request
2732 * @return array A list of HTML strings and array of client loader preset states
2734 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2735 $modules = (array)$modules;
2738 // List of html strings
2740 // Associative array of module names and their states
2744 if ( !count( $modules ) ) {
2748 if ( count( $modules ) > 1 ) {
2749 // Remove duplicate module requests
2750 $modules = array_unique( $modules );
2751 // Sort module names so requests are more uniform
2754 if ( ResourceLoader
::inDebugMode() ) {
2755 // Recursively call us for every item
2756 foreach ( $modules as $name ) {
2757 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2758 $links['html'] = array_merge( $links['html'], $link['html'] );
2759 $links['states'] +
= $link['states'];
2765 if ( !is_null( $this->mTarget
) ) {
2766 $extraQuery['target'] = $this->mTarget
;
2769 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2770 $sortedModules = [];
2771 $resourceLoader = $this->getResourceLoader();
2772 foreach ( $modules as $name ) {
2773 $module = $resourceLoader->getModule( $name );
2774 # Check that we're allowed to include this module on this page
2776 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2777 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2778 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2779 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2780 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2781 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2782 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2787 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2790 foreach ( $sortedModules as $source => $groups ) {
2791 foreach ( $groups as $group => $grpModules ) {
2792 // Special handling for user-specific groups
2794 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2795 $user = $this->getUser()->getName();
2798 // Create a fake request based on the one we are about to make so modules return
2799 // correct timestamp and emptiness data
2800 $query = ResourceLoader
::makeLoaderQuery(
2801 [], // modules; not determined yet
2802 $this->getLanguage()->getCode(),
2803 $this->getSkin()->getSkinName(),
2805 null, // version; not determined yet
2806 ResourceLoader
::inDebugMode(),
2807 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2808 $this->isPrintable(),
2809 $this->getRequest()->getBool( 'handheld' ),
2812 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2814 // Extract modules that know they're empty and see if we have one or more
2817 foreach ( $grpModules as $key => $module ) {
2818 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2819 // If we're only getting the styles, we don't need to do anything for empty modules.
2820 if ( $module->isKnownEmpty( $context ) ) {
2821 unset( $grpModules[$key] );
2822 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2823 $links['states'][$key] = 'ready';
2827 $isRaw |
= $module->isRaw();
2830 // If there are no non-empty modules, skip this group
2831 if ( count( $grpModules ) === 0 ) {
2835 // Inline private modules. These can't be loaded through load.php for security
2836 // reasons, see bug 34907. Note that these modules should be loaded from
2837 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2838 // properly use them as dependencies (bug 30914)
2839 if ( $group === 'private' ) {
2840 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2841 $links['html'][] = Html
::inlineStyle(
2842 $resourceLoader->makeModuleResponse( $context, $grpModules )
2845 $links['html'][] = ResourceLoader
::makeInlineScript(
2846 $resourceLoader->makeModuleResponse( $context, $grpModules )
2852 // Special handling for the user group; because users might change their stuff
2853 // on-wiki like user pages, or user preferences; we need to find the highest
2854 // timestamp of these user-changeable modules so we can ensure cache misses on change
2855 // This should NOT be done for the site group (bug 27564) because anons get that too
2856 // and we shouldn't be putting timestamps in CDN-cached HTML
2858 if ( $group === 'user' ) {
2859 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2862 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2863 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2864 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2866 // Automatically select style/script elements
2867 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2868 $link = Html
::linkedStyle( $url );
2870 if ( $context->getRaw() ||
$isRaw ) {
2871 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2872 $link = Html
::element( 'script', [
2873 // In SpecialJavaScriptTest, QUnit must load synchronous
2874 'async' => !isset( $extraQuery['sync'] ),
2878 $link = ResourceLoader
::makeInlineScript(
2879 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
2883 // For modules requested directly in the html via <script> or mw.loader.load
2884 // tell mw.loader they are being loading to prevent duplicate requests.
2885 foreach ( $grpModules as $key => $module ) {
2886 // Don't output state=loading for the startup module.
2887 if ( $key !== 'startup' ) {
2888 $links['states'][$key] = 'loading';
2893 if ( $group == 'noscript' ) {
2894 $links['html'][] = Html
::rawElement( 'noscript', [], $link );
2896 $links['html'][] = $link;
2905 * Build html output from an array of links from makeResourceLoaderLink.
2906 * @param array $links
2907 * @return string HTML
2909 protected static function getHtmlFromLoaderLinks( array $links ) {
2912 foreach ( $links as $link ) {
2913 if ( !is_array( $link ) ) {
2916 $html = array_merge( $html, $link['html'] );
2917 $states +
= $link['states'];
2920 // Filter out empty values
2921 $html = array_filter( $html, 'strlen' );
2923 if ( count( $states ) ) {
2924 array_unshift( $html, ResourceLoader
::makeInlineScript(
2925 ResourceLoader
::makeLoaderStateScript( $states )
2929 return WrappedString
::join( "\n", $html );
2933 * JS stuff to put in the "<head>". This is the startup module, config
2934 * vars and modules marked with position 'top'
2936 * @return string HTML fragment
2938 function getHeadScripts() {
2939 return $this->getInlineHeadScripts() . $this->getExternalHeadScripts();
2943 * <script src="..."> tags for "<head>". This is the startup module
2944 * and other modules marked with position 'top'.
2946 * @return string HTML fragment
2948 function getExternalHeadScripts() {
2951 // Startup - this provides the client with the module
2952 // manifest and loads jquery and mediawiki base modules
2953 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2955 return self
::getHtmlFromLoaderLinks( $links );
2959 * <script>...</script> tags to put in "<head>".
2961 * @return string HTML fragment
2963 function getInlineHeadScripts() {
2966 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
2967 // Must be done synchronously on every page to avoid flashes of wrong content.
2968 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
2969 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
2970 // For the performance benefit of the majority, this is added unconditionally here and is
2971 // then fixed up by the startup module for unsupported browsers.
2972 $links[] = Html
::inlineScript(
2973 'document.documentElement.className = document.documentElement.className'
2974 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
2977 // Load config before anything else
2978 $links[] = ResourceLoader
::makeInlineScript(
2979 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2982 // Load embeddable private modules before any loader links
2983 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2984 // in mw.loader.implement() calls and deferred until mw.user is available
2985 $embedScripts = [ 'user.options' ];
2986 $links[] = $this->makeResourceLoaderLink(
2988 ResourceLoaderModule
::TYPE_COMBINED
2990 // Separate user.tokens as otherwise caching will be allowed (T84960)
2991 $links[] = $this->makeResourceLoaderLink(
2993 ResourceLoaderModule
::TYPE_COMBINED
2996 // Modules requests - let the client calculate dependencies and batch requests as it likes
2997 // Only load modules that have marked themselves for loading at the top
2998 $modules = $this->getModules( true, 'top' );
3000 $links[] = ResourceLoader
::makeInlineScript(
3001 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3005 // "Scripts only" modules marked for top inclusion
3006 $links[] = $this->makeResourceLoaderLink(
3007 $this->getModuleScripts( true, 'top' ),
3008 ResourceLoaderModule
::TYPE_SCRIPTS
3011 return self
::getHtmlFromLoaderLinks( $links );
3015 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3016 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3017 * site JS, and user JS.
3019 * @param bool $unused Previously used to let this method change its output based
3020 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3023 function getScriptsForBottomQueue( $unused = null ) {
3024 // Scripts "only" requests marked for bottom inclusion
3025 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3028 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3029 ResourceLoaderModule
::TYPE_SCRIPTS
3032 // Modules requests - let the client calculate dependencies and batch requests as it likes
3033 // Only load modules that have marked themselves for loading at the bottom
3034 $modules = $this->getModules( true, 'bottom' );
3036 $links[] = ResourceLoader
::makeInlineScript(
3037 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3042 $links[] = $this->mScripts
;
3044 // Add user JS if enabled
3045 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3046 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3047 if ( $this->getConfig()->get( 'AllowUserJs' )
3048 && $this->getUser()->isLoggedIn()
3049 && $this->getTitle()
3050 && $this->getTitle()->isJsSubpage()
3051 && $this->userCanPreview()
3053 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3054 // and include the draft contents as a raw script instead.
3055 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3056 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3058 // Load the previewed JS
3059 $links[] = ResourceLoader
::makeInlineScript(
3060 Xml
::encodeJsCall( 'mw.loader.using', [
3064 . Xml
::encodeJsCall( '$.globalEval', [
3065 $this->getRequest()->getText( 'wpTextbox1' )
3072 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3073 // asynchronously and may arrive *after* the inline script here. So the previewed code
3074 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3075 // Similarly, when previewing ./common.js and the user module does arrive first,
3076 // it will arrive without common.js and the inline script runs after.
3077 // Thus running common after the excluded subpage.
3079 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3080 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3083 return self
::getHtmlFromLoaderLinks( $links );
3087 * JS stuff to put at the bottom of the "<body>"
3090 function getBottomScripts() {
3091 return $this->getScriptsForBottomQueue();
3095 * Get the javascript config vars to include on this page
3097 * @return array Array of javascript config vars
3100 public function getJsConfigVars() {
3101 return $this->mJsConfigVars
;
3105 * Add one or more variables to be set in mw.config in JavaScript
3107 * @param string|array $keys Key or array of key/value pairs
3108 * @param mixed $value [optional] Value of the configuration variable
3110 public function addJsConfigVars( $keys, $value = null ) {
3111 if ( is_array( $keys ) ) {
3112 foreach ( $keys as $key => $value ) {
3113 $this->mJsConfigVars
[$key] = $value;
3118 $this->mJsConfigVars
[$keys] = $value;
3122 * Get an array containing the variables to be set in mw.config in JavaScript.
3124 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3125 * - in other words, page-independent/site-wide variables (without state).
3126 * You will only be adding bloat to the html page and causing page caches to
3127 * have to be purged on configuration changes.
3130 public function getJSVars() {
3135 $canonicalSpecialPageName = false; # bug 21115
3137 $title = $this->getTitle();
3138 $ns = $title->getNamespace();
3139 $canonicalNamespace = MWNamespace
::exists( $ns )
3140 ? MWNamespace
::getCanonicalName( $ns )
3141 : $title->getNsText();
3143 $sk = $this->getSkin();
3144 // Get the relevant title so that AJAX features can use the correct page name
3145 // when making API requests from certain special pages (bug 34972).
3146 $relevantTitle = $sk->getRelevantTitle();
3147 $relevantUser = $sk->getRelevantUser();
3149 if ( $ns == NS_SPECIAL
) {
3150 list( $canonicalSpecialPageName, /*...*/ ) =
3151 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3152 } elseif ( $this->canUseWikiPage() ) {
3153 $wikiPage = $this->getWikiPage();
3154 $curRevisionId = $wikiPage->getLatest();
3155 $articleId = $wikiPage->getId();
3158 $lang = $title->getPageViewLanguage();
3160 // Pre-process information
3161 $separatorTransTable = $lang->separatorTransformTable();
3162 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3163 $compactSeparatorTransTable = [
3164 implode( "\t", array_keys( $separatorTransTable ) ),
3165 implode( "\t", $separatorTransTable ),
3167 $digitTransTable = $lang->digitTransformTable();
3168 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3169 $compactDigitTransTable = [
3170 implode( "\t", array_keys( $digitTransTable ) ),
3171 implode( "\t", $digitTransTable ),
3174 $user = $this->getUser();
3177 'wgCanonicalNamespace' => $canonicalNamespace,
3178 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3179 'wgNamespaceNumber' => $title->getNamespace(),
3180 'wgPageName' => $title->getPrefixedDBkey(),
3181 'wgTitle' => $title->getText(),
3182 'wgCurRevisionId' => $curRevisionId,
3183 'wgRevisionId' => (int)$this->getRevisionId(),
3184 'wgArticleId' => $articleId,
3185 'wgIsArticle' => $this->isArticle(),
3186 'wgIsRedirect' => $title->isRedirect(),
3187 'wgAction' => Action
::getActionName( $this->getContext() ),
3188 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3189 'wgUserGroups' => $user->getEffectiveGroups(),
3190 'wgCategories' => $this->getCategories(),
3191 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3192 'wgPageContentLanguage' => $lang->getCode(),
3193 'wgPageContentModel' => $title->getContentModel(),
3194 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3195 'wgDigitTransformTable' => $compactDigitTransTable,
3196 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3197 'wgMonthNames' => $lang->getMonthNamesArray(),
3198 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3199 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3200 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3201 'wgRequestId' => WebRequest
::getRequestId(),
3204 if ( $user->isLoggedIn() ) {
3205 $vars['wgUserId'] = $user->getId();
3206 $vars['wgUserEditCount'] = $user->getEditCount();
3207 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3208 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3209 // Get the revision ID of the oldest new message on the user's talk
3210 // page. This can be used for constructing new message alerts on
3212 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3215 if ( $wgContLang->hasVariants() ) {
3216 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3218 // Same test as SkinTemplate
3219 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3220 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3222 foreach ( $title->getRestrictionTypes() as $type ) {
3223 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3226 if ( $title->isMainPage() ) {
3227 $vars['wgIsMainPage'] = true;
3230 if ( $this->mRedirectedFrom
) {
3231 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3234 if ( $relevantUser ) {
3235 $vars['wgRelevantUserName'] = $relevantUser->getName();
3238 // Allow extensions to add their custom variables to the mw.config map.
3239 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3240 // page-dependant but site-wide (without state).
3241 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3242 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3244 // Merge in variables from addJsConfigVars last
3245 return array_merge( $vars, $this->getJsConfigVars() );
3249 * To make it harder for someone to slip a user a fake
3250 * user-JavaScript or user-CSS preview, a random token
3251 * is associated with the login session. If it's not
3252 * passed back with the preview request, we won't render
3257 public function userCanPreview() {
3258 $request = $this->getRequest();
3260 $request->getVal( 'action' ) !== 'submit' ||
3261 !$request->getCheck( 'wpPreview' ) ||
3262 !$request->wasPosted()
3267 $user = $this->getUser();
3268 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3272 $title = $this->getTitle();
3273 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3276 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3277 // Don't execute another user's CSS or JS on preview (T85855)
3281 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3282 if ( count( $errors ) !== 0 ) {
3290 * @return array Array in format "link name or number => 'link html'".
3292 public function getHeadLinksArray() {
3296 $config = $this->getConfig();
3298 $canonicalUrl = $this->mCanonicalUrl
;
3300 $tags['meta-generator'] = Html
::element( 'meta', [
3301 'name' => 'generator',
3302 'content' => "MediaWiki $wgVersion",
3305 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3306 $tags['meta-referrer'] = Html
::element( 'meta', [
3307 'name' => 'referrer',
3308 'content' => $config->get( 'ReferrerPolicy' )
3312 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3313 if ( $p !== 'index,follow' ) {
3314 // http://www.robotstxt.org/wc/meta-user.html
3315 // Only show if it's different from the default robots policy
3316 $tags['meta-robots'] = Html
::element( 'meta', [
3322 foreach ( $this->mMetatags
as $tag ) {
3323 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3325 $tag[0] = substr( $tag[0], 5 );
3329 $tagName = "meta-{$tag[0]}";
3330 if ( isset( $tags[$tagName] ) ) {
3331 $tagName .= $tag[1];
3333 $tags[$tagName] = Html
::element( 'meta',
3336 'content' => $tag[1]
3341 foreach ( $this->mLinktags
as $tag ) {
3342 $tags[] = Html
::element( 'link', $tag );
3345 # Universal edit button
3346 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3347 $user = $this->getUser();
3348 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3349 && ( $this->getTitle()->exists() ||
3350 $this->getTitle()->quickUserCan( 'create', $user ) )
3352 // Original UniversalEditButton
3353 $msg = $this->msg( 'edit' )->text();
3354 $tags['universal-edit-button'] = Html
::element( 'link', [
3355 'rel' => 'alternate',
3356 'type' => 'application/x-wiki',
3358 'href' => $this->getTitle()->getEditURL(),
3360 // Alternate edit link
3361 $tags['alternative-edit'] = Html
::element( 'link', [
3364 'href' => $this->getTitle()->getEditURL(),
3369 # Generally the order of the favicon and apple-touch-icon links
3370 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3371 # uses whichever one appears later in the HTML source. Make sure
3372 # apple-touch-icon is specified first to avoid this.
3373 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3374 $tags['apple-touch-icon'] = Html
::element( 'link', [
3375 'rel' => 'apple-touch-icon',
3376 'href' => $config->get( 'AppleTouchIcon' )
3380 if ( $config->get( 'Favicon' ) !== false ) {
3381 $tags['favicon'] = Html
::element( 'link', [
3382 'rel' => 'shortcut icon',
3383 'href' => $config->get( 'Favicon' )
3387 # OpenSearch description link
3388 $tags['opensearch'] = Html
::element( 'link', [
3390 'type' => 'application/opensearchdescription+xml',
3391 'href' => wfScript( 'opensearch_desc' ),
3392 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3395 if ( $config->get( 'EnableAPI' ) ) {
3396 # Real Simple Discovery link, provides auto-discovery information
3397 # for the MediaWiki API (and potentially additional custom API
3398 # support such as WordPress or Twitter-compatible APIs for a
3399 # blogging extension, etc)
3400 $tags['rsd'] = Html
::element( 'link', [
3402 'type' => 'application/rsd+xml',
3403 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3404 // Whether RSD accepts relative or protocol-relative URLs is completely
3405 // undocumented, though.
3406 'href' => wfExpandUrl( wfAppendQuery(
3408 [ 'action' => 'rsd' ] ),
3415 if ( !$config->get( 'DisableLangConversion' ) ) {
3416 $lang = $this->getTitle()->getPageLanguage();
3417 if ( $lang->hasVariants() ) {
3418 $variants = $lang->getVariants();
3419 foreach ( $variants as $variant ) {
3420 $tags["variant-$variant"] = Html
::element( 'link', [
3421 'rel' => 'alternate',
3422 'hreflang' => wfBCP47( $variant ),
3423 'href' => $this->getTitle()->getLocalURL(
3424 [ 'variant' => $variant ] )
3428 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3429 $tags["variant-x-default"] = Html
::element( 'link', [
3430 'rel' => 'alternate',
3431 'hreflang' => 'x-default',
3432 'href' => $this->getTitle()->getLocalURL() ] );
3437 if ( $this->copyrightUrl
!== null ) {
3438 $copyright = $this->copyrightUrl
;
3441 if ( $config->get( 'RightsPage' ) ) {
3442 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3445 $copyright = $copy->getLocalURL();
3449 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3450 $copyright = $config->get( 'RightsUrl' );
3455 $tags['copyright'] = Html
::element( 'link', [
3456 'rel' => 'copyright',
3457 'href' => $copyright ]
3462 if ( $config->get( 'Feed' ) ) {
3465 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3466 # Use the page name for the title. In principle, this could
3467 # lead to issues with having the same name for different feeds
3468 # corresponding to the same page, but we can't avoid that at
3471 $feedLinks[] = $this->feedLink(
3474 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3476 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3481 # Recent changes feed should appear on every page (except recentchanges,
3482 # that would be redundant). Put it after the per-page feed to avoid
3483 # changing existing behavior. It's still available, probably via a
3484 # menu in your browser. Some sites might have a different feed they'd
3485 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3486 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3487 # If so, use it instead.
3488 $sitename = $config->get( 'Sitename' );
3489 if ( $config->get( 'OverrideSiteFeed' ) ) {
3490 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3491 // Note, this->feedLink escapes the url.
3492 $feedLinks[] = $this->feedLink(
3495 $this->msg( "site-{$type}-feed", $sitename )->text()
3498 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3499 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3500 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3501 $feedLinks[] = $this->feedLink(
3503 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3504 # For grep: 'site-rss-feed', 'site-atom-feed'
3505 $this->msg( "site-{$format}-feed", $sitename )->text()
3510 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3511 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3512 # use OutputPage::addFeedLink() instead.
3513 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3515 $tags +
= $feedLinks;
3519 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3520 if ( $canonicalUrl !== false ) {
3521 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3523 if ( $this->isArticleRelated() ) {
3524 // This affects all requests where "setArticleRelated" is true. This is
3525 // typically all requests that show content (query title, curid, oldid, diff),
3526 // and all wikipage actions (edit, delete, purge, info, history etc.).
3527 // It does not apply to File pages and Special pages.
3528 // 'history' and 'info' actions address page metadata rather than the page
3529 // content itself, so they may not be canonicalized to the view page url.
3530 // TODO: this ought to be better encapsulated in the Action class.
3531 $action = Action
::getActionName( $this->getContext() );
3532 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3533 $query = "action={$action}";
3537 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3539 $reqUrl = $this->getRequest()->getRequestURL();
3540 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3544 if ( $canonicalUrl !== false ) {
3545 $tags[] = Html
::element( 'link', [
3546 'rel' => 'canonical',
3547 'href' => $canonicalUrl
3555 * @return string HTML tag links to be put in the header.
3556 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3557 * OutputPage::getHeadLinksArray directly.
3559 public function getHeadLinks() {
3560 wfDeprecated( __METHOD__
, '1.24' );
3561 return implode( "\n", $this->getHeadLinksArray() );
3565 * Generate a "<link rel/>" for a feed.
3567 * @param string $type Feed type
3568 * @param string $url URL to the feed
3569 * @param string $text Value of the "title" attribute
3570 * @return string HTML fragment
3572 private function feedLink( $type, $url, $text ) {
3573 return Html
::element( 'link', [
3574 'rel' => 'alternate',
3575 'type' => "application/$type+xml",
3582 * Add a local or specified stylesheet, with the given media options.
3583 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3585 * @param string $style URL to the file
3586 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3587 * @param string $condition For IE conditional comments, specifying an IE version
3588 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3590 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3593 $options['media'] = $media;
3596 $options['condition'] = $condition;
3599 $options['dir'] = $dir;
3601 $this->styles
[$style] = $options;
3605 * Adds inline CSS styles
3606 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3608 * @param mixed $style_css Inline CSS
3609 * @param string $flip Set to 'flip' to flip the CSS if needed
3611 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3612 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3613 # If wanted, and the interface is right-to-left, flip the CSS
3614 $style_css = CSSJanus
::transform( $style_css, true, false );
3616 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3620 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3621 * These will be applied to various media & IE conditionals.
3625 public function buildCssLinks() {
3628 $this->getSkin()->setupSkinUserCss( $this );
3630 // Add ResourceLoader styles
3631 // Split the styles into these groups
3640 $otherTags = []; // Tags to append after the normal <link> tags
3641 $resourceLoader = $this->getResourceLoader();
3643 $moduleStyles = $this->getModuleStyles();
3645 // Per-site custom styles
3646 $moduleStyles[] = 'site.styles';
3647 $moduleStyles[] = 'noscript';
3649 // Per-user custom styles
3650 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3651 && $this->userCanPreview()
3653 // We're on a preview of a CSS subpage
3654 // Exclude this page from the user module in case it's in there (bug 26283)
3655 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3656 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3658 $otherTags = array_merge( $otherTags, $link['html'] );
3660 // Load the previewed CSS
3661 // If needed, Janus it first. This is user-supplied CSS, so it's
3662 // assumed to be right for the content language directionality.
3663 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3664 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3665 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3667 $otherTags[] = Html
::inlineStyle( $previewedCSS );
3669 // Load the user styles normally
3670 $moduleStyles[] = 'user';
3673 // Per-user preference styles
3674 $moduleStyles[] = 'user.cssprefs';
3676 foreach ( $moduleStyles as $name ) {
3677 $module = $resourceLoader->getModule( $name );
3681 if ( $name === 'site.styles' ) {
3682 // HACK: The site module shouldn't be fragmented with a cache group and
3683 // http request. But in order to ensure its styles are separated and after the
3684 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3685 // The scripts remain ungrouped and rides the bottom queue.
3686 $styles['site'][] = $name;
3689 $group = $module->getGroup();
3690 // Modules in groups other than the ones needing special treatment
3691 // (see $styles assignment)
3692 // will be placed in the "other" style category.
3693 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3696 // We want site, private and user styles to override dynamically added
3697 // styles from modules, but we want dynamically added styles to override
3698 // statically added styles from other modules. So the order has to be
3699 // other, dynamic, site, private, user. Add statically added styles for
3701 $links[] = $this->makeResourceLoaderLink(
3703 ResourceLoaderModule
::TYPE_STYLES
3705 // Add normal styles added through addStyle()/addInlineStyle() here
3706 $links[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3707 // Add marker tag to mark the place where the client-side
3708 // loader should inject dynamic styles
3709 // We use a <meta> tag with a made-up name for this because that's valid HTML
3710 $links[] = Html
::element(
3712 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3715 // Add site-specific and user-specific styles
3716 // 'private' at present only contains user.options, so put that before 'user'
3717 // Any future private modules will likely have a similar user-specific character
3718 foreach ( [ 'site', 'noscript', 'private', 'user' ] as $group ) {
3719 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3720 ResourceLoaderModule
::TYPE_STYLES
3724 // Add stuff in $otherTags (previewed user CSS if applicable)
3725 return self
::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3731 public function buildCssLinksArray() {
3734 // Add any extension CSS
3735 foreach ( $this->mExtStyles
as $url ) {
3736 $this->addStyle( $url );
3738 $this->mExtStyles
= [];
3740 foreach ( $this->styles
as $file => $options ) {
3741 $link = $this->styleLink( $file, $options );
3743 $links[$file] = $link;
3750 * Generate \<link\> tags for stylesheets
3752 * @param string $style URL to the file
3753 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3754 * @return string HTML fragment
3756 protected function styleLink( $style, array $options ) {
3757 if ( isset( $options['dir'] ) ) {
3758 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3763 if ( isset( $options['media'] ) ) {
3764 $media = self
::transformCssMedia( $options['media'] );
3765 if ( is_null( $media ) ) {
3772 if ( substr( $style, 0, 1 ) == '/' ||
3773 substr( $style, 0, 5 ) == 'http:' ||
3774 substr( $style, 0, 6 ) == 'https:' ) {
3777 $config = $this->getConfig();
3778 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3779 $config->get( 'StyleVersion' );
3782 $link = Html
::linkedStyle( $url, $media );
3784 if ( isset( $options['condition'] ) ) {
3785 $condition = htmlspecialchars( $options['condition'] );
3786 $link = "<!--[if $condition]>$link<![endif]-->";
3792 * Transform path to web-accessible static resource.
3794 * This is used to add a validation hash as query string.
3795 * This aids various behaviors:
3797 * - Put long Cache-Control max-age headers on responses for improved
3798 * cache performance.
3799 * - Get the correct version of a file as expected by the current page.
3800 * - Instantly get the updated version of a file after deployment.
3802 * Avoid using this for urls included in HTML as otherwise clients may get different
3803 * versions of a resource when navigating the site depending on when the page was cached.
3804 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3805 * an external stylesheet).
3808 * @param Config $config
3809 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3810 * @return string URL
3812 public static function transformResourcePath( Config
$config, $path ) {
3814 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3815 if ( $remotePathPrefix === '' ) {
3816 // The configured base path is required to be empty string for
3817 // wikis in the domain root
3820 $remotePath = $remotePathPrefix;
3822 if ( strpos( $path, $remotePath ) !== 0 ) {
3823 // Path is outside wgResourceBasePath, ignore.
3826 $path = RelPath\
getRelativePath( $path, $remotePath );
3827 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3831 * Utility method for transformResourceFilePath().
3833 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3836 * @param string $remotePath URL path prefix that points to $localPath
3837 * @param string $localPath File directory exposed at $remotePath
3838 * @param string $file Path to target file relative to $localPath
3839 * @return string URL
3841 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3842 $hash = md5_file( "$localPath/$file" );
3843 if ( $hash === false ) {
3844 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3847 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3851 * Transform "media" attribute based on request parameters
3853 * @param string $media Current value of the "media" attribute
3854 * @return string Modified value of the "media" attribute, or null to skip
3857 public static function transformCssMedia( $media ) {
3860 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3861 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3863 // Switch in on-screen display for media testing
3865 'printable' => 'print',
3866 'handheld' => 'handheld',
3868 foreach ( $switches as $switch => $targetMedia ) {
3869 if ( $wgRequest->getBool( $switch ) ) {
3870 if ( $media == $targetMedia ) {
3872 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3873 /* This regex will not attempt to understand a comma-separated media_query_list
3875 * Example supported values for $media:
3876 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3877 * Example NOT supported value for $media:
3878 * '3d-glasses, screen, print and resolution > 90dpi'
3880 * If it's a print request, we never want any kind of screen stylesheets
3881 * If it's a handheld request (currently the only other choice with a switch),
3882 * we don't want simple 'screen' but we might want screen queries that
3883 * have a max-width or something, so we'll pass all others on and let the
3884 * client do the query.
3886 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3897 * Add a wikitext-formatted message to the output.
3898 * This is equivalent to:
3900 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3902 public function addWikiMsg( /*...*/ ) {
3903 $args = func_get_args();
3904 $name = array_shift( $args );
3905 $this->addWikiMsgArray( $name, $args );
3909 * Add a wikitext-formatted message to the output.
3910 * Like addWikiMsg() except the parameters are taken as an array
3911 * instead of a variable argument list.
3913 * @param string $name
3914 * @param array $args
3916 public function addWikiMsgArray( $name, $args ) {
3917 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3921 * This function takes a number of message/argument specifications, wraps them in
3922 * some overall structure, and then parses the result and adds it to the output.
3924 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3925 * and so on. The subsequent arguments may be either
3926 * 1) strings, in which case they are message names, or
3927 * 2) arrays, in which case, within each array, the first element is the message
3928 * name, and subsequent elements are the parameters to that message.
3930 * Don't use this for messages that are not in the user's interface language.
3934 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3938 * $wgOut->addWikiText( "<div class='error'>\n"
3939 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3941 * The newline after the opening div is needed in some wikitext. See bug 19226.
3943 * @param string $wrap
3945 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3946 $msgSpecs = func_get_args();
3947 array_shift( $msgSpecs );
3948 $msgSpecs = array_values( $msgSpecs );
3950 foreach ( $msgSpecs as $n => $spec ) {
3951 if ( is_array( $spec ) ) {
3953 $name = array_shift( $args );
3954 if ( isset( $args['options'] ) ) {
3955 unset( $args['options'] );
3957 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3965 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3967 $this->addWikiText( $s );
3971 * Enables/disables TOC, doesn't override __NOTOC__
3975 public function enableTOC( $flag = true ) {
3976 $this->mEnableTOC
= $flag;
3983 public function isTOCEnabled() {
3984 return $this->mEnableTOC
;
3988 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3992 public function enableSectionEditLinks( $flag = true ) {
3993 $this->mEnableSectionEditLinks
= $flag;
4000 public function sectionEditLinksEnabled() {
4001 return $this->mEnableSectionEditLinks
;
4005 * Helper function to setup the PHP implementation of OOUI to use in this request.
4008 * @param String $skinName The Skin name to determine the correct OOUI theme
4009 * @param String $dir Language direction
4011 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4012 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
4013 // Make keys (skin names) lowercase for case-insensitive matching.
4014 $themes = array_change_key_case( $themes, CASE_LOWER
);
4015 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
4016 // For example, 'OOUI\MediaWikiTheme'.
4017 $themeClass = "OOUI\\{$theme}Theme";
4018 OOUI\Theme
::setSingleton( new $themeClass() );
4019 OOUI\Element
::setDefaultDir( $dir );
4023 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4024 * MediaWiki and this OutputPage instance.
4028 public function enableOOUI() {
4030 strtolower( $this->getSkin()->getSkinName() ),
4031 $this->getLanguage()->getDir()
4033 $this->addModuleStyles( [
4034 'oojs-ui-core.styles',
4035 'oojs-ui.styles.icons',
4036 'oojs-ui.styles.indicators',
4037 'oojs-ui.styles.textures',
4038 'mediawiki.widgets.styles',
4040 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
4041 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
4042 $this->addMeta( 'X-OOUI-PHP', '1' );