3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use WrappedString\WrappedString
;
27 use WrappedString\WrappedStringList
;
30 * This class should be covered by a general architecture document which does
31 * not exist as of January 2011. This is one of the Core classes and should
32 * be read at least once by any new developers.
34 * This class is used to prepare the final rendering. A skin is then
35 * applied to the output parameters (links, javascript, html, categories ...).
37 * @todo FIXME: Another class handles sending the whole page to the client.
39 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
44 class OutputPage
extends ContextSource
{
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
49 protected $mLinktags = [];
52 protected $mCanonicalUrl = false;
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
58 protected $mExtStyles = [];
61 * @var string Should be private - has getter and setter. Contains
63 public $mPagetitle = '';
66 * @var string Contains all of the "<body>" content. Should be private we
67 * got set/get accessors and the append() method.
69 public $mBodytext = '';
71 /** @var string Stores contents of "<title>" tag */
72 private $mHTMLtitle = '';
75 * @var bool Is the displayed content related to the source of the
76 * corresponding wiki article.
78 private $mIsarticle = false;
80 /** @var bool Stores "article flag" toggle. */
81 private $mIsArticleRelated = true;
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
87 private $mPrintable = false;
90 * @var array Contains the page subtitle. Special pages usually have some
91 * links here. Don't confuse with site subtitle added by skins.
93 private $mSubtitle = [];
96 public $mRedirect = '';
99 protected $mStatusCode;
102 * @var string Used for sending cache control.
103 * The whole caching system should probably be moved into its own class.
105 protected $mLastModified = '';
108 protected $mCategoryLinks = [];
111 protected $mCategories = [
117 protected $mIndicators = [];
119 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
120 private $mLanguageLinks = [];
123 * Used for JavaScript (predates ResourceLoader)
124 * @todo We should split JS / CSS.
125 * mScripts content is inserted as is in "<head>" by Skin. This might
126 * contain either a link to a stylesheet or inline CSS.
128 private $mScripts = '';
130 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
131 protected $mInlineStyles = '';
134 * @var string Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 public $mPageLinkTitle = '';
139 /** @var array Array of elements in "<head>". Parser might add its own headers! */
140 protected $mHeadItems = [];
143 protected $mModules = [];
146 protected $mModuleScripts = [];
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
161 private $rlUserModuleState;
164 private $rlExemptStyleModules;
167 protected $mJsConfigVars = [];
170 protected $mTemplateIds = [];
173 protected $mImageTimeKeys = [];
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = [
186 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = [];
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
217 protected $mNewSectionLink = false;
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF
;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
248 private $mRevisionTimestamp = null;
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = [];
263 private $mIndexPolicy = 'index';
264 private $mFollowPolicy = 'follow';
265 private $mVaryHeader = [
266 'Accept-Encoding' => [ 'match=gzip' ],
270 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
275 private $mRedirectedFrom = null;
278 * Additional key => value data
280 private $mProperties = [];
283 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
285 private $mTarget = null;
288 * @var bool Whether parser output should contain table of contents
290 private $mEnableTOC = true;
293 * @var bool Whether parser output should contain section edit links
295 private $mEnableSectionEditLinks = true;
298 * @var string|null The URL to send in a <link> element with rel=copyright
300 private $copyrightUrl;
302 /** @var array Profiling data */
303 private $limitReportJSData = [];
306 * Constructor for OutputPage. This should not be called directly.
307 * Instead a new RequestContext should be created and it will implicitly create
308 * a OutputPage tied to that context.
309 * @param IContextSource|null $context
311 function __construct( IContextSource
$context = null ) {
312 if ( $context === null ) {
313 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
314 wfDeprecated( __METHOD__
, '1.18' );
316 $this->setContext( $context );
321 * Redirect to $url rather than displaying the normal page
323 * @param string $url URL
324 * @param string $responsecode HTTP status code
326 public function redirect( $url, $responsecode = '302' ) {
327 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
328 $this->mRedirect
= str_replace( "\n", '', $url );
329 $this->mRedirectCode
= $responsecode;
333 * Get the URL to redirect to, or an empty string if not redirect URL set
337 public function getRedirect() {
338 return $this->mRedirect
;
342 * Set the copyright URL to send with the output.
343 * Empty string to omit, null to reset.
347 * @param string|null $url
349 public function setCopyrightUrl( $url ) {
350 $this->copyrightUrl
= $url;
354 * Set the HTTP status code to send with the output.
356 * @param int $statusCode
358 public function setStatusCode( $statusCode ) {
359 $this->mStatusCode
= $statusCode;
363 * Add a new "<meta>" tag
364 * To add an http-equiv meta tag, precede the name with "http:"
366 * @param string $name Tag name
367 * @param string $val Tag value
369 function addMeta( $name, $val ) {
370 array_push( $this->mMetatags
, [ $name, $val ] );
374 * Returns the current <meta> tags
379 public function getMetaTags() {
380 return $this->mMetatags
;
384 * Add a new \<link\> tag to the page header.
386 * Note: use setCanonicalUrl() for rel=canonical.
388 * @param array $linkarr Associative array of attributes.
390 function addLink( array $linkarr ) {
391 array_push( $this->mLinktags
, $linkarr );
395 * Returns the current <link> tags
400 public function getLinkTags() {
401 return $this->mLinktags
;
405 * Add a new \<link\> with "rel" attribute set to "meta"
407 * @param array $linkarr Associative array mapping attribute names to their
408 * values, both keys and values will be escaped, and the
409 * "rel" attribute will be automatically added
411 function addMetadataLink( array $linkarr ) {
412 $linkarr['rel'] = $this->getMetadataAttribute();
413 $this->addLink( $linkarr );
417 * Set the URL to be used for the <link rel=canonical>. This should be used
418 * in preference to addLink(), to avoid duplicate link tags.
421 function setCanonicalUrl( $url ) {
422 $this->mCanonicalUrl
= $url;
426 * Returns the URL to be used for the <link rel=canonical> if
430 * @return bool|string
432 public function getCanonicalUrl() {
433 return $this->mCanonicalUrl
;
437 * Get the value of the "rel" attribute for metadata links
441 public function getMetadataAttribute() {
442 # note: buggy CC software only reads first "meta" link
443 static $haveMeta = false;
445 return 'alternate meta';
453 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
454 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
457 * @param string $script Raw HTML
459 function addScript( $script ) {
460 $this->mScripts
.= $script;
464 * Register and add a stylesheet from an extension directory.
466 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
467 * @param string $url Path to sheet. Provide either a full url (beginning
468 * with 'http', etc) or a relative path from the document root
469 * (beginning with '/'). Otherwise it behaves identically to
470 * addStyle() and draws from the /skins folder.
472 public function addExtensionStyle( $url ) {
473 wfDeprecated( __METHOD__
, '1.27' );
474 array_push( $this->mExtStyles
, $url );
478 * Get all styles added by extensions
480 * @deprecated since 1.27
483 function getExtStyle() {
484 wfDeprecated( __METHOD__
, '1.27' );
485 return $this->mExtStyles
;
489 * Add a JavaScript file out of skins/common, or a given relative path.
490 * Internal use only. Use OutputPage::addModules() if possible.
492 * @param string $file Filename in skins/common or complete on-server path
494 * @param string $version Style version of the file. Defaults to $wgStyleVersion
496 public function addScriptFile( $file, $version = null ) {
497 // See if $file parameter is an absolute URL or begins with a slash
498 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
501 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
503 if ( is_null( $version ) ) {
504 $version = $this->getConfig()->get( 'StyleVersion' );
506 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
510 * Add a self-contained script tag with the given contents
511 * Internal use only. Use OutputPage::addModules() if possible.
513 * @param string $script JavaScript text, no script tags
515 public function addInlineScript( $script ) {
516 $this->mScripts
.= Html
::inlineScript( $script );
520 * Filter an array of modules to remove insufficiently trustworthy members, and modules
521 * which are no longer registered (eg a page is cached before an extension is disabled)
522 * @param array $modules
523 * @param string|null $position If not null, only return modules with this position
524 * @param string $type
527 protected function filterModules( array $modules, $position = null,
528 $type = ResourceLoaderModule
::TYPE_COMBINED
530 $resourceLoader = $this->getResourceLoader();
531 $filteredModules = [];
532 foreach ( $modules as $val ) {
533 $module = $resourceLoader->getModule( $val );
534 if ( $module instanceof ResourceLoaderModule
535 && $module->getOrigin() <= $this->getAllowedModules( $type )
536 && ( is_null( $position ) ||
$module->getPosition() == $position )
538 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
539 $this->warnModuleTargetFilter( $module->getName() );
542 $filteredModules[] = $val;
545 return $filteredModules;
548 private function warnModuleTargetFilter( $moduleName ) {
549 static $warnings = [];
550 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
553 $warnings[$this->mTarget
][$moduleName] = true;
554 $this->getResourceLoader()->getLogger()->debug(
555 'Module "{module}" not loadable on target "{target}".',
557 'module' => $moduleName,
558 'target' => $this->mTarget
,
564 * Get the list of modules to include on this page
566 * @param bool $filter Whether to filter out insufficiently trustworthy modules
567 * @param string|null $position If not null, only return modules with this position
568 * @param string $param
569 * @return array Array of module names
571 public function getModules( $filter = false, $position = null, $param = 'mModules',
572 $type = ResourceLoaderModule
::TYPE_COMBINED
574 $modules = array_values( array_unique( $this->$param ) );
576 ?
$this->filterModules( $modules, $position, $type )
581 * Add one or more modules recognized by ResourceLoader. Modules added
582 * through this function will be loaded by ResourceLoader when the
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModules( $modules ) {
588 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
592 * Get the list of module JS to include on this page
594 * @param bool $filter
595 * @param string|null $position
596 * @return array Array of module names
598 public function getModuleScripts( $filter = false, $position = null ) {
599 return $this->getModules( $filter, $position, 'mModuleScripts',
600 ResourceLoaderModule
::TYPE_SCRIPTS
605 * Add only JS of one or more modules recognized by ResourceLoader. Module
606 * scripts added through this function will be loaded by ResourceLoader when
609 * @param string|array $modules Module name (string) or array of module names
611 public function addModuleScripts( $modules ) {
612 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
616 * Get the list of module CSS to include on this page
618 * @param bool $filter
619 * @param string|null $position
620 * @return array Array of module names
622 public function getModuleStyles( $filter = false, $position = null ) {
623 return $this->getModules( $filter, $position, 'mModuleStyles',
624 ResourceLoaderModule
::TYPE_STYLES
629 * Add only CSS of one or more modules recognized by ResourceLoader.
631 * Module styles added through this function will be added using standard link CSS
632 * tags, rather than as a combined Javascript and CSS package. Thus, they will
633 * load when JavaScript is disabled (unless CSS also happens to be disabled).
635 * @param string|array $modules Module name (string) or array of module names
637 public function addModuleStyles( $modules ) {
638 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
642 * @return null|string ResourceLoader target
644 public function getTarget() {
645 return $this->mTarget
;
649 * Sets ResourceLoader target for load.php links. If null, will be omitted
651 * @param string|null $target
653 public function setTarget( $target ) {
654 $this->mTarget
= $target;
658 * Get an array of head items
662 function getHeadItemsArray() {
663 return $this->mHeadItems
;
667 * Add or replace a head item to the output
669 * Whenever possible, use more specific options like ResourceLoader modules,
670 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
671 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
672 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
673 * This would be your very LAST fallback.
675 * @param string $name Item name
676 * @param string $value Raw HTML
678 public function addHeadItem( $name, $value ) {
679 $this->mHeadItems
[$name] = $value;
683 * Add one or more head items to the output
686 * @param string|string[] $value Raw HTML
688 public function addHeadItems( $values ) {
689 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
693 * Check if the header item $name is already set
695 * @param string $name Item name
698 public function hasHeadItem( $name ) {
699 return isset( $this->mHeadItems
[$name] );
703 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
706 public function setETag( $tag ) {
710 * Set whether the output should only contain the body of the article,
711 * without any skin, sidebar, etc.
712 * Used e.g. when calling with "action=render".
714 * @param bool $only Whether to output only the body of the article
716 public function setArticleBodyOnly( $only ) {
717 $this->mArticleBodyOnly
= $only;
721 * Return whether the output will contain only the body of the article
725 public function getArticleBodyOnly() {
726 return $this->mArticleBodyOnly
;
730 * Set an additional output property
733 * @param string $name
734 * @param mixed $value
736 public function setProperty( $name, $value ) {
737 $this->mProperties
[$name] = $value;
741 * Get an additional output property
744 * @param string $name
745 * @return mixed Property value or null if not found
747 public function getProperty( $name ) {
748 if ( isset( $this->mProperties
[$name] ) ) {
749 return $this->mProperties
[$name];
756 * checkLastModified tells the client to use the client-cached page if
757 * possible. If successful, the OutputPage is disabled so that
758 * any future call to OutputPage->output() have no effect.
760 * Side effect: sets mLastModified for Last-Modified header
762 * @param string $timestamp
764 * @return bool True if cache-ok headers was sent.
766 public function checkLastModified( $timestamp ) {
767 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
768 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
771 $config = $this->getConfig();
772 if ( !$config->get( 'CachePages' ) ) {
773 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
777 $timestamp = wfTimestamp( TS_MW
, $timestamp );
779 'page' => $timestamp,
780 'user' => $this->getUser()->getTouched(),
781 'epoch' => $config->get( 'CacheEpoch' )
783 if ( $config->get( 'UseSquid' ) ) {
784 // T46570: the core page itself may not change, but resources might
785 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
787 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
789 $maxModified = max( $modifiedTimes );
790 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
792 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
793 if ( $clientHeader === false ) {
794 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
798 # IE sends sizes after the date like this:
799 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
800 # this breaks strtotime().
801 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
803 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
804 $clientHeaderTime = strtotime( $clientHeader );
805 MediaWiki\restoreWarnings
();
806 if ( !$clientHeaderTime ) {
808 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
811 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
815 foreach ( $modifiedTimes as $name => $value ) {
816 if ( $info !== '' ) {
819 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
822 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
823 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
824 wfDebug( __METHOD__
. ": effective Last-Modified: " .
825 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
826 if ( $clientHeaderTime < $maxModified ) {
827 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
832 # Give a 304 Not Modified response code and disable body output
833 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
834 ini_set( 'zlib.output_compression', 0 );
835 $this->getRequest()->response()->statusHeader( 304 );
836 $this->sendCacheControl();
839 // Don't output a compressed blob when using ob_gzhandler;
840 // it's technically against HTTP spec and seems to confuse
841 // Firefox when the response gets split over two packets.
842 wfClearOutputBuffers();
848 * Override the last modified timestamp
850 * @param string $timestamp New timestamp, in a format readable by
853 public function setLastModified( $timestamp ) {
854 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
858 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
860 * @param string $policy The literal string to output as the contents of
861 * the meta tag. Will be parsed according to the spec and output in
865 public function setRobotPolicy( $policy ) {
866 $policy = Article
::formatRobotPolicy( $policy );
868 if ( isset( $policy['index'] ) ) {
869 $this->setIndexPolicy( $policy['index'] );
871 if ( isset( $policy['follow'] ) ) {
872 $this->setFollowPolicy( $policy['follow'] );
877 * Set the index policy for the page, but leave the follow policy un-
880 * @param string $policy Either 'index' or 'noindex'.
883 public function setIndexPolicy( $policy ) {
884 $policy = trim( $policy );
885 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
886 $this->mIndexPolicy
= $policy;
891 * Set the follow policy for the page, but leave the index policy un-
894 * @param string $policy Either 'follow' or 'nofollow'.
897 public function setFollowPolicy( $policy ) {
898 $policy = trim( $policy );
899 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
900 $this->mFollowPolicy
= $policy;
905 * Set the new value of the "action text", this will be added to the
906 * "HTML title", separated from it with " - ".
908 * @param string $text New value of the "action text"
910 public function setPageTitleActionText( $text ) {
911 $this->mPageTitleActionText
= $text;
915 * Get the value of the "action text"
919 public function getPageTitleActionText() {
920 return $this->mPageTitleActionText
;
924 * "HTML title" means the contents of "<title>".
925 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
927 * @param string|Message $name
929 public function setHTMLTitle( $name ) {
930 if ( $name instanceof Message
) {
931 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
933 $this->mHTMLtitle
= $name;
938 * Return the "HTML title", i.e. the content of the "<title>" tag.
942 public function getHTMLTitle() {
943 return $this->mHTMLtitle
;
947 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
951 public function setRedirectedFrom( $t ) {
952 $this->mRedirectedFrom
= $t;
956 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
957 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
958 * but not bad tags like \<script\>. This function automatically sets
959 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
960 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
961 * good tags like \<i\> will be dropped entirely.
963 * @param string|Message $name
965 public function setPageTitle( $name ) {
966 if ( $name instanceof Message
) {
967 $name = $name->setContext( $this->getContext() )->text();
970 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
971 # but leave "<i>foobar</i>" alone
972 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
973 $this->mPagetitle
= $nameWithTags;
975 # change "<i>foo&bar</i>" to "foo&bar"
977 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
978 ->inContentLanguage()
983 * Return the "page title", i.e. the content of the \<h1\> tag.
987 public function getPageTitle() {
988 return $this->mPagetitle
;
992 * Set the Title object to use
996 public function setTitle( Title
$t ) {
997 $this->getContext()->setTitle( $t );
1001 * Replace the subtitle with $str
1003 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1005 public function setSubtitle( $str ) {
1006 $this->clearSubtitle();
1007 $this->addSubtitle( $str );
1011 * Add $str to the subtitle
1013 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1015 public function addSubtitle( $str ) {
1016 if ( $str instanceof Message
) {
1017 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1019 $this->mSubtitle
[] = $str;
1024 * Build message object for a subtitle containing a backlink to a page
1026 * @param Title $title Title to link to
1027 * @param array $query Array of additional parameters to include in the link
1031 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1032 if ( $title->isRedirect() ) {
1033 $query['redirect'] = 'no';
1035 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1036 return wfMessage( 'backlinksubtitle' )
1037 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1041 * Add a subtitle containing a backlink to a page
1043 * @param Title $title Title to link to
1044 * @param array $query Array of additional parameters to include in the link
1046 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1047 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1051 * Clear the subtitles
1053 public function clearSubtitle() {
1054 $this->mSubtitle
= [];
1062 public function getSubtitle() {
1063 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1067 * Set the page as printable, i.e. it'll be displayed with all
1068 * print styles included
1070 public function setPrintable() {
1071 $this->mPrintable
= true;
1075 * Return whether the page is "printable"
1079 public function isPrintable() {
1080 return $this->mPrintable
;
1084 * Disable output completely, i.e. calling output() will have no effect
1086 public function disable() {
1087 $this->mDoNothing
= true;
1091 * Return whether the output will be completely disabled
1095 public function isDisabled() {
1096 return $this->mDoNothing
;
1100 * Show an "add new section" link?
1104 public function showNewSectionLink() {
1105 return $this->mNewSectionLink
;
1109 * Forcibly hide the new section link?
1113 public function forceHideNewSectionLink() {
1114 return $this->mHideNewSectionLink
;
1118 * Add or remove feed links in the page header
1119 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1120 * for the new version
1121 * @see addFeedLink()
1123 * @param bool $show True: add default feeds, false: remove all feeds
1125 public function setSyndicated( $show = true ) {
1127 $this->setFeedAppendQuery( false );
1129 $this->mFeedLinks
= [];
1134 * Add default feeds to the page header
1135 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1136 * for the new version
1137 * @see addFeedLink()
1139 * @param string $val Query to append to feed links or false to output
1142 public function setFeedAppendQuery( $val ) {
1143 $this->mFeedLinks
= [];
1145 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1146 $query = "feed=$type";
1147 if ( is_string( $val ) ) {
1148 $query .= '&' . $val;
1150 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1155 * Add a feed link to the page header
1157 * @param string $format Feed type, should be a key of $wgFeedClasses
1158 * @param string $href URL
1160 public function addFeedLink( $format, $href ) {
1161 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1162 $this->mFeedLinks
[$format] = $href;
1167 * Should we output feed links for this page?
1170 public function isSyndicated() {
1171 return count( $this->mFeedLinks
) > 0;
1175 * Return URLs for each supported syndication format for this page.
1176 * @return array Associating format keys with URLs
1178 public function getSyndicationLinks() {
1179 return $this->mFeedLinks
;
1183 * Will currently always return null
1187 public function getFeedAppendQuery() {
1188 return $this->mFeedLinksAppendQuery
;
1192 * Set whether the displayed content is related to the source of the
1193 * corresponding article on the wiki
1194 * Setting true will cause the change "article related" toggle to true
1198 public function setArticleFlag( $v ) {
1199 $this->mIsarticle
= $v;
1201 $this->mIsArticleRelated
= $v;
1206 * Return whether the content displayed page is related to the source of
1207 * the corresponding article on the wiki
1211 public function isArticle() {
1212 return $this->mIsarticle
;
1216 * Set whether this page is related an article on the wiki
1217 * Setting false will cause the change of "article flag" toggle to false
1221 public function setArticleRelated( $v ) {
1222 $this->mIsArticleRelated
= $v;
1224 $this->mIsarticle
= false;
1229 * Return whether this page is related an article on the wiki
1233 public function isArticleRelated() {
1234 return $this->mIsArticleRelated
;
1238 * Add new language links
1240 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1241 * (e.g. 'fr:Test page')
1243 public function addLanguageLinks( array $newLinkArray ) {
1244 $this->mLanguageLinks +
= $newLinkArray;
1248 * Reset the language links and add new language links
1250 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1251 * (e.g. 'fr:Test page')
1253 public function setLanguageLinks( array $newLinkArray ) {
1254 $this->mLanguageLinks
= $newLinkArray;
1258 * Get the list of language links
1260 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1262 public function getLanguageLinks() {
1263 return $this->mLanguageLinks
;
1267 * Add an array of categories, with names in the keys
1269 * @param array $categories Mapping category name => sort key
1271 public function addCategoryLinks( array $categories ) {
1274 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1278 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1280 # Set all the values to 'normal'.
1281 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1283 # Mark hidden categories
1284 foreach ( $res as $row ) {
1285 if ( isset( $row->pp_value
) ) {
1286 $categories[$row->page_title
] = 'hidden';
1290 // Avoid PHP 7.1 warning of passing $this by reference
1291 $outputPage = $this;
1292 # Add the remaining categories to the skin
1294 'OutputPageMakeCategoryLinks',
1295 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1297 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1298 foreach ( $categories as $category => $type ) {
1299 // array keys will cast numeric category names to ints, so cast back to string
1300 $category = (string)$category;
1301 $origcategory = $category;
1302 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1306 $wgContLang->findVariantLink( $category, $title, true );
1307 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1310 $text = $wgContLang->convertHtml( $title->getText() );
1311 $this->mCategories
[$type][] = $title->getText();
1312 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1318 * @param array $categories
1319 * @return bool|ResultWrapper
1321 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1322 # Add the links to a LinkBatch
1323 $arr = [ NS_CATEGORY
=> $categories ];
1324 $lb = new LinkBatch
;
1325 $lb->setArray( $arr );
1327 # Fetch existence plus the hiddencat property
1328 $dbr = wfGetDB( DB_REPLICA
);
1329 $fields = array_merge(
1330 LinkCache
::getSelectFields(),
1331 [ 'page_namespace', 'page_title', 'pp_value' ]
1334 $res = $dbr->select( [ 'page', 'page_props' ],
1336 $lb->constructSet( 'page', $dbr ),
1339 [ 'page_props' => [ 'LEFT JOIN', [
1340 'pp_propname' => 'hiddencat',
1345 # Add the results to the link cache
1346 $lb->addResultToCache( LinkCache
::singleton(), $res );
1352 * Reset the category links (but not the category list) and add $categories
1354 * @param array $categories Mapping category name => sort key
1356 public function setCategoryLinks( array $categories ) {
1357 $this->mCategoryLinks
= [];
1358 $this->addCategoryLinks( $categories );
1362 * Get the list of category links, in a 2-D array with the following format:
1363 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1364 * hidden categories) and $link a HTML fragment with a link to the category
1369 public function getCategoryLinks() {
1370 return $this->mCategoryLinks
;
1374 * Get the list of category names this page belongs to.
1376 * @param string $type The type of categories which should be returned. Possible values:
1377 * * all: all categories of all types
1378 * * hidden: only the hidden categories
1379 * * normal: all categories, except hidden categories
1380 * @return array Array of strings
1382 public function getCategories( $type = 'all' ) {
1383 if ( $type === 'all' ) {
1384 $allCategories = [];
1385 foreach ( $this->mCategories
as $categories ) {
1386 $allCategories = array_merge( $allCategories, $categories );
1388 return $allCategories;
1390 if ( !isset( $this->mCategories
[$type] ) ) {
1391 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1393 return $this->mCategories
[$type];
1397 * Add an array of indicators, with their identifiers as array
1398 * keys and HTML contents as values.
1400 * In case of duplicate keys, existing values are overwritten.
1402 * @param array $indicators
1405 public function setIndicators( array $indicators ) {
1406 $this->mIndicators
= $indicators +
$this->mIndicators
;
1407 // Keep ordered by key
1408 ksort( $this->mIndicators
);
1412 * Get the indicators associated with this page.
1414 * The array will be internally ordered by item keys.
1416 * @return array Keys: identifiers, values: HTML contents
1419 public function getIndicators() {
1420 return $this->mIndicators
;
1424 * Adds help link with an icon via page indicators.
1425 * Link target can be overridden by a local message containing a wikilink:
1426 * the message key is: lowercase action or special page name + '-helppage'.
1427 * @param string $to Target MediaWiki.org page title or encoded URL.
1428 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1431 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1432 $this->addModuleStyles( 'mediawiki.helplink' );
1433 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1435 if ( $overrideBaseUrl ) {
1438 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1439 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1442 $link = Html
::rawElement(
1446 'target' => '_blank',
1447 'class' => 'mw-helplink',
1452 $this->setIndicators( [ 'mw-helplink' => $link ] );
1456 * Do not allow scripts which can be modified by wiki users to load on this page;
1457 * only allow scripts bundled with, or generated by, the software.
1458 * Site-wide styles are controlled by a config setting, since they can be
1459 * used to create a custom skin/theme, but not user-specific ones.
1461 * @todo this should be given a more accurate name
1463 public function disallowUserJs() {
1464 $this->reduceAllowedModules(
1465 ResourceLoaderModule
::TYPE_SCRIPTS
,
1466 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1469 // Site-wide styles are controlled by a config setting, see T73621
1470 // for background on why. User styles are never allowed.
1471 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1472 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1474 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1476 $this->reduceAllowedModules(
1477 ResourceLoaderModule
::TYPE_STYLES
,
1483 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1484 * @see ResourceLoaderModule::$origin
1485 * @param string $type ResourceLoaderModule TYPE_ constant
1486 * @return int ResourceLoaderModule ORIGIN_ class constant
1488 public function getAllowedModules( $type ) {
1489 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1490 return min( array_values( $this->mAllowedModules
) );
1492 return isset( $this->mAllowedModules
[$type] )
1493 ?
$this->mAllowedModules
[$type]
1494 : ResourceLoaderModule
::ORIGIN_ALL
;
1499 * Limit the highest level of CSS/JS untrustworthiness allowed.
1501 * If passed the same or a higher level than the current level of untrustworthiness set, the
1502 * level will remain unchanged.
1504 * @param string $type
1505 * @param int $level ResourceLoaderModule class constant
1507 public function reduceAllowedModules( $type, $level ) {
1508 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1512 * Prepend $text to the body HTML
1514 * @param string $text HTML
1516 public function prependHTML( $text ) {
1517 $this->mBodytext
= $text . $this->mBodytext
;
1521 * Append $text to the body HTML
1523 * @param string $text HTML
1525 public function addHTML( $text ) {
1526 $this->mBodytext
.= $text;
1530 * Shortcut for adding an Html::element via addHTML.
1534 * @param string $element
1535 * @param array $attribs
1536 * @param string $contents
1538 public function addElement( $element, array $attribs = [], $contents = '' ) {
1539 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1543 * Clear the body HTML
1545 public function clearHTML() {
1546 $this->mBodytext
= '';
1552 * @return string HTML
1554 public function getHTML() {
1555 return $this->mBodytext
;
1559 * Get/set the ParserOptions object to use for wikitext parsing
1561 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1562 * current ParserOption object
1563 * @return ParserOptions
1565 public function parserOptions( $options = null ) {
1566 if ( $options !== null && !empty( $options->isBogus
) ) {
1567 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1568 // been changed somehow, and keep it if so.
1569 $anonPO = ParserOptions
::newFromAnon();
1570 $anonPO->setEditSection( false );
1571 $anonPO->setAllowUnsafeRawHtml( false );
1572 if ( !$options->matches( $anonPO ) ) {
1573 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1574 $options->isBogus
= false;
1578 if ( !$this->mParserOptions
) {
1579 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1580 // $wgUser isn't unstubbable yet, so don't try to get a
1581 // ParserOptions for it. And don't cache this ParserOptions
1583 $po = ParserOptions
::newFromAnon();
1584 $po->setEditSection( false );
1585 $po->setAllowUnsafeRawHtml( false );
1586 $po->isBogus
= true;
1587 if ( $options !== null ) {
1588 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1593 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1594 $this->mParserOptions
->setEditSection( false );
1595 $this->mParserOptions
->setAllowUnsafeRawHtml( false );
1598 if ( $options !== null && !empty( $options->isBogus
) ) {
1599 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1601 return wfSetVar( $this->mParserOptions
, null, true );
1603 return wfSetVar( $this->mParserOptions
, $options );
1608 * Set the revision ID which will be seen by the wiki text parser
1609 * for things such as embedded {{REVISIONID}} variable use.
1611 * @param int|null $revid An positive integer, or null
1612 * @return mixed Previous value
1614 public function setRevisionId( $revid ) {
1615 $val = is_null( $revid ) ?
null : intval( $revid );
1616 return wfSetVar( $this->mRevisionId
, $val );
1620 * Get the displayed revision ID
1624 public function getRevisionId() {
1625 return $this->mRevisionId
;
1629 * Set the timestamp of the revision which will be displayed. This is used
1630 * to avoid a extra DB call in Skin::lastModified().
1632 * @param string|null $timestamp
1633 * @return mixed Previous value
1635 public function setRevisionTimestamp( $timestamp ) {
1636 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1640 * Get the timestamp of displayed revision.
1641 * This will be null if not filled by setRevisionTimestamp().
1643 * @return string|null
1645 public function getRevisionTimestamp() {
1646 return $this->mRevisionTimestamp
;
1650 * Set the displayed file version
1652 * @param File|bool $file
1653 * @return mixed Previous value
1655 public function setFileVersion( $file ) {
1657 if ( $file instanceof File
&& $file->exists() ) {
1658 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1660 return wfSetVar( $this->mFileVersion
, $val, true );
1664 * Get the displayed file version
1666 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1668 public function getFileVersion() {
1669 return $this->mFileVersion
;
1673 * Get the templates used on this page
1675 * @return array (namespace => dbKey => revId)
1678 public function getTemplateIds() {
1679 return $this->mTemplateIds
;
1683 * Get the files used on this page
1685 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1688 public function getFileSearchOptions() {
1689 return $this->mImageTimeKeys
;
1693 * Convert wikitext to HTML and add it to the buffer
1694 * Default assumes that the current page title will be used.
1696 * @param string $text
1697 * @param bool $linestart Is this the start of a line?
1698 * @param bool $interface Is this text in the user interface language?
1699 * @throws MWException
1701 public function addWikiText( $text, $linestart = true, $interface = true ) {
1702 $title = $this->getTitle(); // Work around E_STRICT
1704 throw new MWException( 'Title is null' );
1706 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1710 * Add wikitext with a custom Title object
1712 * @param string $text Wikitext
1713 * @param Title $title
1714 * @param bool $linestart Is this the start of a line?
1716 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1717 $this->addWikiTextTitle( $text, $title, $linestart );
1721 * Add wikitext with a custom Title object and tidy enabled.
1723 * @param string $text Wikitext
1724 * @param Title $title
1725 * @param bool $linestart Is this the start of a line?
1727 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1728 $this->addWikiTextTitle( $text, $title, $linestart, true );
1732 * Add wikitext with tidy enabled
1734 * @param string $text Wikitext
1735 * @param bool $linestart Is this the start of a line?
1737 public function addWikiTextTidy( $text, $linestart = true ) {
1738 $title = $this->getTitle();
1739 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1743 * Add wikitext with a custom Title object
1745 * @param string $text Wikitext
1746 * @param Title $title
1747 * @param bool $linestart Is this the start of a line?
1748 * @param bool $tidy Whether to use tidy
1749 * @param bool $interface Whether it is an interface message
1750 * (for example disables conversion)
1752 public function addWikiTextTitle( $text, Title
$title, $linestart,
1753 $tidy = false, $interface = false
1757 $popts = $this->parserOptions();
1758 $oldTidy = $popts->setTidy( $tidy );
1759 $popts->setInterfaceMessage( (bool)$interface );
1761 $parserOutput = $wgParser->getFreshParser()->parse(
1762 $text, $title, $popts,
1763 $linestart, true, $this->mRevisionId
1766 $popts->setTidy( $oldTidy );
1768 $this->addParserOutput( $parserOutput );
1772 * Add a ParserOutput object, but without Html.
1774 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1775 * @param ParserOutput $parserOutput
1777 public function addParserOutputNoText( $parserOutput ) {
1778 wfDeprecated( __METHOD__
, '1.24' );
1779 $this->addParserOutputMetadata( $parserOutput );
1783 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1784 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1788 * @param ParserOutput $parserOutput
1790 public function addParserOutputMetadata( $parserOutput ) {
1791 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1792 $this->addCategoryLinks( $parserOutput->getCategories() );
1793 $this->setIndicators( $parserOutput->getIndicators() );
1794 $this->mNewSectionLink
= $parserOutput->getNewSection();
1795 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1797 if ( !$parserOutput->isCacheable() ) {
1798 $this->enableClientCache( false );
1800 $this->mNoGallery
= $parserOutput->getNoGallery();
1801 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1802 $this->addModules( $parserOutput->getModules() );
1803 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1804 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1805 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1806 $this->mPreventClickjacking
= $this->mPreventClickjacking
1807 ||
$parserOutput->preventClickjacking();
1809 // Template versioning...
1810 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1811 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1812 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1814 $this->mTemplateIds
[$ns] = $dbks;
1817 // File versioning...
1818 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1819 $this->mImageTimeKeys
[$dbk] = $data;
1822 // Hooks registered in the object
1823 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1824 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1825 list( $hookName, $data ) = $hookInfo;
1826 if ( isset( $parserOutputHooks[$hookName] ) ) {
1827 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1831 // Enable OOUI if requested via ParserOutput
1832 if ( $parserOutput->getEnableOOUI() ) {
1833 $this->enableOOUI();
1836 // Include parser limit report
1837 if ( !$this->limitReportJSData
) {
1838 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1841 // Link flags are ignored for now, but may in the future be
1842 // used to mark individual language links.
1844 // Avoid PHP 7.1 warning of passing $this by reference
1845 $outputPage = $this;
1846 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1847 Hooks
::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1851 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1852 * ParserOutput object, without any other metadata.
1855 * @param ParserOutput $parserOutput
1857 public function addParserOutputContent( $parserOutput ) {
1858 $this->addParserOutputText( $parserOutput );
1860 $this->addModules( $parserOutput->getModules() );
1861 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1862 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1864 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1868 * Add the HTML associated with a ParserOutput object, without any metadata.
1871 * @param ParserOutput $parserOutput
1873 public function addParserOutputText( $parserOutput ) {
1874 $text = $parserOutput->getText();
1875 // Avoid PHP 7.1 warning of passing $this by reference
1876 $outputPage = $this;
1877 Hooks
::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1878 $this->addHTML( $text );
1882 * Add everything from a ParserOutput object.
1884 * @param ParserOutput $parserOutput
1886 function addParserOutput( $parserOutput ) {
1887 $this->addParserOutputMetadata( $parserOutput );
1888 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1890 // Touch section edit links only if not previously disabled
1891 if ( $parserOutput->getEditSectionTokens() ) {
1892 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1895 $this->addParserOutputText( $parserOutput );
1899 * Add the output of a QuickTemplate to the output buffer
1901 * @param QuickTemplate $template
1903 public function addTemplate( &$template ) {
1904 $this->addHTML( $template->getHTML() );
1908 * Parse wikitext and return the HTML.
1910 * @param string $text
1911 * @param bool $linestart Is this the start of a line?
1912 * @param bool $interface Use interface language ($wgLang instead of
1913 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1914 * This also disables LanguageConverter.
1915 * @param Language $language Target language object, will override $interface
1916 * @throws MWException
1917 * @return string HTML
1919 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1922 if ( is_null( $this->getTitle() ) ) {
1923 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1926 $popts = $this->parserOptions();
1928 $popts->setInterfaceMessage( true );
1930 if ( $language !== null ) {
1931 $oldLang = $popts->setTargetLanguage( $language );
1934 $parserOutput = $wgParser->getFreshParser()->parse(
1935 $text, $this->getTitle(), $popts,
1936 $linestart, true, $this->mRevisionId
1940 $popts->setInterfaceMessage( false );
1942 if ( $language !== null ) {
1943 $popts->setTargetLanguage( $oldLang );
1946 return $parserOutput->getText();
1950 * Parse wikitext, strip paragraphs, and return the HTML.
1952 * @param string $text
1953 * @param bool $linestart Is this the start of a line?
1954 * @param bool $interface Use interface language ($wgLang instead of
1955 * $wgContLang) while parsing language sensitive magic
1956 * words like GRAMMAR and PLURAL
1957 * @return string HTML
1959 public function parseInline( $text, $linestart = true, $interface = false ) {
1960 $parsed = $this->parse( $text, $linestart, $interface );
1961 return Parser
::stripOuterParagraph( $parsed );
1966 * @deprecated since 1.27 Use setCdnMaxage() instead
1968 public function setSquidMaxage( $maxage ) {
1969 $this->setCdnMaxage( $maxage );
1973 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1975 * @param int $maxage Maximum cache time on the CDN, in seconds.
1977 public function setCdnMaxage( $maxage ) {
1978 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1982 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1984 * @param int $maxage Maximum cache time on the CDN, in seconds
1987 public function lowerCdnMaxage( $maxage ) {
1988 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1989 $this->setCdnMaxage( $this->mCdnMaxage
);
1993 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1995 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1996 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1997 * TTL is 90% of the age of the object, subject to the min and max.
1999 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
2000 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
2001 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2002 * @return integer TTL in seconds
2005 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2006 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2007 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2009 if ( $mtime === null ||
$mtime === false ) {
2010 return $minTTL; // entity does not exist
2013 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2014 $adaptiveTTL = max( .9 * $age, $minTTL );
2015 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2017 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2019 return $adaptiveTTL;
2023 * Use enableClientCache(false) to force it to send nocache headers
2025 * @param bool $state
2029 public function enableClientCache( $state ) {
2030 return wfSetVar( $this->mEnableClientCache
, $state );
2034 * Get the list of cookies that will influence on the cache
2038 function getCacheVaryCookies() {
2040 if ( $cookies === null ) {
2041 $config = $this->getConfig();
2042 $cookies = array_merge(
2043 SessionManager
::singleton()->getVaryCookies(),
2047 $config->get( 'CacheVaryCookies' )
2049 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2055 * Check if the request has a cache-varying cookie header
2056 * If it does, it's very important that we don't allow public caching
2060 function haveCacheVaryCookies() {
2061 $request = $this->getRequest();
2062 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2063 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2064 wfDebug( __METHOD__
. ": found $cookieName\n" );
2068 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2073 * Add an HTTP header that will influence on the cache
2075 * @param string $header Header name
2076 * @param string[]|null $option Options for the Key header. See
2077 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2078 * for the list of valid options.
2080 public function addVaryHeader( $header, array $option = null ) {
2081 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2082 $this->mVaryHeader
[$header] = [];
2084 if ( !is_array( $option ) ) {
2087 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2091 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2092 * such as Accept-Encoding or Cookie
2096 public function getVaryHeader() {
2097 // If we vary on cookies, let's make sure it's always included here too.
2098 if ( $this->getCacheVaryCookies() ) {
2099 $this->addVaryHeader( 'Cookie' );
2102 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2103 $this->addVaryHeader( $header, $options );
2105 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2109 * Get a complete Key header
2113 public function getKeyHeader() {
2114 $cvCookies = $this->getCacheVaryCookies();
2116 $cookiesOption = [];
2117 foreach ( $cvCookies as $cookieName ) {
2118 $cookiesOption[] = 'param=' . $cookieName;
2120 $this->addVaryHeader( 'Cookie', $cookiesOption );
2122 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2123 $this->addVaryHeader( $header, $options );
2127 foreach ( $this->mVaryHeader
as $header => $option ) {
2128 $newheader = $header;
2129 if ( is_array( $option ) && count( $option ) > 0 ) {
2130 $newheader .= ';' . implode( ';', $option );
2132 $headers[] = $newheader;
2134 $key = 'Key: ' . implode( ',', $headers );
2140 * T23672: Add Accept-Language to Vary and Key headers
2141 * if there's no 'variant' parameter existed in GET.
2144 * /w/index.php?title=Main_page should always be served; but
2145 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2147 function addAcceptLanguage() {
2148 $title = $this->getTitle();
2149 if ( !$title instanceof Title
) {
2153 $lang = $title->getPageLanguage();
2154 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2155 $variants = $lang->getVariants();
2157 foreach ( $variants as $variant ) {
2158 if ( $variant === $lang->getCode() ) {
2161 $aloption[] = 'substr=' . $variant;
2163 // IE and some other browsers use BCP 47 standards in
2164 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2165 // We should handle these too.
2166 $variantBCP47 = wfBCP47( $variant );
2167 if ( $variantBCP47 !== $variant ) {
2168 $aloption[] = 'substr=' . $variantBCP47;
2172 $this->addVaryHeader( 'Accept-Language', $aloption );
2177 * Set a flag which will cause an X-Frame-Options header appropriate for
2178 * edit pages to be sent. The header value is controlled by
2179 * $wgEditPageFrameOptions.
2181 * This is the default for special pages. If you display a CSRF-protected
2182 * form on an ordinary view page, then you need to call this function.
2184 * @param bool $enable
2186 public function preventClickjacking( $enable = true ) {
2187 $this->mPreventClickjacking
= $enable;
2191 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2192 * This can be called from pages which do not contain any CSRF-protected
2195 public function allowClickjacking() {
2196 $this->mPreventClickjacking
= false;
2200 * Get the prevent-clickjacking flag
2205 public function getPreventClickjacking() {
2206 return $this->mPreventClickjacking
;
2210 * Get the X-Frame-Options header value (without the name part), or false
2211 * if there isn't one. This is used by Skin to determine whether to enable
2212 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2214 * @return string|false
2216 public function getFrameOptions() {
2217 $config = $this->getConfig();
2218 if ( $config->get( 'BreakFrames' ) ) {
2220 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2221 return $config->get( 'EditPageFrameOptions' );
2227 * Send cache control HTTP headers
2229 public function sendCacheControl() {
2230 $response = $this->getRequest()->response();
2231 $config = $this->getConfig();
2233 $this->addVaryHeader( 'Cookie' );
2234 $this->addAcceptLanguage();
2236 # don't serve compressed data to clients who can't handle it
2237 # maintain different caches for logged-in users and non-logged in ones
2238 $response->header( $this->getVaryHeader() );
2240 if ( $config->get( 'UseKeyHeader' ) ) {
2241 $response->header( $this->getKeyHeader() );
2244 if ( $this->mEnableClientCache
) {
2246 $config->get( 'UseSquid' ) &&
2247 !$response->hasCookies() &&
2248 !SessionManager
::getGlobalSession()->isPersistent() &&
2249 !$this->isPrintable() &&
2250 $this->mCdnMaxage
!= 0 &&
2251 !$this->haveCacheVaryCookies()
2253 if ( $config->get( 'UseESI' ) ) {
2254 # We'll purge the proxy cache explicitly, but require end user agents
2255 # to revalidate against the proxy on each visit.
2256 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2257 wfDebug( __METHOD__
.
2258 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2259 # start with a shorter timeout for initial testing
2260 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2262 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2263 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2265 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2267 # We'll purge the proxy cache for anons explicitly, but require end user agents
2268 # to revalidate against the proxy on each visit.
2269 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2270 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2271 wfDebug( __METHOD__
.
2272 ": local proxy caching; {$this->mLastModified} **", 'private' );
2273 # start with a shorter timeout for initial testing
2274 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2275 $response->header( "Cache-Control: " .
2276 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2279 # We do want clients to cache if they can, but they *must* check for updates
2280 # on revisiting the page.
2281 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2282 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2283 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2285 if ( $this->mLastModified
) {
2286 $response->header( "Last-Modified: {$this->mLastModified}" );
2289 wfDebug( __METHOD__
. ": no caching **", 'private' );
2291 # In general, the absence of a last modified header should be enough to prevent
2292 # the client from using its cache. We send a few other things just to make sure.
2293 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2294 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2295 $response->header( 'Pragma: no-cache' );
2300 * Finally, all the text has been munged and accumulated into
2301 * the object, let's actually output it:
2303 * @param bool $return Set to true to get the result as a string rather than sending it
2304 * @return string|null
2306 * @throws FatalError
2307 * @throws MWException
2309 public function output( $return = false ) {
2312 if ( $this->mDoNothing
) {
2313 return $return ?
'' : null;
2316 $response = $this->getRequest()->response();
2317 $config = $this->getConfig();
2319 if ( $this->mRedirect
!= '' ) {
2320 # Standards require redirect URLs to be absolute
2321 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2323 $redirect = $this->mRedirect
;
2324 $code = $this->mRedirectCode
;
2326 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2327 if ( $code == '301' ||
$code == '303' ) {
2328 if ( !$config->get( 'DebugRedirects' ) ) {
2329 $response->statusHeader( $code );
2331 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2333 if ( $config->get( 'VaryOnXFP' ) ) {
2334 $this->addVaryHeader( 'X-Forwarded-Proto' );
2336 $this->sendCacheControl();
2338 $response->header( "Content-Type: text/html; charset=utf-8" );
2339 if ( $config->get( 'DebugRedirects' ) ) {
2340 $url = htmlspecialchars( $redirect );
2341 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2342 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2343 print "</body>\n</html>\n";
2345 $response->header( 'Location: ' . $redirect );
2349 return $return ?
'' : null;
2350 } elseif ( $this->mStatusCode
) {
2351 $response->statusHeader( $this->mStatusCode
);
2354 # Buffer output; final headers may depend on later processing
2357 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2358 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2360 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2361 // jQuery etc. can work correctly.
2362 $response->header( 'X-UA-Compatible: IE=Edge' );
2364 // Prevent framing, if requested
2365 $frameOptions = $this->getFrameOptions();
2366 if ( $frameOptions ) {
2367 $response->header( "X-Frame-Options: $frameOptions" );
2370 if ( $this->mArticleBodyOnly
) {
2371 echo $this->mBodytext
;
2373 // Enable safe mode if requested
2374 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2375 $this->disallowUserJs();
2378 $sk = $this->getSkin();
2379 // add skin specific modules
2380 $modules = $sk->getDefaultModules();
2382 // Enforce various default modules for all pages and all skins
2384 // Keep this list as small as possible
2386 'mediawiki.page.startup',
2390 // Support for high-density display images if enabled
2391 if ( $config->get( 'ResponsiveImages' ) ) {
2392 $coreModules[] = 'mediawiki.hidpi';
2395 $this->addModules( $coreModules );
2396 foreach ( $modules as $group ) {
2397 $this->addModules( $group );
2399 MWDebug
::addModules( $this );
2401 // Avoid PHP 7.1 warning of passing $this by reference
2402 $outputPage = $this;
2403 // Hook that allows last minute changes to the output page, e.g.
2404 // adding of CSS or Javascript by extensions.
2405 Hooks
::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2409 } catch ( Exception
$e ) {
2410 ob_end_clean(); // bug T129657
2416 // This hook allows last minute changes to final overall output by modifying output buffer
2417 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2418 } catch ( Exception
$e ) {
2419 ob_end_clean(); // bug T129657
2423 $this->sendCacheControl();
2426 return ob_get_clean();
2434 * Prepare this object to display an error page; disable caching and
2435 * indexing, clear the current text and redirect, set the page's title
2436 * and optionally an custom HTML title (content of the "<title>" tag).
2438 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2439 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2440 * optional, if not passed the "<title>" attribute will be
2441 * based on $pageTitle
2443 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2444 $this->setPageTitle( $pageTitle );
2445 if ( $htmlTitle !== false ) {
2446 $this->setHTMLTitle( $htmlTitle );
2448 $this->setRobotPolicy( 'noindex,nofollow' );
2449 $this->setArticleRelated( false );
2450 $this->enableClientCache( false );
2451 $this->mRedirect
= '';
2452 $this->clearSubtitle();
2457 * Output a standard error page
2459 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2460 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2461 * showErrorPage( 'titlemsg', $messageObject );
2462 * showErrorPage( $titleMessageObject, $messageObject );
2464 * @param string|Message $title Message key (string) for page title, or a Message object
2465 * @param string|Message $msg Message key (string) for page text, or a Message object
2466 * @param array $params Message parameters; ignored if $msg is a Message object
2468 public function showErrorPage( $title, $msg, $params = [] ) {
2469 if ( !$title instanceof Message
) {
2470 $title = $this->msg( $title );
2473 $this->prepareErrorPage( $title );
2475 if ( $msg instanceof Message
) {
2476 if ( $params !== [] ) {
2477 trigger_error( 'Argument ignored: $params. The message parameters argument '
2478 . 'is discarded when the $msg argument is a Message object instead of '
2479 . 'a string.', E_USER_NOTICE
);
2481 $this->addHTML( $msg->parseAsBlock() );
2483 $this->addWikiMsgArray( $msg, $params );
2486 $this->returnToMain();
2490 * Output a standard permission error page
2492 * @param array $errors Error message keys or [key, param...] arrays
2493 * @param string $action Action that was denied or null if unknown
2495 public function showPermissionsErrorPage( array $errors, $action = null ) {
2496 foreach ( $errors as $key => $error ) {
2497 $errors[$key] = (array)$error;
2500 // For some action (read, edit, create and upload), display a "login to do this action"
2501 // error if all of the following conditions are met:
2502 // 1. the user is not logged in
2503 // 2. the only error is insufficient permissions (i.e. no block or something else)
2504 // 3. the error can be avoided simply by logging in
2505 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2506 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2507 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2508 && ( User
::groupHasPermission( 'user', $action )
2509 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2511 $displayReturnto = null;
2513 # Due to T34276, if a user does not have read permissions,
2514 # $this->getTitle() will just give Special:Badtitle, which is
2515 # not especially useful as a returnto parameter. Use the title
2516 # from the request instead, if there was one.
2517 $request = $this->getRequest();
2518 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2519 if ( $action == 'edit' ) {
2520 $msg = 'whitelistedittext';
2521 $displayReturnto = $returnto;
2522 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2523 $msg = 'nocreatetext';
2524 } elseif ( $action == 'upload' ) {
2525 $msg = 'uploadnologintext';
2527 $msg = 'loginreqpagetext';
2528 $displayReturnto = Title
::newMainPage();
2534 $query['returnto'] = $returnto->getPrefixedText();
2536 if ( !$request->wasPosted() ) {
2537 $returntoquery = $request->getValues();
2538 unset( $returntoquery['title'] );
2539 unset( $returntoquery['returnto'] );
2540 unset( $returntoquery['returntoquery'] );
2541 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2544 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2545 $loginLink = $linkRenderer->makeKnownLink(
2546 SpecialPage
::getTitleFor( 'Userlogin' ),
2547 $this->msg( 'loginreqlink' )->text(),
2552 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2553 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2555 # Don't return to a page the user can't read otherwise
2556 # we'll end up in a pointless loop
2557 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2558 $this->returnToMain( null, $displayReturnto );
2561 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2562 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2567 * Display an error page indicating that a given version of MediaWiki is
2568 * required to use it
2570 * @param mixed $version The version of MediaWiki needed to use the page
2572 public function versionRequired( $version ) {
2573 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2575 $this->addWikiMsg( 'versionrequiredtext', $version );
2576 $this->returnToMain();
2580 * Format a list of error messages
2582 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2583 * @param string $action Action that was denied or null if unknown
2584 * @return string The wikitext error-messages, formatted into a list.
2586 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2587 if ( $action == null ) {
2588 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2590 $action_desc = $this->msg( "action-$action" )->plain();
2592 'permissionserrorstext-withaction',
2595 )->plain() . "\n\n";
2598 if ( count( $errors ) > 1 ) {
2599 $text .= '<ul class="permissions-errors">' . "\n";
2601 foreach ( $errors as $error ) {
2603 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2608 $text .= "<div class=\"permissions-errors\">\n" .
2609 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2617 * Display a page stating that the Wiki is in read-only mode.
2618 * Should only be called after wfReadOnly() has returned true.
2620 * Historically, this function was used to show the source of the page that the user
2621 * was trying to edit and _also_ permissions error messages. The relevant code was
2622 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2624 * @deprecated since 1.25; throw the exception directly
2625 * @throws ReadOnlyError
2627 public function readOnlyPage() {
2628 if ( func_num_args() > 0 ) {
2629 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2632 throw new ReadOnlyError
;
2636 * Turn off regular page output and return an error response
2637 * for when rate limiting has triggered.
2639 * @deprecated since 1.25; throw the exception directly
2641 public function rateLimited() {
2642 wfDeprecated( __METHOD__
, '1.25' );
2643 throw new ThrottledError
;
2647 * Show a warning about replica DB lag
2649 * If the lag is higher than $wgSlaveLagCritical seconds,
2650 * then the warning is a bit more obvious. If the lag is
2651 * lower than $wgSlaveLagWarning, then no warning is shown.
2653 * @param int $lag Slave lag
2655 public function showLagWarning( $lag ) {
2656 $config = $this->getConfig();
2657 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2658 $lag = floor( $lag ); // floor to avoid nano seconds to display
2659 $message = $lag < $config->get( 'SlaveLagCritical' )
2662 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2663 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2667 public function showFatalError( $message ) {
2668 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2670 $this->addHTML( $message );
2673 public function showUnexpectedValueError( $name, $val ) {
2674 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2677 public function showFileCopyError( $old, $new ) {
2678 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2681 public function showFileRenameError( $old, $new ) {
2682 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2685 public function showFileDeleteError( $name ) {
2686 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2689 public function showFileNotFoundError( $name ) {
2690 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2694 * Add a "return to" link pointing to a specified title
2696 * @param Title $title Title to link
2697 * @param array $query Query string parameters
2698 * @param string $text Text of the link (input is not escaped)
2699 * @param array $options Options array to pass to Linker
2701 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2702 $linkRenderer = MediaWikiServices
::getInstance()
2703 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2704 $link = $this->msg( 'returnto' )->rawParams(
2705 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2706 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2710 * Add a "return to" link pointing to a specified title,
2711 * or the title indicated in the request, or else the main page
2713 * @param mixed $unused
2714 * @param Title|string $returnto Title or String to return to
2715 * @param string $returntoquery Query string for the return to link
2717 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2718 if ( $returnto == null ) {
2719 $returnto = $this->getRequest()->getText( 'returnto' );
2722 if ( $returntoquery == null ) {
2723 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2726 if ( $returnto === '' ) {
2727 $returnto = Title
::newMainPage();
2730 if ( is_object( $returnto ) ) {
2731 $titleObj = $returnto;
2733 $titleObj = Title
::newFromText( $returnto );
2735 // We don't want people to return to external interwiki. That
2736 // might potentially be used as part of a phishing scheme
2737 if ( !is_object( $titleObj ) ||
$titleObj->isExternal() ) {
2738 $titleObj = Title
::newMainPage();
2741 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2744 private function getRlClientContext() {
2745 if ( !$this->rlClientContext
) {
2746 $query = ResourceLoader
::makeLoaderQuery(
2747 [], // modules; not relevant
2748 $this->getLanguage()->getCode(),
2749 $this->getSkin()->getSkinName(),
2750 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2751 null, // version; not relevant
2752 ResourceLoader
::inDebugMode(),
2753 null, // only; not relevant
2754 $this->isPrintable(),
2755 $this->getRequest()->getBool( 'handheld' )
2757 $this->rlClientContext
= new ResourceLoaderContext(
2758 $this->getResourceLoader(),
2759 new FauxRequest( $query )
2762 return $this->rlClientContext
;
2766 * Call this to freeze the module queue and JS config and create a formatter.
2768 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2769 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2770 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2771 * the module filters retroactively. Skins and extension hooks may also add modules until very
2772 * late in the request lifecycle.
2774 * @return ResourceLoaderClientHtml
2776 public function getRlClient() {
2777 if ( !$this->rlClient
) {
2778 $context = $this->getRlClientContext();
2779 $rl = $this->getResourceLoader();
2780 $this->addModules( [
2784 $this->addModuleStyles( [
2789 $this->getSkin()->setupSkinUserCss( $this );
2791 // Prepare exempt modules for buildExemptModules()
2792 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2794 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2796 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2797 // Separate user-specific batch for improved cache-hit ratio.
2798 $userBatch = [ 'user.styles', 'user' ];
2799 $siteBatch = array_diff( $moduleStyles, $userBatch );
2800 $dbr = wfGetDB( DB_REPLICA
);
2801 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2802 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2804 // Filter out modules handled by buildExemptModules()
2805 $moduleStyles = array_filter( $moduleStyles,
2806 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2807 $module = $rl->getModule( $name );
2809 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2810 $exemptStates[$name] = 'ready';
2811 // Special case in buildExemptModules()
2814 $group = $module->getGroup();
2815 if ( isset( $exemptGroups[$group] ) ) {
2816 $exemptStates[$name] = 'ready';
2817 if ( !$module->isKnownEmpty( $context ) ) {
2818 // E.g. Don't output empty <styles>
2819 $exemptGroups[$group][] = $name;
2827 $this->rlExemptStyleModules
= $exemptGroups;
2829 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2830 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2831 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2832 if ( !$isUserModuleFiltered ) {
2833 // Manually handled by getBottomScripts()
2834 $userModule = $rl->getModule( 'user' );
2835 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2838 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2841 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2842 $rlClient->setConfig( $this->getJSVars() );
2843 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2844 $rlClient->setModuleStyles( $moduleStyles );
2845 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2846 $rlClient->setExemptStates( $exemptStates );
2847 $this->rlClient
= $rlClient;
2849 return $this->rlClient
;
2853 * @param Skin $sk The given Skin
2854 * @param bool $includeStyle Unused
2855 * @return string The doctype, opening "<html>", and head element.
2857 public function headElement( Skin
$sk, $includeStyle = true ) {
2860 $userdir = $this->getLanguage()->getDir();
2861 $sitedir = $wgContLang->getDir();
2864 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2865 $this->getRlClient()->getDocumentAttributes(),
2866 $sk->getHtmlElementAttributes()
2868 $pieces[] = Html
::openElement( 'head' );
2870 if ( $this->getHTMLTitle() == '' ) {
2871 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2874 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2875 // Add <meta charset="UTF-8">
2876 // This should be before <title> since it defines the charset used by
2877 // text including the text inside <title>.
2878 // The spec recommends defining XHTML5's charset using the XML declaration
2880 // Our XML declaration is output by Html::htmlHeader.
2881 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2882 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2883 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2886 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2887 $pieces[] = $this->getRlClient()->getHeadHtml();
2888 $pieces[] = $this->buildExemptModules();
2889 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2890 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2891 $pieces[] = Html
::closeElement( 'head' );
2894 $bodyClasses[] = 'mediawiki';
2896 # Classes for LTR/RTL directionality support
2897 $bodyClasses[] = $userdir;
2898 $bodyClasses[] = "sitedir-$sitedir";
2900 $underline = $this->getUser()->getOption( 'underline' );
2901 if ( $underline < 2 ) {
2902 // The following classes can be used here:
2903 // * mw-underline-always
2904 // * mw-underline-never
2905 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2908 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2909 # A <body> class is probably not the best way to do this . . .
2910 $bodyClasses[] = 'capitalize-all-nouns';
2913 // Parser feature migration class
2914 // The idea is that this will eventually be removed, after the wikitext
2915 // which requires it is cleaned up.
2916 $bodyClasses[] = 'mw-hide-empty-elt';
2918 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2919 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2921 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2924 // While the implode() is not strictly needed, it's used for backwards compatibility
2925 // (this used to be built as a string and hooks likely still expect that).
2926 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2928 // Allow skins and extensions to add body attributes they need
2929 $sk->addToBodyAttributes( $this, $bodyAttrs );
2930 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2932 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2934 return self
::combineWrappedStrings( $pieces );
2938 * Get a ResourceLoader object associated with this OutputPage
2940 * @return ResourceLoader
2942 public function getResourceLoader() {
2943 if ( is_null( $this->mResourceLoader
) ) {
2944 $this->mResourceLoader
= new ResourceLoader(
2946 LoggerFactory
::getInstance( 'resourceloader' )
2949 return $this->mResourceLoader
;
2953 * Explicily load or embed modules on a page.
2955 * @param array|string $modules One or more module names
2956 * @param string $only ResourceLoaderModule TYPE_ class constant
2957 * @param array $extraQuery [optional] Array with extra query parameters for the request
2958 * @return string|WrappedStringList HTML
2960 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2961 // Apply 'target' and 'origin' filters
2962 $modules = $this->filterModules( (array)$modules, null, $only );
2964 return ResourceLoaderClientHtml
::makeLoad(
2965 $this->getRlClientContext(),
2973 * Combine WrappedString chunks and filter out empty ones
2975 * @param array $chunks
2976 * @return string|WrappedStringList HTML
2978 protected static function combineWrappedStrings( array $chunks ) {
2979 // Filter out empty values
2980 $chunks = array_filter( $chunks, 'strlen' );
2981 return WrappedString
::join( "\n", $chunks );
2984 private function isUserJsPreview() {
2985 return $this->getConfig()->get( 'AllowUserJs' )
2986 && $this->getTitle()
2987 && $this->getTitle()->isJsSubpage()
2988 && $this->userCanPreview();
2991 private function isUserCssPreview() {
2992 return $this->getConfig()->get( 'AllowUserCss' )
2993 && $this->getTitle()
2994 && $this->getTitle()->isCssSubpage()
2995 && $this->userCanPreview();
2999 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
3000 * legacy scripts ($this->mScripts), and user JS.
3002 * @return string|WrappedStringList HTML
3004 public function getBottomScripts() {
3006 $chunks[] = $this->getRlClient()->getBodyHtml();
3008 // Legacy non-ResourceLoader scripts
3009 $chunks[] = $this->mScripts
;
3011 // Exempt 'user' module
3012 // - May need excludepages for live preview. (T28283)
3013 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3014 // ensures execution is scheduled after the "site" module.
3015 // - Don't load if module state is already resolved as "ready".
3016 if ( $this->rlUserModuleState
=== 'loading' ) {
3017 if ( $this->isUserJsPreview() ) {
3018 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3019 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3021 $chunks[] = ResourceLoader
::makeInlineScript(
3022 Xml
::encodeJsCall( 'mw.loader.using', [
3026 . Xml
::encodeJsCall( '$.globalEval', [
3027 $this->getRequest()->getText( 'wpTextbox1' )
3033 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3034 // asynchronously and may arrive *after* the inline script here. So the previewed code
3035 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3036 // Similarly, when previewing ./common.js and the user module does arrive first,
3037 // it will arrive without common.js and the inline script runs after.
3038 // Thus running common after the excluded subpage.
3041 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3045 if ( $this->limitReportJSData
) {
3046 $chunks[] = ResourceLoader
::makeInlineScript(
3047 ResourceLoader
::makeConfigSetScript(
3048 [ 'wgPageParseReport' => $this->limitReportJSData
]
3053 return self
::combineWrappedStrings( $chunks );
3057 * Get the javascript config vars to include on this page
3059 * @return array Array of javascript config vars
3062 public function getJsConfigVars() {
3063 return $this->mJsConfigVars
;
3067 * Add one or more variables to be set in mw.config in JavaScript
3069 * @param string|array $keys Key or array of key/value pairs
3070 * @param mixed $value [optional] Value of the configuration variable
3072 public function addJsConfigVars( $keys, $value = null ) {
3073 if ( is_array( $keys ) ) {
3074 foreach ( $keys as $key => $value ) {
3075 $this->mJsConfigVars
[$key] = $value;
3080 $this->mJsConfigVars
[$keys] = $value;
3084 * Get an array containing the variables to be set in mw.config in JavaScript.
3086 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3087 * - in other words, page-independent/site-wide variables (without state).
3088 * You will only be adding bloat to the html page and causing page caches to
3089 * have to be purged on configuration changes.
3092 public function getJSVars() {
3097 $canonicalSpecialPageName = false; # T23115
3099 $title = $this->getTitle();
3100 $ns = $title->getNamespace();
3101 $canonicalNamespace = MWNamespace
::exists( $ns )
3102 ? MWNamespace
::getCanonicalName( $ns )
3103 : $title->getNsText();
3105 $sk = $this->getSkin();
3106 // Get the relevant title so that AJAX features can use the correct page name
3107 // when making API requests from certain special pages (T36972).
3108 $relevantTitle = $sk->getRelevantTitle();
3109 $relevantUser = $sk->getRelevantUser();
3111 if ( $ns == NS_SPECIAL
) {
3112 list( $canonicalSpecialPageName, /*...*/ ) =
3113 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3114 } elseif ( $this->canUseWikiPage() ) {
3115 $wikiPage = $this->getWikiPage();
3116 $curRevisionId = $wikiPage->getLatest();
3117 $articleId = $wikiPage->getId();
3120 $lang = $title->getPageViewLanguage();
3122 // Pre-process information
3123 $separatorTransTable = $lang->separatorTransformTable();
3124 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3125 $compactSeparatorTransTable = [
3126 implode( "\t", array_keys( $separatorTransTable ) ),
3127 implode( "\t", $separatorTransTable ),
3129 $digitTransTable = $lang->digitTransformTable();
3130 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3131 $compactDigitTransTable = [
3132 implode( "\t", array_keys( $digitTransTable ) ),
3133 implode( "\t", $digitTransTable ),
3136 $user = $this->getUser();
3139 'wgCanonicalNamespace' => $canonicalNamespace,
3140 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3141 'wgNamespaceNumber' => $title->getNamespace(),
3142 'wgPageName' => $title->getPrefixedDBkey(),
3143 'wgTitle' => $title->getText(),
3144 'wgCurRevisionId' => $curRevisionId,
3145 'wgRevisionId' => (int)$this->getRevisionId(),
3146 'wgArticleId' => $articleId,
3147 'wgIsArticle' => $this->isArticle(),
3148 'wgIsRedirect' => $title->isRedirect(),
3149 'wgAction' => Action
::getActionName( $this->getContext() ),
3150 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3151 'wgUserGroups' => $user->getEffectiveGroups(),
3152 'wgCategories' => $this->getCategories(),
3153 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3154 'wgPageContentLanguage' => $lang->getCode(),
3155 'wgPageContentModel' => $title->getContentModel(),
3156 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3157 'wgDigitTransformTable' => $compactDigitTransTable,
3158 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3159 'wgMonthNames' => $lang->getMonthNamesArray(),
3160 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3161 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3162 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3163 'wgRequestId' => WebRequest
::getRequestId(),
3166 if ( $user->isLoggedIn() ) {
3167 $vars['wgUserId'] = $user->getId();
3168 $vars['wgUserEditCount'] = $user->getEditCount();
3169 $userReg = $user->getRegistration();
3170 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3171 // Get the revision ID of the oldest new message on the user's talk
3172 // page. This can be used for constructing new message alerts on
3174 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3177 if ( $wgContLang->hasVariants() ) {
3178 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3180 // Same test as SkinTemplate
3181 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3182 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3184 foreach ( $title->getRestrictionTypes() as $type ) {
3185 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3188 if ( $title->isMainPage() ) {
3189 $vars['wgIsMainPage'] = true;
3192 if ( $this->mRedirectedFrom
) {
3193 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3196 if ( $relevantUser ) {
3197 $vars['wgRelevantUserName'] = $relevantUser->getName();
3200 // Allow extensions to add their custom variables to the mw.config map.
3201 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3202 // page-dependant but site-wide (without state).
3203 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3204 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3206 // Merge in variables from addJsConfigVars last
3207 return array_merge( $vars, $this->getJsConfigVars() );
3211 * To make it harder for someone to slip a user a fake
3212 * user-JavaScript or user-CSS preview, a random token
3213 * is associated with the login session. If it's not
3214 * passed back with the preview request, we won't render
3219 public function userCanPreview() {
3220 $request = $this->getRequest();
3222 $request->getVal( 'action' ) !== 'submit' ||
3223 !$request->getCheck( 'wpPreview' ) ||
3224 !$request->wasPosted()
3229 $user = $this->getUser();
3231 if ( !$user->isLoggedIn() ) {
3232 // Anons have predictable edit tokens
3235 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3239 $title = $this->getTitle();
3240 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3243 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3244 // Don't execute another user's CSS or JS on preview (T85855)
3248 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3249 if ( count( $errors ) !== 0 ) {
3257 * @return array Array in format "link name or number => 'link html'".
3259 public function getHeadLinksArray() {
3263 $config = $this->getConfig();
3265 $canonicalUrl = $this->mCanonicalUrl
;
3267 $tags['meta-generator'] = Html
::element( 'meta', [
3268 'name' => 'generator',
3269 'content' => "MediaWiki $wgVersion",
3272 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3273 $tags['meta-referrer'] = Html
::element( 'meta', [
3274 'name' => 'referrer',
3275 'content' => $config->get( 'ReferrerPolicy' )
3279 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3280 if ( $p !== 'index,follow' ) {
3281 // http://www.robotstxt.org/wc/meta-user.html
3282 // Only show if it's different from the default robots policy
3283 $tags['meta-robots'] = Html
::element( 'meta', [
3289 foreach ( $this->mMetatags
as $tag ) {
3290 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3292 $tag[0] = substr( $tag[0], 5 );
3293 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3298 $tagName = "meta-{$tag[0]}";
3299 if ( isset( $tags[$tagName] ) ) {
3300 $tagName .= $tag[1];
3302 $tags[$tagName] = Html
::element( 'meta',
3305 'content' => $tag[1]
3310 foreach ( $this->mLinktags
as $tag ) {
3311 $tags[] = Html
::element( 'link', $tag );
3314 # Universal edit button
3315 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3316 $user = $this->getUser();
3317 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3318 && ( $this->getTitle()->exists() ||
3319 $this->getTitle()->quickUserCan( 'create', $user ) )
3321 // Original UniversalEditButton
3322 $msg = $this->msg( 'edit' )->text();
3323 $tags['universal-edit-button'] = Html
::element( 'link', [
3324 'rel' => 'alternate',
3325 'type' => 'application/x-wiki',
3327 'href' => $this->getTitle()->getEditURL(),
3329 // Alternate edit link
3330 $tags['alternative-edit'] = Html
::element( 'link', [
3333 'href' => $this->getTitle()->getEditURL(),
3338 # Generally the order of the favicon and apple-touch-icon links
3339 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3340 # uses whichever one appears later in the HTML source. Make sure
3341 # apple-touch-icon is specified first to avoid this.
3342 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3343 $tags['apple-touch-icon'] = Html
::element( 'link', [
3344 'rel' => 'apple-touch-icon',
3345 'href' => $config->get( 'AppleTouchIcon' )
3349 if ( $config->get( 'Favicon' ) !== false ) {
3350 $tags['favicon'] = Html
::element( 'link', [
3351 'rel' => 'shortcut icon',
3352 'href' => $config->get( 'Favicon' )
3356 # OpenSearch description link
3357 $tags['opensearch'] = Html
::element( 'link', [
3359 'type' => 'application/opensearchdescription+xml',
3360 'href' => wfScript( 'opensearch_desc' ),
3361 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3364 if ( $config->get( 'EnableAPI' ) ) {
3365 # Real Simple Discovery link, provides auto-discovery information
3366 # for the MediaWiki API (and potentially additional custom API
3367 # support such as WordPress or Twitter-compatible APIs for a
3368 # blogging extension, etc)
3369 $tags['rsd'] = Html
::element( 'link', [
3371 'type' => 'application/rsd+xml',
3372 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3373 // Whether RSD accepts relative or protocol-relative URLs is completely
3374 // undocumented, though.
3375 'href' => wfExpandUrl( wfAppendQuery(
3377 [ 'action' => 'rsd' ] ),
3384 if ( !$config->get( 'DisableLangConversion' ) ) {
3385 $lang = $this->getTitle()->getPageLanguage();
3386 if ( $lang->hasVariants() ) {
3387 $variants = $lang->getVariants();
3388 foreach ( $variants as $variant ) {
3389 $tags["variant-$variant"] = Html
::element( 'link', [
3390 'rel' => 'alternate',
3391 'hreflang' => wfBCP47( $variant ),
3392 'href' => $this->getTitle()->getLocalURL(
3393 [ 'variant' => $variant ] )
3397 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3398 $tags["variant-x-default"] = Html
::element( 'link', [
3399 'rel' => 'alternate',
3400 'hreflang' => 'x-default',
3401 'href' => $this->getTitle()->getLocalURL() ] );
3406 if ( $this->copyrightUrl
!== null ) {
3407 $copyright = $this->copyrightUrl
;
3410 if ( $config->get( 'RightsPage' ) ) {
3411 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3414 $copyright = $copy->getLocalURL();
3418 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3419 $copyright = $config->get( 'RightsUrl' );
3424 $tags['copyright'] = Html
::element( 'link', [
3425 'rel' => 'copyright',
3426 'href' => $copyright ]
3431 if ( $config->get( 'Feed' ) ) {
3434 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3435 # Use the page name for the title. In principle, this could
3436 # lead to issues with having the same name for different feeds
3437 # corresponding to the same page, but we can't avoid that at
3440 $feedLinks[] = $this->feedLink(
3443 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3445 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3450 # Recent changes feed should appear on every page (except recentchanges,
3451 # that would be redundant). Put it after the per-page feed to avoid
3452 # changing existing behavior. It's still available, probably via a
3453 # menu in your browser. Some sites might have a different feed they'd
3454 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3455 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3456 # If so, use it instead.
3457 $sitename = $config->get( 'Sitename' );
3458 if ( $config->get( 'OverrideSiteFeed' ) ) {
3459 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3460 // Note, this->feedLink escapes the url.
3461 $feedLinks[] = $this->feedLink(
3464 $this->msg( "site-{$type}-feed", $sitename )->text()
3467 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3468 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3469 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3470 $feedLinks[] = $this->feedLink(
3472 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3473 # For grep: 'site-rss-feed', 'site-atom-feed'
3474 $this->msg( "site-{$format}-feed", $sitename )->text()
3479 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3480 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3481 # use OutputPage::addFeedLink() instead.
3482 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3484 $tags +
= $feedLinks;
3488 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3489 if ( $canonicalUrl !== false ) {
3490 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3492 if ( $this->isArticleRelated() ) {
3493 // This affects all requests where "setArticleRelated" is true. This is
3494 // typically all requests that show content (query title, curid, oldid, diff),
3495 // and all wikipage actions (edit, delete, purge, info, history etc.).
3496 // It does not apply to File pages and Special pages.
3497 // 'history' and 'info' actions address page metadata rather than the page
3498 // content itself, so they may not be canonicalized to the view page url.
3499 // TODO: this ought to be better encapsulated in the Action class.
3500 $action = Action
::getActionName( $this->getContext() );
3501 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3502 $query = "action={$action}";
3506 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3508 $reqUrl = $this->getRequest()->getRequestURL();
3509 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3513 if ( $canonicalUrl !== false ) {
3514 $tags[] = Html
::element( 'link', [
3515 'rel' => 'canonical',
3516 'href' => $canonicalUrl
3524 * @return string HTML tag links to be put in the header.
3525 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3526 * OutputPage::getHeadLinksArray directly.
3528 public function getHeadLinks() {
3529 wfDeprecated( __METHOD__
, '1.24' );
3530 return implode( "\n", $this->getHeadLinksArray() );
3534 * Generate a "<link rel/>" for a feed.
3536 * @param string $type Feed type
3537 * @param string $url URL to the feed
3538 * @param string $text Value of the "title" attribute
3539 * @return string HTML fragment
3541 private function feedLink( $type, $url, $text ) {
3542 return Html
::element( 'link', [
3543 'rel' => 'alternate',
3544 'type' => "application/$type+xml",
3551 * Add a local or specified stylesheet, with the given media options.
3552 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3554 * @param string $style URL to the file
3555 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3556 * @param string $condition For IE conditional comments, specifying an IE version
3557 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3559 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3562 $options['media'] = $media;
3565 $options['condition'] = $condition;
3568 $options['dir'] = $dir;
3570 $this->styles
[$style] = $options;
3574 * Adds inline CSS styles
3575 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3577 * @param mixed $style_css Inline CSS
3578 * @param string $flip Set to 'flip' to flip the CSS if needed
3580 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3581 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3582 # If wanted, and the interface is right-to-left, flip the CSS
3583 $style_css = CSSJanus
::transform( $style_css, true, false );
3585 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3589 * Build exempt modules and legacy non-ResourceLoader styles.
3591 * @return string|WrappedStringList HTML
3593 protected function buildExemptModules() {
3597 // Things that go after the ResourceLoaderDynamicStyles marker
3600 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3601 if ( $this->isUserCssPreview() ) {
3602 $append[] = $this->makeResourceLoaderLink(
3604 ResourceLoaderModule
::TYPE_STYLES
,
3605 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3608 // Load the previewed CSS. Janus it if needed.
3609 // User-supplied CSS is assumed to in the wiki's content language.
3610 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3611 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3612 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3614 $append[] = Html
::inlineStyle( $previewedCSS );
3617 // We want site, private and user styles to override dynamically added styles from
3618 // general modules, but we want dynamically added styles to override statically added
3619 // style modules. So the order has to be:
3620 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3621 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3622 // - ResourceLoaderDynamicStyles marker
3623 // - site/private/user styles
3625 // Add legacy styles added through addStyle()/addInlineStyle() here
3626 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3628 $chunks[] = Html
::element(
3630 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3633 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3634 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3635 ResourceLoaderModule
::TYPE_STYLES
3639 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3645 public function buildCssLinksArray() {
3648 // Add any extension CSS
3649 foreach ( $this->mExtStyles
as $url ) {
3650 $this->addStyle( $url );
3652 $this->mExtStyles
= [];
3654 foreach ( $this->styles
as $file => $options ) {
3655 $link = $this->styleLink( $file, $options );
3657 $links[$file] = $link;
3664 * Generate \<link\> tags for stylesheets
3666 * @param string $style URL to the file
3667 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3668 * @return string HTML fragment
3670 protected function styleLink( $style, array $options ) {
3671 if ( isset( $options['dir'] ) ) {
3672 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3677 if ( isset( $options['media'] ) ) {
3678 $media = self
::transformCssMedia( $options['media'] );
3679 if ( is_null( $media ) ) {
3686 if ( substr( $style, 0, 1 ) == '/' ||
3687 substr( $style, 0, 5 ) == 'http:' ||
3688 substr( $style, 0, 6 ) == 'https:' ) {
3691 $config = $this->getConfig();
3692 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3693 $config->get( 'StyleVersion' );
3696 $link = Html
::linkedStyle( $url, $media );
3698 if ( isset( $options['condition'] ) ) {
3699 $condition = htmlspecialchars( $options['condition'] );
3700 $link = "<!--[if $condition]>$link<![endif]-->";
3706 * Transform path to web-accessible static resource.
3708 * This is used to add a validation hash as query string.
3709 * This aids various behaviors:
3711 * - Put long Cache-Control max-age headers on responses for improved
3712 * cache performance.
3713 * - Get the correct version of a file as expected by the current page.
3714 * - Instantly get the updated version of a file after deployment.
3716 * Avoid using this for urls included in HTML as otherwise clients may get different
3717 * versions of a resource when navigating the site depending on when the page was cached.
3718 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3719 * an external stylesheet).
3722 * @param Config $config
3723 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3724 * @return string URL
3726 public static function transformResourcePath( Config
$config, $path ) {
3730 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3731 if ( $remotePathPrefix === '' ) {
3732 // The configured base path is required to be empty string for
3733 // wikis in the domain root
3736 $remotePath = $remotePathPrefix;
3738 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3739 // - Path is outside wgResourceBasePath, ignore.
3740 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3743 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3744 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3745 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3746 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3747 $uploadPath = $config->get( 'UploadPath' );
3748 if ( strpos( $path, $uploadPath ) === 0 ) {
3749 $localDir = $config->get( 'UploadDirectory' );
3750 $remotePathPrefix = $remotePath = $uploadPath;
3753 $path = RelPath\
getRelativePath( $path, $remotePath );
3754 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3758 * Utility method for transformResourceFilePath().
3760 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3763 * @param string $remotePath URL path prefix that points to $localPath
3764 * @param string $localPath File directory exposed at $remotePath
3765 * @param string $file Path to target file relative to $localPath
3766 * @return string URL
3768 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3769 $hash = md5_file( "$localPath/$file" );
3770 if ( $hash === false ) {
3771 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3774 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3778 * Transform "media" attribute based on request parameters
3780 * @param string $media Current value of the "media" attribute
3781 * @return string Modified value of the "media" attribute, or null to skip
3784 public static function transformCssMedia( $media ) {
3787 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3788 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3790 // Switch in on-screen display for media testing
3792 'printable' => 'print',
3793 'handheld' => 'handheld',
3795 foreach ( $switches as $switch => $targetMedia ) {
3796 if ( $wgRequest->getBool( $switch ) ) {
3797 if ( $media == $targetMedia ) {
3799 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3800 /* This regex will not attempt to understand a comma-separated media_query_list
3802 * Example supported values for $media:
3803 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3804 * Example NOT supported value for $media:
3805 * '3d-glasses, screen, print and resolution > 90dpi'
3807 * If it's a print request, we never want any kind of screen stylesheets
3808 * If it's a handheld request (currently the only other choice with a switch),
3809 * we don't want simple 'screen' but we might want screen queries that
3810 * have a max-width or something, so we'll pass all others on and let the
3811 * client do the query.
3813 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3824 * Add a wikitext-formatted message to the output.
3825 * This is equivalent to:
3827 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3829 public function addWikiMsg( /*...*/ ) {
3830 $args = func_get_args();
3831 $name = array_shift( $args );
3832 $this->addWikiMsgArray( $name, $args );
3836 * Add a wikitext-formatted message to the output.
3837 * Like addWikiMsg() except the parameters are taken as an array
3838 * instead of a variable argument list.
3840 * @param string $name
3841 * @param array $args
3843 public function addWikiMsgArray( $name, $args ) {
3844 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3848 * This function takes a number of message/argument specifications, wraps them in
3849 * some overall structure, and then parses the result and adds it to the output.
3851 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3852 * and so on. The subsequent arguments may be either
3853 * 1) strings, in which case they are message names, or
3854 * 2) arrays, in which case, within each array, the first element is the message
3855 * name, and subsequent elements are the parameters to that message.
3857 * Don't use this for messages that are not in the user's interface language.
3861 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3865 * $wgOut->addWikiText( "<div class='error'>\n"
3866 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3868 * The newline after the opening div is needed in some wikitext. See T21226.
3870 * @param string $wrap
3872 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3873 $msgSpecs = func_get_args();
3874 array_shift( $msgSpecs );
3875 $msgSpecs = array_values( $msgSpecs );
3877 foreach ( $msgSpecs as $n => $spec ) {
3878 if ( is_array( $spec ) ) {
3880 $name = array_shift( $args );
3881 if ( isset( $args['options'] ) ) {
3882 unset( $args['options'] );
3884 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3892 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3894 $this->addWikiText( $s );
3898 * Enables/disables TOC, doesn't override __NOTOC__
3902 public function enableTOC( $flag = true ) {
3903 $this->mEnableTOC
= $flag;
3910 public function isTOCEnabled() {
3911 return $this->mEnableTOC
;
3915 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3919 public function enableSectionEditLinks( $flag = true ) {
3920 $this->mEnableSectionEditLinks
= $flag;
3927 public function sectionEditLinksEnabled() {
3928 return $this->mEnableSectionEditLinks
;
3932 * Helper function to setup the PHP implementation of OOUI to use in this request.
3935 * @param String $skinName The Skin name to determine the correct OOUI theme
3936 * @param String $dir Language direction
3938 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3939 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3940 // Make keys (skin names) lowercase for case-insensitive matching.
3941 $themes = array_change_key_case( $themes, CASE_LOWER
);
3942 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3943 // For example, 'OOUI\MediaWikiTheme'.
3944 $themeClass = "OOUI\\{$theme}Theme";
3945 OOUI\Theme
::setSingleton( new $themeClass() );
3946 OOUI\Element
::setDefaultDir( $dir );
3950 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3951 * MediaWiki and this OutputPage instance.
3955 public function enableOOUI() {
3957 strtolower( $this->getSkin()->getSkinName() ),
3958 $this->getLanguage()->getDir()
3960 $this->addModuleStyles( [
3961 'oojs-ui-core.styles',
3962 'oojs-ui.styles.icons',
3963 'oojs-ui.styles.indicators',
3964 'oojs-ui.styles.textures',
3965 'mediawiki.widgets.styles',