3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\Session\SessionManager
;
25 use WrappedString\WrappedString
;
26 use WrappedString\WrappedStringList
;
29 * This class should be covered by a general architecture document which does
30 * not exist as of January 2011. This is one of the Core classes and should
31 * be read at least once by any new developers.
33 * This class is used to prepare the final rendering. A skin is then
34 * applied to the output parameters (links, javascript, html, categories ...).
36 * @todo FIXME: Another class handles sending the whole page to the client.
38 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
43 class OutputPage
extends ContextSource
{
44 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
45 protected $mMetatags = [];
48 protected $mLinktags = [];
51 protected $mCanonicalUrl = false;
54 * @var array Additional stylesheets. Looks like this is for extensions.
55 * Might be replaced by ResourceLoader.
57 protected $mExtStyles = [];
60 * @var string Should be private - has getter and setter. Contains
62 public $mPagetitle = '';
65 * @var string Contains all of the "<body>" content. Should be private we
66 * got set/get accessors and the append() method.
68 public $mBodytext = '';
70 /** @var string Stores contents of "<title>" tag */
71 private $mHTMLtitle = '';
74 * @var bool Is the displayed content related to the source of the
75 * corresponding wiki article.
77 private $mIsarticle = false;
79 /** @var bool Stores "article flag" toggle. */
80 private $mIsArticleRelated = true;
83 * @var bool We have to set isPrintable(). Some pages should
84 * never be printed (ex: redirections).
86 private $mPrintable = false;
89 * @var array Contains the page subtitle. Special pages usually have some
90 * links here. Don't confuse with site subtitle added by skins.
92 private $mSubtitle = [];
95 public $mRedirect = '';
98 protected $mStatusCode;
101 * @var string Used for sending cache control.
102 * The whole caching system should probably be moved into its own class.
104 protected $mLastModified = '';
107 protected $mCategoryLinks = [];
110 protected $mCategories = [
116 protected $mIndicators = [];
118 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
119 private $mLanguageLinks = [];
122 * Used for JavaScript (predates ResourceLoader)
123 * @todo We should split JS / CSS.
124 * mScripts content is inserted as is in "<head>" by Skin. This might
125 * contain either a link to a stylesheet or inline CSS.
127 private $mScripts = '';
129 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
130 protected $mInlineStyles = '';
133 * @var string Used by skin template.
134 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 public $mPageLinkTitle = '';
138 /** @var array Array of elements in "<head>". Parser might add its own headers! */
139 protected $mHeadItems = [];
142 protected $mModules = [];
145 protected $mModuleScripts = [];
148 protected $mModuleStyles = [];
150 /** @var ResourceLoader */
151 protected $mResourceLoader;
153 /** @var ResourceLoaderClientHtml */
156 /** @var ResourceLoaderContext */
157 private $rlClientContext;
160 private $rlUserModuleState;
163 private $rlExemptStyleModules;
166 protected $mJsConfigVars = [];
169 protected $mTemplateIds = [];
172 protected $mImageTimeKeys = [];
175 public $mRedirectCode = '';
177 protected $mFeedLinksAppendQuery = null;
180 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
181 * @see ResourceLoaderModule::$origin
182 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
184 protected $mAllowedModules = [
185 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
188 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
189 protected $mDoNothing = false;
194 protected $mContainsNewMagic = 0;
197 * lazy initialised, use parserOptions()
200 protected $mParserOptions = null;
203 * Handles the Atom / RSS links.
204 * We probably only support Atom in 2011.
205 * @see $wgAdvertisedFeedTypes
207 private $mFeedLinks = [];
209 // Gwicke work on squid caching? Roughly from 2003.
210 protected $mEnableClientCache = true;
212 /** @var bool Flag if output should only contain the body of the article. */
213 private $mArticleBodyOnly = false;
216 protected $mNewSectionLink = false;
219 protected $mHideNewSectionLink = false;
222 * @var bool Comes from the parser. This was probably made to load CSS/JS
223 * only if we had "<gallery>". Used directly in CategoryPage.php.
224 * Looks like ResourceLoader can replace this.
226 public $mNoGallery = false;
229 private $mPageTitleActionText = '';
231 /** @var int Cache stuff. Looks like mEnableClientCache */
232 protected $mCdnMaxage = 0;
233 /** @var int Upper limit on mCdnMaxage */
234 protected $mCdnMaxageLimit = INF
;
237 * @var bool Controls if anti-clickjacking / frame-breaking headers will
238 * be sent. This should be done for pages where edit actions are possible.
239 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
241 protected $mPreventClickjacking = true;
243 /** @var int To include the variable {{REVISIONID}} */
244 private $mRevisionId = null;
247 private $mRevisionTimestamp = null;
250 protected $mFileVersion = null;
253 * @var array An array of stylesheet filenames (relative from skins path),
254 * with options for CSS media, IE conditions, and RTL/LTR direction.
255 * For internal use; add settings in the skin via $this->addStyle()
257 * Style again! This seems like a code duplication since we already have
258 * mStyles. This is what makes Open Source amazing.
260 protected $styles = [];
262 private $mIndexPolicy = 'index';
263 private $mFollowPolicy = 'follow';
264 private $mVaryHeader = [
265 'Accept-Encoding' => [ 'match=gzip' ],
269 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
274 private $mRedirectedFrom = null;
277 * Additional key => value data
279 private $mProperties = [];
282 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
284 private $mTarget = null;
287 * @var bool Whether parser output should contain table of contents
289 private $mEnableTOC = true;
292 * @var bool Whether parser output should contain section edit links
294 private $mEnableSectionEditLinks = true;
297 * @var string|null The URL to send in a <link> element with rel=copyright
299 private $copyrightUrl;
301 /** @var array Profiling data */
302 private $limitReportData = [];
305 * Constructor for OutputPage. This should not be called directly.
306 * Instead a new RequestContext should be created and it will implicitly create
307 * a OutputPage tied to that context.
308 * @param IContextSource|null $context
310 function __construct( IContextSource
$context = null ) {
311 if ( $context === null ) {
312 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
313 wfDeprecated( __METHOD__
, '1.18' );
315 $this->setContext( $context );
320 * Redirect to $url rather than displaying the normal page
322 * @param string $url URL
323 * @param string $responsecode HTTP status code
325 public function redirect( $url, $responsecode = '302' ) {
326 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
327 $this->mRedirect
= str_replace( "\n", '', $url );
328 $this->mRedirectCode
= $responsecode;
332 * Get the URL to redirect to, or an empty string if not redirect URL set
336 public function getRedirect() {
337 return $this->mRedirect
;
341 * Set the copyright URL to send with the output.
342 * Empty string to omit, null to reset.
346 * @param string|null $url
348 public function setCopyrightUrl( $url ) {
349 $this->copyrightUrl
= $url;
353 * Set the HTTP status code to send with the output.
355 * @param int $statusCode
357 public function setStatusCode( $statusCode ) {
358 $this->mStatusCode
= $statusCode;
362 * Add a new "<meta>" tag
363 * To add an http-equiv meta tag, precede the name with "http:"
365 * @param string $name Tag name
366 * @param string $val Tag value
368 function addMeta( $name, $val ) {
369 array_push( $this->mMetatags
, [ $name, $val ] );
373 * Returns the current <meta> tags
378 public function getMetaTags() {
379 return $this->mMetatags
;
383 * Add a new \<link\> tag to the page header.
385 * Note: use setCanonicalUrl() for rel=canonical.
387 * @param array $linkarr Associative array of attributes.
389 function addLink( array $linkarr ) {
390 array_push( $this->mLinktags
, $linkarr );
394 * Returns the current <link> tags
399 public function getLinkTags() {
400 return $this->mLinktags
;
404 * Add a new \<link\> with "rel" attribute set to "meta"
406 * @param array $linkarr Associative array mapping attribute names to their
407 * values, both keys and values will be escaped, and the
408 * "rel" attribute will be automatically added
410 function addMetadataLink( array $linkarr ) {
411 $linkarr['rel'] = $this->getMetadataAttribute();
412 $this->addLink( $linkarr );
416 * Set the URL to be used for the <link rel=canonical>. This should be used
417 * in preference to addLink(), to avoid duplicate link tags.
420 function setCanonicalUrl( $url ) {
421 $this->mCanonicalUrl
= $url;
425 * Returns the URL to be used for the <link rel=canonical> if
429 * @return bool|string
431 public function getCanonicalUrl() {
432 return $this->mCanonicalUrl
;
436 * Get the value of the "rel" attribute for metadata links
440 public function getMetadataAttribute() {
441 # note: buggy CC software only reads first "meta" link
442 static $haveMeta = false;
444 return 'alternate meta';
452 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
453 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
456 * @param string $script Raw HTML
458 function addScript( $script ) {
459 $this->mScripts
.= $script;
463 * Register and add a stylesheet from an extension directory.
465 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
466 * @param string $url Path to sheet. Provide either a full url (beginning
467 * with 'http', etc) or a relative path from the document root
468 * (beginning with '/'). Otherwise it behaves identically to
469 * addStyle() and draws from the /skins folder.
471 public function addExtensionStyle( $url ) {
472 wfDeprecated( __METHOD__
, '1.27' );
473 array_push( $this->mExtStyles
, $url );
477 * Get all styles added by extensions
479 * @deprecated since 1.27
482 function getExtStyle() {
483 wfDeprecated( __METHOD__
, '1.27' );
484 return $this->mExtStyles
;
488 * Add a JavaScript file out of skins/common, or a given relative path.
489 * Internal use only. Use OutputPage::addModules() if possible.
491 * @param string $file Filename in skins/common or complete on-server path
493 * @param string $version Style version of the file. Defaults to $wgStyleVersion
495 public function addScriptFile( $file, $version = null ) {
496 // See if $file parameter is an absolute URL or begins with a slash
497 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
500 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
502 if ( is_null( $version ) ) {
503 $version = $this->getConfig()->get( 'StyleVersion' );
505 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
509 * Add a self-contained script tag with the given contents
510 * Internal use only. Use OutputPage::addModules() if possible.
512 * @param string $script JavaScript text, no script tags
514 public function addInlineScript( $script ) {
515 $this->mScripts
.= Html
::inlineScript( $script );
519 * Filter an array of modules to remove insufficiently trustworthy members, and modules
520 * which are no longer registered (eg a page is cached before an extension is disabled)
521 * @param array $modules
522 * @param string|null $position If not null, only return modules with this position
523 * @param string $type
526 protected function filterModules( array $modules, $position = null,
527 $type = ResourceLoaderModule
::TYPE_COMBINED
529 $resourceLoader = $this->getResourceLoader();
530 $filteredModules = [];
531 foreach ( $modules as $val ) {
532 $module = $resourceLoader->getModule( $val );
533 if ( $module instanceof ResourceLoaderModule
534 && $module->getOrigin() <= $this->getAllowedModules( $type )
535 && ( is_null( $position ) ||
$module->getPosition() == $position )
536 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
538 $filteredModules[] = $val;
541 return $filteredModules;
545 * Get the list of modules to include on this page
547 * @param bool $filter Whether to filter out insufficiently trustworthy modules
548 * @param string|null $position If not null, only return modules with this position
549 * @param string $param
550 * @return array Array of module names
552 public function getModules( $filter = false, $position = null, $param = 'mModules',
553 $type = ResourceLoaderModule
::TYPE_COMBINED
555 $modules = array_values( array_unique( $this->$param ) );
557 ?
$this->filterModules( $modules, $position, $type )
562 * Add one or more modules recognized by ResourceLoader. Modules added
563 * through this function will be loaded by ResourceLoader when the
566 * @param string|array $modules Module name (string) or array of module names
568 public function addModules( $modules ) {
569 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
573 * Get the list of module JS to include on this page
575 * @param bool $filter
576 * @param string|null $position
577 * @return array Array of module names
579 public function getModuleScripts( $filter = false, $position = null ) {
580 return $this->getModules( $filter, $position, 'mModuleScripts',
581 ResourceLoaderModule
::TYPE_SCRIPTS
586 * Add only JS of one or more modules recognized by ResourceLoader. Module
587 * scripts added through this function will be loaded by ResourceLoader when
590 * @param string|array $modules Module name (string) or array of module names
592 public function addModuleScripts( $modules ) {
593 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
597 * Get the list of module CSS to include on this page
599 * @param bool $filter
600 * @param string|null $position
601 * @return array Array of module names
603 public function getModuleStyles( $filter = false, $position = null ) {
604 return $this->getModules( $filter, $position, 'mModuleStyles',
605 ResourceLoaderModule
::TYPE_STYLES
610 * Add only CSS of one or more modules recognized by ResourceLoader.
612 * Module styles added through this function will be added using standard link CSS
613 * tags, rather than as a combined Javascript and CSS package. Thus, they will
614 * load when JavaScript is disabled (unless CSS also happens to be disabled).
616 * @param string|array $modules Module name (string) or array of module names
618 public function addModuleStyles( $modules ) {
619 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
623 * @return null|string ResourceLoader target
625 public function getTarget() {
626 return $this->mTarget
;
630 * Sets ResourceLoader target for load.php links. If null, will be omitted
632 * @param string|null $target
634 public function setTarget( $target ) {
635 $this->mTarget
= $target;
639 * Get an array of head items
643 function getHeadItemsArray() {
644 return $this->mHeadItems
;
648 * Add or replace a head item to the output
650 * Whenever possible, use more specific options like ResourceLoader modules,
651 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
652 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
653 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
654 * This would be your very LAST fallback.
656 * @param string $name Item name
657 * @param string $value Raw HTML
659 public function addHeadItem( $name, $value ) {
660 $this->mHeadItems
[$name] = $value;
664 * Add one or more head items to the output
667 * @param string|string[] $value Raw HTML
669 public function addHeadItems( $values ) {
670 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
674 * Check if the header item $name is already set
676 * @param string $name Item name
679 public function hasHeadItem( $name ) {
680 return isset( $this->mHeadItems
[$name] );
684 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
687 public function setETag( $tag ) {
691 * Set whether the output should only contain the body of the article,
692 * without any skin, sidebar, etc.
693 * Used e.g. when calling with "action=render".
695 * @param bool $only Whether to output only the body of the article
697 public function setArticleBodyOnly( $only ) {
698 $this->mArticleBodyOnly
= $only;
702 * Return whether the output will contain only the body of the article
706 public function getArticleBodyOnly() {
707 return $this->mArticleBodyOnly
;
711 * Set an additional output property
714 * @param string $name
715 * @param mixed $value
717 public function setProperty( $name, $value ) {
718 $this->mProperties
[$name] = $value;
722 * Get an additional output property
725 * @param string $name
726 * @return mixed Property value or null if not found
728 public function getProperty( $name ) {
729 if ( isset( $this->mProperties
[$name] ) ) {
730 return $this->mProperties
[$name];
737 * checkLastModified tells the client to use the client-cached page if
738 * possible. If successful, the OutputPage is disabled so that
739 * any future call to OutputPage->output() have no effect.
741 * Side effect: sets mLastModified for Last-Modified header
743 * @param string $timestamp
745 * @return bool True if cache-ok headers was sent.
747 public function checkLastModified( $timestamp ) {
748 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
749 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
752 $config = $this->getConfig();
753 if ( !$config->get( 'CachePages' ) ) {
754 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
758 $timestamp = wfTimestamp( TS_MW
, $timestamp );
760 'page' => $timestamp,
761 'user' => $this->getUser()->getTouched(),
762 'epoch' => $config->get( 'CacheEpoch' )
764 if ( $config->get( 'UseSquid' ) ) {
765 // bug 44570: the core page itself may not change, but resources might
766 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
768 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
770 $maxModified = max( $modifiedTimes );
771 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
773 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
774 if ( $clientHeader === false ) {
775 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
779 # IE sends sizes after the date like this:
780 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
781 # this breaks strtotime().
782 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
784 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
785 $clientHeaderTime = strtotime( $clientHeader );
786 MediaWiki\restoreWarnings
();
787 if ( !$clientHeaderTime ) {
789 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
792 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
796 foreach ( $modifiedTimes as $name => $value ) {
797 if ( $info !== '' ) {
800 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
803 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
804 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
805 wfDebug( __METHOD__
. ": effective Last-Modified: " .
806 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
807 if ( $clientHeaderTime < $maxModified ) {
808 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
813 # Give a 304 Not Modified response code and disable body output
814 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
815 ini_set( 'zlib.output_compression', 0 );
816 $this->getRequest()->response()->statusHeader( 304 );
817 $this->sendCacheControl();
820 // Don't output a compressed blob when using ob_gzhandler;
821 // it's technically against HTTP spec and seems to confuse
822 // Firefox when the response gets split over two packets.
823 wfClearOutputBuffers();
829 * Override the last modified timestamp
831 * @param string $timestamp New timestamp, in a format readable by
834 public function setLastModified( $timestamp ) {
835 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
839 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
841 * @param string $policy The literal string to output as the contents of
842 * the meta tag. Will be parsed according to the spec and output in
846 public function setRobotPolicy( $policy ) {
847 $policy = Article
::formatRobotPolicy( $policy );
849 if ( isset( $policy['index'] ) ) {
850 $this->setIndexPolicy( $policy['index'] );
852 if ( isset( $policy['follow'] ) ) {
853 $this->setFollowPolicy( $policy['follow'] );
858 * Set the index policy for the page, but leave the follow policy un-
861 * @param string $policy Either 'index' or 'noindex'.
864 public function setIndexPolicy( $policy ) {
865 $policy = trim( $policy );
866 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
867 $this->mIndexPolicy
= $policy;
872 * Set the follow policy for the page, but leave the index policy un-
875 * @param string $policy Either 'follow' or 'nofollow'.
878 public function setFollowPolicy( $policy ) {
879 $policy = trim( $policy );
880 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
881 $this->mFollowPolicy
= $policy;
886 * Set the new value of the "action text", this will be added to the
887 * "HTML title", separated from it with " - ".
889 * @param string $text New value of the "action text"
891 public function setPageTitleActionText( $text ) {
892 $this->mPageTitleActionText
= $text;
896 * Get the value of the "action text"
900 public function getPageTitleActionText() {
901 return $this->mPageTitleActionText
;
905 * "HTML title" means the contents of "<title>".
906 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
908 * @param string|Message $name
910 public function setHTMLTitle( $name ) {
911 if ( $name instanceof Message
) {
912 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
914 $this->mHTMLtitle
= $name;
919 * Return the "HTML title", i.e. the content of the "<title>" tag.
923 public function getHTMLTitle() {
924 return $this->mHTMLtitle
;
928 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
932 public function setRedirectedFrom( $t ) {
933 $this->mRedirectedFrom
= $t;
937 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
938 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
939 * but not bad tags like \<script\>. This function automatically sets
940 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
941 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
942 * good tags like \<i\> will be dropped entirely.
944 * @param string|Message $name
946 public function setPageTitle( $name ) {
947 if ( $name instanceof Message
) {
948 $name = $name->setContext( $this->getContext() )->text();
951 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
952 # but leave "<i>foobar</i>" alone
953 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
954 $this->mPagetitle
= $nameWithTags;
956 # change "<i>foo&bar</i>" to "foo&bar"
958 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
959 ->inContentLanguage()
964 * Return the "page title", i.e. the content of the \<h1\> tag.
968 public function getPageTitle() {
969 return $this->mPagetitle
;
973 * Set the Title object to use
977 public function setTitle( Title
$t ) {
978 $this->getContext()->setTitle( $t );
982 * Replace the subtitle with $str
984 * @param string|Message $str New value of the subtitle. String should be safe HTML.
986 public function setSubtitle( $str ) {
987 $this->clearSubtitle();
988 $this->addSubtitle( $str );
992 * Add $str to the subtitle
994 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
996 public function addSubtitle( $str ) {
997 if ( $str instanceof Message
) {
998 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1000 $this->mSubtitle
[] = $str;
1005 * Build message object for a subtitle containing a backlink to a page
1007 * @param Title $title Title to link to
1008 * @param array $query Array of additional parameters to include in the link
1012 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1013 if ( $title->isRedirect() ) {
1014 $query['redirect'] = 'no';
1016 return wfMessage( 'backlinksubtitle' )
1017 ->rawParams( Linker
::link( $title, null, [], $query ) );
1021 * Add a subtitle containing a backlink to a page
1023 * @param Title $title Title to link to
1024 * @param array $query Array of additional parameters to include in the link
1026 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1027 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1031 * Clear the subtitles
1033 public function clearSubtitle() {
1034 $this->mSubtitle
= [];
1042 public function getSubtitle() {
1043 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1047 * Set the page as printable, i.e. it'll be displayed with all
1048 * print styles included
1050 public function setPrintable() {
1051 $this->mPrintable
= true;
1055 * Return whether the page is "printable"
1059 public function isPrintable() {
1060 return $this->mPrintable
;
1064 * Disable output completely, i.e. calling output() will have no effect
1066 public function disable() {
1067 $this->mDoNothing
= true;
1071 * Return whether the output will be completely disabled
1075 public function isDisabled() {
1076 return $this->mDoNothing
;
1080 * Show an "add new section" link?
1084 public function showNewSectionLink() {
1085 return $this->mNewSectionLink
;
1089 * Forcibly hide the new section link?
1093 public function forceHideNewSectionLink() {
1094 return $this->mHideNewSectionLink
;
1098 * Add or remove feed links in the page header
1099 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1100 * for the new version
1101 * @see addFeedLink()
1103 * @param bool $show True: add default feeds, false: remove all feeds
1105 public function setSyndicated( $show = true ) {
1107 $this->setFeedAppendQuery( false );
1109 $this->mFeedLinks
= [];
1114 * Add default feeds to the page header
1115 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1116 * for the new version
1117 * @see addFeedLink()
1119 * @param string $val Query to append to feed links or false to output
1122 public function setFeedAppendQuery( $val ) {
1123 $this->mFeedLinks
= [];
1125 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1126 $query = "feed=$type";
1127 if ( is_string( $val ) ) {
1128 $query .= '&' . $val;
1130 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1135 * Add a feed link to the page header
1137 * @param string $format Feed type, should be a key of $wgFeedClasses
1138 * @param string $href URL
1140 public function addFeedLink( $format, $href ) {
1141 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1142 $this->mFeedLinks
[$format] = $href;
1147 * Should we output feed links for this page?
1150 public function isSyndicated() {
1151 return count( $this->mFeedLinks
) > 0;
1155 * Return URLs for each supported syndication format for this page.
1156 * @return array Associating format keys with URLs
1158 public function getSyndicationLinks() {
1159 return $this->mFeedLinks
;
1163 * Will currently always return null
1167 public function getFeedAppendQuery() {
1168 return $this->mFeedLinksAppendQuery
;
1172 * Set whether the displayed content is related to the source of the
1173 * corresponding article on the wiki
1174 * Setting true will cause the change "article related" toggle to true
1178 public function setArticleFlag( $v ) {
1179 $this->mIsarticle
= $v;
1181 $this->mIsArticleRelated
= $v;
1186 * Return whether the content displayed page is related to the source of
1187 * the corresponding article on the wiki
1191 public function isArticle() {
1192 return $this->mIsarticle
;
1196 * Set whether this page is related an article on the wiki
1197 * Setting false will cause the change of "article flag" toggle to false
1201 public function setArticleRelated( $v ) {
1202 $this->mIsArticleRelated
= $v;
1204 $this->mIsarticle
= false;
1209 * Return whether this page is related an article on the wiki
1213 public function isArticleRelated() {
1214 return $this->mIsArticleRelated
;
1218 * Add new language links
1220 * @param array $newLinkArray Associative array mapping language code to the page
1223 public function addLanguageLinks( array $newLinkArray ) {
1224 $this->mLanguageLinks +
= $newLinkArray;
1228 * Reset the language links and add new language links
1230 * @param array $newLinkArray Associative array mapping language code to the page
1233 public function setLanguageLinks( array $newLinkArray ) {
1234 $this->mLanguageLinks
= $newLinkArray;
1238 * Get the list of language links
1240 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1242 public function getLanguageLinks() {
1243 return $this->mLanguageLinks
;
1247 * Add an array of categories, with names in the keys
1249 * @param array $categories Mapping category name => sort key
1251 public function addCategoryLinks( array $categories ) {
1254 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1258 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1260 # Set all the values to 'normal'.
1261 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1263 # Mark hidden categories
1264 foreach ( $res as $row ) {
1265 if ( isset( $row->pp_value
) ) {
1266 $categories[$row->page_title
] = 'hidden';
1270 # Add the remaining categories to the skin
1272 'OutputPageMakeCategoryLinks',
1273 [ &$this, $categories, &$this->mCategoryLinks
] )
1275 foreach ( $categories as $category => $type ) {
1276 // array keys will cast numeric category names to ints, so cast back to string
1277 $category = (string)$category;
1278 $origcategory = $category;
1279 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1283 $wgContLang->findVariantLink( $category, $title, true );
1284 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1287 $text = $wgContLang->convertHtml( $title->getText() );
1288 $this->mCategories
[$type][] = $title->getText();
1289 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1295 * @param array $categories
1296 * @return bool|ResultWrapper
1298 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1299 # Add the links to a LinkBatch
1300 $arr = [ NS_CATEGORY
=> $categories ];
1301 $lb = new LinkBatch
;
1302 $lb->setArray( $arr );
1304 # Fetch existence plus the hiddencat property
1305 $dbr = wfGetDB( DB_REPLICA
);
1306 $fields = array_merge(
1307 LinkCache
::getSelectFields(),
1308 [ 'page_namespace', 'page_title', 'pp_value' ]
1311 $res = $dbr->select( [ 'page', 'page_props' ],
1313 $lb->constructSet( 'page', $dbr ),
1316 [ 'page_props' => [ 'LEFT JOIN', [
1317 'pp_propname' => 'hiddencat',
1322 # Add the results to the link cache
1323 $lb->addResultToCache( LinkCache
::singleton(), $res );
1329 * Reset the category links (but not the category list) and add $categories
1331 * @param array $categories Mapping category name => sort key
1333 public function setCategoryLinks( array $categories ) {
1334 $this->mCategoryLinks
= [];
1335 $this->addCategoryLinks( $categories );
1339 * Get the list of category links, in a 2-D array with the following format:
1340 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1341 * hidden categories) and $link a HTML fragment with a link to the category
1346 public function getCategoryLinks() {
1347 return $this->mCategoryLinks
;
1351 * Get the list of category names this page belongs to.
1353 * @param string $type The type of categories which should be returned. Possible values:
1354 * * all: all categories of all types
1355 * * hidden: only the hidden categories
1356 * * normal: all categories, except hidden categories
1357 * @return array Array of strings
1359 public function getCategories( $type = 'all' ) {
1360 if ( $type === 'all' ) {
1361 $allCategories = [];
1362 foreach ( $this->mCategories
as $categories ) {
1363 $allCategories = array_merge( $allCategories, $categories );
1365 return $allCategories;
1367 if ( !isset( $this->mCategories
[$type] ) ) {
1368 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1370 return $this->mCategories
[$type];
1374 * Add an array of indicators, with their identifiers as array
1375 * keys and HTML contents as values.
1377 * In case of duplicate keys, existing values are overwritten.
1379 * @param array $indicators
1382 public function setIndicators( array $indicators ) {
1383 $this->mIndicators
= $indicators +
$this->mIndicators
;
1384 // Keep ordered by key
1385 ksort( $this->mIndicators
);
1389 * Get the indicators associated with this page.
1391 * The array will be internally ordered by item keys.
1393 * @return array Keys: identifiers, values: HTML contents
1396 public function getIndicators() {
1397 return $this->mIndicators
;
1401 * Adds help link with an icon via page indicators.
1402 * Link target can be overridden by a local message containing a wikilink:
1403 * the message key is: lowercase action or special page name + '-helppage'.
1404 * @param string $to Target MediaWiki.org page title or encoded URL.
1405 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1408 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1409 $this->addModuleStyles( 'mediawiki.helplink' );
1410 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1412 if ( $overrideBaseUrl ) {
1415 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1416 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1419 $link = Html
::rawElement(
1423 'target' => '_blank',
1424 'class' => 'mw-helplink',
1429 $this->setIndicators( [ 'mw-helplink' => $link ] );
1433 * Do not allow scripts which can be modified by wiki users to load on this page;
1434 * only allow scripts bundled with, or generated by, the software.
1435 * Site-wide styles are controlled by a config setting, since they can be
1436 * used to create a custom skin/theme, but not user-specific ones.
1438 * @todo this should be given a more accurate name
1440 public function disallowUserJs() {
1441 $this->reduceAllowedModules(
1442 ResourceLoaderModule
::TYPE_SCRIPTS
,
1443 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1446 // Site-wide styles are controlled by a config setting, see bug 71621
1447 // for background on why. User styles are never allowed.
1448 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1449 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1451 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1453 $this->reduceAllowedModules(
1454 ResourceLoaderModule
::TYPE_STYLES
,
1460 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1461 * @see ResourceLoaderModule::$origin
1462 * @param string $type ResourceLoaderModule TYPE_ constant
1463 * @return int ResourceLoaderModule ORIGIN_ class constant
1465 public function getAllowedModules( $type ) {
1466 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1467 return min( array_values( $this->mAllowedModules
) );
1469 return isset( $this->mAllowedModules
[$type] )
1470 ?
$this->mAllowedModules
[$type]
1471 : ResourceLoaderModule
::ORIGIN_ALL
;
1476 * Limit the highest level of CSS/JS untrustworthiness allowed.
1478 * If passed the same or a higher level than the current level of untrustworthiness set, the
1479 * level will remain unchanged.
1481 * @param string $type
1482 * @param int $level ResourceLoaderModule class constant
1484 public function reduceAllowedModules( $type, $level ) {
1485 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1489 * Prepend $text to the body HTML
1491 * @param string $text HTML
1493 public function prependHTML( $text ) {
1494 $this->mBodytext
= $text . $this->mBodytext
;
1498 * Append $text to the body HTML
1500 * @param string $text HTML
1502 public function addHTML( $text ) {
1503 $this->mBodytext
.= $text;
1507 * Shortcut for adding an Html::element via addHTML.
1511 * @param string $element
1512 * @param array $attribs
1513 * @param string $contents
1515 public function addElement( $element, array $attribs = [], $contents = '' ) {
1516 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1520 * Clear the body HTML
1522 public function clearHTML() {
1523 $this->mBodytext
= '';
1529 * @return string HTML
1531 public function getHTML() {
1532 return $this->mBodytext
;
1536 * Get/set the ParserOptions object to use for wikitext parsing
1538 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1539 * current ParserOption object
1540 * @return ParserOptions
1542 public function parserOptions( $options = null ) {
1543 if ( $options !== null && !empty( $options->isBogus
) ) {
1544 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1545 // been changed somehow, and keep it if so.
1546 $anonPO = ParserOptions
::newFromAnon();
1547 $anonPO->setEditSection( false );
1548 if ( !$options->matches( $anonPO ) ) {
1549 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1550 $options->isBogus
= false;
1554 if ( !$this->mParserOptions
) {
1555 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1556 // $wgUser isn't unstubbable yet, so don't try to get a
1557 // ParserOptions for it. And don't cache this ParserOptions
1559 $po = ParserOptions
::newFromAnon();
1560 $po->setEditSection( false );
1561 $po->isBogus
= true;
1562 if ( $options !== null ) {
1563 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1568 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1569 $this->mParserOptions
->setEditSection( false );
1572 if ( $options !== null && !empty( $options->isBogus
) ) {
1573 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1575 return wfSetVar( $this->mParserOptions
, null, true );
1577 return wfSetVar( $this->mParserOptions
, $options );
1582 * Set the revision ID which will be seen by the wiki text parser
1583 * for things such as embedded {{REVISIONID}} variable use.
1585 * @param int|null $revid An positive integer, or null
1586 * @return mixed Previous value
1588 public function setRevisionId( $revid ) {
1589 $val = is_null( $revid ) ?
null : intval( $revid );
1590 return wfSetVar( $this->mRevisionId
, $val );
1594 * Get the displayed revision ID
1598 public function getRevisionId() {
1599 return $this->mRevisionId
;
1603 * Set the timestamp of the revision which will be displayed. This is used
1604 * to avoid a extra DB call in Skin::lastModified().
1606 * @param string|null $timestamp
1607 * @return mixed Previous value
1609 public function setRevisionTimestamp( $timestamp ) {
1610 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1614 * Get the timestamp of displayed revision.
1615 * This will be null if not filled by setRevisionTimestamp().
1617 * @return string|null
1619 public function getRevisionTimestamp() {
1620 return $this->mRevisionTimestamp
;
1624 * Set the displayed file version
1626 * @param File|bool $file
1627 * @return mixed Previous value
1629 public function setFileVersion( $file ) {
1631 if ( $file instanceof File
&& $file->exists() ) {
1632 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1634 return wfSetVar( $this->mFileVersion
, $val, true );
1638 * Get the displayed file version
1640 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1642 public function getFileVersion() {
1643 return $this->mFileVersion
;
1647 * Get the templates used on this page
1649 * @return array (namespace => dbKey => revId)
1652 public function getTemplateIds() {
1653 return $this->mTemplateIds
;
1657 * Get the files used on this page
1659 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1662 public function getFileSearchOptions() {
1663 return $this->mImageTimeKeys
;
1667 * Convert wikitext to HTML and add it to the buffer
1668 * Default assumes that the current page title will be used.
1670 * @param string $text
1671 * @param bool $linestart Is this the start of a line?
1672 * @param bool $interface Is this text in the user interface language?
1673 * @throws MWException
1675 public function addWikiText( $text, $linestart = true, $interface = true ) {
1676 $title = $this->getTitle(); // Work around E_STRICT
1678 throw new MWException( 'Title is null' );
1680 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1684 * Add wikitext with a custom Title object
1686 * @param string $text Wikitext
1687 * @param Title $title
1688 * @param bool $linestart Is this the start of a line?
1690 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1691 $this->addWikiTextTitle( $text, $title, $linestart );
1695 * Add wikitext with a custom Title object and tidy enabled.
1697 * @param string $text Wikitext
1698 * @param Title $title
1699 * @param bool $linestart Is this the start of a line?
1701 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1702 $this->addWikiTextTitle( $text, $title, $linestart, true );
1706 * Add wikitext with tidy enabled
1708 * @param string $text Wikitext
1709 * @param bool $linestart Is this the start of a line?
1711 public function addWikiTextTidy( $text, $linestart = true ) {
1712 $title = $this->getTitle();
1713 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1717 * Add wikitext with a custom Title object
1719 * @param string $text Wikitext
1720 * @param Title $title
1721 * @param bool $linestart Is this the start of a line?
1722 * @param bool $tidy Whether to use tidy
1723 * @param bool $interface Whether it is an interface message
1724 * (for example disables conversion)
1726 public function addWikiTextTitle( $text, Title
$title, $linestart,
1727 $tidy = false, $interface = false
1731 $popts = $this->parserOptions();
1732 $oldTidy = $popts->setTidy( $tidy );
1733 $popts->setInterfaceMessage( (bool)$interface );
1735 $parserOutput = $wgParser->getFreshParser()->parse(
1736 $text, $title, $popts,
1737 $linestart, true, $this->mRevisionId
1740 $popts->setTidy( $oldTidy );
1742 $this->addParserOutput( $parserOutput );
1747 * Add a ParserOutput object, but without Html.
1749 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1750 * @param ParserOutput $parserOutput
1752 public function addParserOutputNoText( $parserOutput ) {
1753 wfDeprecated( __METHOD__
, '1.24' );
1754 $this->addParserOutputMetadata( $parserOutput );
1758 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1759 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1763 * @param ParserOutput $parserOutput
1765 public function addParserOutputMetadata( $parserOutput ) {
1766 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1767 $this->addCategoryLinks( $parserOutput->getCategories() );
1768 $this->setIndicators( $parserOutput->getIndicators() );
1769 $this->mNewSectionLink
= $parserOutput->getNewSection();
1770 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1772 if ( !$parserOutput->isCacheable() ) {
1773 $this->enableClientCache( false );
1775 $this->mNoGallery
= $parserOutput->getNoGallery();
1776 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1777 $this->addModules( $parserOutput->getModules() );
1778 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1779 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1780 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1781 $this->mPreventClickjacking
= $this->mPreventClickjacking
1782 ||
$parserOutput->preventClickjacking();
1784 // Template versioning...
1785 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1786 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1787 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1789 $this->mTemplateIds
[$ns] = $dbks;
1792 // File versioning...
1793 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1794 $this->mImageTimeKeys
[$dbk] = $data;
1797 // Hooks registered in the object
1798 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1799 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1800 list( $hookName, $data ) = $hookInfo;
1801 if ( isset( $parserOutputHooks[$hookName] ) ) {
1802 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1806 // Enable OOUI if requested via ParserOutput
1807 if ( $parserOutput->getEnableOOUI() ) {
1808 $this->enableOOUI();
1811 // Include profiling data
1812 if ( !$this->limitReportData
) {
1813 $this->setLimitReportData( $parserOutput->getLimitReportData() );
1816 // Link flags are ignored for now, but may in the future be
1817 // used to mark individual language links.
1819 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1820 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1824 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1825 * ParserOutput object, without any other metadata.
1828 * @param ParserOutput $parserOutput
1830 public function addParserOutputContent( $parserOutput ) {
1831 $this->addParserOutputText( $parserOutput );
1833 $this->addModules( $parserOutput->getModules() );
1834 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1835 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1837 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1841 * Add the HTML associated with a ParserOutput object, without any metadata.
1844 * @param ParserOutput $parserOutput
1846 public function addParserOutputText( $parserOutput ) {
1847 $text = $parserOutput->getText();
1848 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1849 $this->addHTML( $text );
1853 * Add everything from a ParserOutput object.
1855 * @param ParserOutput $parserOutput
1857 function addParserOutput( $parserOutput ) {
1858 $this->addParserOutputMetadata( $parserOutput );
1859 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1861 // Touch section edit links only if not previously disabled
1862 if ( $parserOutput->getEditSectionTokens() ) {
1863 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1866 $this->addParserOutputText( $parserOutput );
1870 * Add the output of a QuickTemplate to the output buffer
1872 * @param QuickTemplate $template
1874 public function addTemplate( &$template ) {
1875 $this->addHTML( $template->getHTML() );
1879 * Parse wikitext and return the HTML.
1881 * @param string $text
1882 * @param bool $linestart Is this the start of a line?
1883 * @param bool $interface Use interface language ($wgLang instead of
1884 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1885 * This also disables LanguageConverter.
1886 * @param Language $language Target language object, will override $interface
1887 * @throws MWException
1888 * @return string HTML
1890 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1893 if ( is_null( $this->getTitle() ) ) {
1894 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1897 $popts = $this->parserOptions();
1899 $popts->setInterfaceMessage( true );
1901 if ( $language !== null ) {
1902 $oldLang = $popts->setTargetLanguage( $language );
1905 $parserOutput = $wgParser->getFreshParser()->parse(
1906 $text, $this->getTitle(), $popts,
1907 $linestart, true, $this->mRevisionId
1911 $popts->setInterfaceMessage( false );
1913 if ( $language !== null ) {
1914 $popts->setTargetLanguage( $oldLang );
1917 return $parserOutput->getText();
1921 * Parse wikitext, strip paragraphs, and return the HTML.
1923 * @param string $text
1924 * @param bool $linestart Is this the start of a line?
1925 * @param bool $interface Use interface language ($wgLang instead of
1926 * $wgContLang) while parsing language sensitive magic
1927 * words like GRAMMAR and PLURAL
1928 * @return string HTML
1930 public function parseInline( $text, $linestart = true, $interface = false ) {
1931 $parsed = $this->parse( $text, $linestart, $interface );
1932 return Parser
::stripOuterParagraph( $parsed );
1937 * @deprecated since 1.27 Use setCdnMaxage() instead
1939 public function setSquidMaxage( $maxage ) {
1940 $this->setCdnMaxage( $maxage );
1944 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1946 * @param int $maxage Maximum cache time on the CDN, in seconds.
1948 public function setCdnMaxage( $maxage ) {
1949 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1953 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1955 * @param int $maxage Maximum cache time on the CDN, in seconds
1958 public function lowerCdnMaxage( $maxage ) {
1959 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1960 $this->setCdnMaxage( $this->mCdnMaxage
);
1964 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1966 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1967 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1968 * TTL is 90% of the age of the object, subject to the min and max.
1970 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1971 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1972 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1973 * @return integer TTL in seconds
1976 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1977 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
1978 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
1980 if ( $mtime === null ||
$mtime === false ) {
1981 return $minTTL; // entity does not exist
1984 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
1985 $adaptiveTTL = max( .9 * $age, $minTTL );
1986 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1988 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1990 return $adaptiveTTL;
1994 * Use enableClientCache(false) to force it to send nocache headers
1996 * @param bool $state
2000 public function enableClientCache( $state ) {
2001 return wfSetVar( $this->mEnableClientCache
, $state );
2005 * Get the list of cookies that will influence on the cache
2009 function getCacheVaryCookies() {
2011 if ( $cookies === null ) {
2012 $config = $this->getConfig();
2013 $cookies = array_merge(
2014 SessionManager
::singleton()->getVaryCookies(),
2018 $config->get( 'CacheVaryCookies' )
2020 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2026 * Check if the request has a cache-varying cookie header
2027 * If it does, it's very important that we don't allow public caching
2031 function haveCacheVaryCookies() {
2032 $request = $this->getRequest();
2033 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2034 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2035 wfDebug( __METHOD__
. ": found $cookieName\n" );
2039 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2044 * Add an HTTP header that will influence on the cache
2046 * @param string $header Header name
2047 * @param string[]|null $option Options for the Key header. See
2048 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2049 * for the list of valid options.
2051 public function addVaryHeader( $header, array $option = null ) {
2052 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2053 $this->mVaryHeader
[$header] = [];
2055 if ( !is_array( $option ) ) {
2058 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2062 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2063 * such as Accept-Encoding or Cookie
2067 public function getVaryHeader() {
2068 // If we vary on cookies, let's make sure it's always included here too.
2069 if ( $this->getCacheVaryCookies() ) {
2070 $this->addVaryHeader( 'Cookie' );
2073 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2074 $this->addVaryHeader( $header, $options );
2076 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2080 * Get a complete Key header
2084 public function getKeyHeader() {
2085 $cvCookies = $this->getCacheVaryCookies();
2087 $cookiesOption = [];
2088 foreach ( $cvCookies as $cookieName ) {
2089 $cookiesOption[] = 'param=' . $cookieName;
2091 $this->addVaryHeader( 'Cookie', $cookiesOption );
2093 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2094 $this->addVaryHeader( $header, $options );
2098 foreach ( $this->mVaryHeader
as $header => $option ) {
2099 $newheader = $header;
2100 if ( is_array( $option ) && count( $option ) > 0 ) {
2101 $newheader .= ';' . implode( ';', $option );
2103 $headers[] = $newheader;
2105 $key = 'Key: ' . implode( ',', $headers );
2111 * T23672: Add Accept-Language to Vary and Key headers
2112 * if there's no 'variant' parameter existed in GET.
2115 * /w/index.php?title=Main_page should always be served; but
2116 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2118 function addAcceptLanguage() {
2119 $title = $this->getTitle();
2120 if ( !$title instanceof Title
) {
2124 $lang = $title->getPageLanguage();
2125 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2126 $variants = $lang->getVariants();
2128 foreach ( $variants as $variant ) {
2129 if ( $variant === $lang->getCode() ) {
2132 $aloption[] = 'substr=' . $variant;
2134 // IE and some other browsers use BCP 47 standards in
2135 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2136 // We should handle these too.
2137 $variantBCP47 = wfBCP47( $variant );
2138 if ( $variantBCP47 !== $variant ) {
2139 $aloption[] = 'substr=' . $variantBCP47;
2143 $this->addVaryHeader( 'Accept-Language', $aloption );
2148 * Set a flag which will cause an X-Frame-Options header appropriate for
2149 * edit pages to be sent. The header value is controlled by
2150 * $wgEditPageFrameOptions.
2152 * This is the default for special pages. If you display a CSRF-protected
2153 * form on an ordinary view page, then you need to call this function.
2155 * @param bool $enable
2157 public function preventClickjacking( $enable = true ) {
2158 $this->mPreventClickjacking
= $enable;
2162 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2163 * This can be called from pages which do not contain any CSRF-protected
2166 public function allowClickjacking() {
2167 $this->mPreventClickjacking
= false;
2171 * Get the prevent-clickjacking flag
2176 public function getPreventClickjacking() {
2177 return $this->mPreventClickjacking
;
2181 * Get the X-Frame-Options header value (without the name part), or false
2182 * if there isn't one. This is used by Skin to determine whether to enable
2183 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2187 public function getFrameOptions() {
2188 $config = $this->getConfig();
2189 if ( $config->get( 'BreakFrames' ) ) {
2191 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2192 return $config->get( 'EditPageFrameOptions' );
2198 * Send cache control HTTP headers
2200 public function sendCacheControl() {
2201 $response = $this->getRequest()->response();
2202 $config = $this->getConfig();
2204 $this->addVaryHeader( 'Cookie' );
2205 $this->addAcceptLanguage();
2207 # don't serve compressed data to clients who can't handle it
2208 # maintain different caches for logged-in users and non-logged in ones
2209 $response->header( $this->getVaryHeader() );
2211 if ( $config->get( 'UseKeyHeader' ) ) {
2212 $response->header( $this->getKeyHeader() );
2215 if ( $this->mEnableClientCache
) {
2217 $config->get( 'UseSquid' ) &&
2218 !$response->hasCookies() &&
2219 !SessionManager
::getGlobalSession()->isPersistent() &&
2220 !$this->isPrintable() &&
2221 $this->mCdnMaxage
!= 0 &&
2222 !$this->haveCacheVaryCookies()
2224 if ( $config->get( 'UseESI' ) ) {
2225 # We'll purge the proxy cache explicitly, but require end user agents
2226 # to revalidate against the proxy on each visit.
2227 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2228 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2229 # start with a shorter timeout for initial testing
2230 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2231 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2232 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2233 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2235 # We'll purge the proxy cache for anons explicitly, but require end user agents
2236 # to revalidate against the proxy on each visit.
2237 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2238 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2239 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2240 # start with a shorter timeout for initial testing
2241 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2242 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2243 . ', must-revalidate, max-age=0' );
2246 # We do want clients to cache if they can, but they *must* check for updates
2247 # on revisiting the page.
2248 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2249 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2250 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2252 if ( $this->mLastModified
) {
2253 $response->header( "Last-Modified: {$this->mLastModified}" );
2256 wfDebug( __METHOD__
. ": no caching **", 'private' );
2258 # In general, the absence of a last modified header should be enough to prevent
2259 # the client from using its cache. We send a few other things just to make sure.
2260 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2261 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2262 $response->header( 'Pragma: no-cache' );
2267 * Finally, all the text has been munged and accumulated into
2268 * the object, let's actually output it:
2270 * @param bool $return Set to true to get the result as a string rather than sending it
2271 * @return string|null
2273 * @throws FatalError
2274 * @throws MWException
2276 public function output( $return = false ) {
2279 if ( $this->mDoNothing
) {
2280 return $return ?
'' : null;
2283 $response = $this->getRequest()->response();
2284 $config = $this->getConfig();
2286 if ( $this->mRedirect
!= '' ) {
2287 # Standards require redirect URLs to be absolute
2288 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2290 $redirect = $this->mRedirect
;
2291 $code = $this->mRedirectCode
;
2293 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2294 if ( $code == '301' ||
$code == '303' ) {
2295 if ( !$config->get( 'DebugRedirects' ) ) {
2296 $response->statusHeader( $code );
2298 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2300 if ( $config->get( 'VaryOnXFP' ) ) {
2301 $this->addVaryHeader( 'X-Forwarded-Proto' );
2303 $this->sendCacheControl();
2305 $response->header( "Content-Type: text/html; charset=utf-8" );
2306 if ( $config->get( 'DebugRedirects' ) ) {
2307 $url = htmlspecialchars( $redirect );
2308 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2309 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2310 print "</body>\n</html>\n";
2312 $response->header( 'Location: ' . $redirect );
2316 return $return ?
'' : null;
2317 } elseif ( $this->mStatusCode
) {
2318 $response->statusHeader( $this->mStatusCode
);
2321 # Buffer output; final headers may depend on later processing
2324 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2325 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2327 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2328 // jQuery etc. can work correctly.
2329 $response->header( 'X-UA-Compatible: IE=Edge' );
2331 // Prevent framing, if requested
2332 $frameOptions = $this->getFrameOptions();
2333 if ( $frameOptions ) {
2334 $response->header( "X-Frame-Options: $frameOptions" );
2337 if ( $this->mArticleBodyOnly
) {
2338 echo $this->mBodytext
;
2340 $sk = $this->getSkin();
2341 // add skin specific modules
2342 $modules = $sk->getDefaultModules();
2344 // Enforce various default modules for all pages and all skins
2346 // Keep this list as small as possible
2348 'mediawiki.page.startup',
2352 // Support for high-density display images if enabled
2353 if ( $config->get( 'ResponsiveImages' ) ) {
2354 $coreModules[] = 'mediawiki.hidpi';
2357 $this->addModules( $coreModules );
2358 foreach ( $modules as $group ) {
2359 $this->addModules( $group );
2361 MWDebug
::addModules( $this );
2363 // Hook that allows last minute changes to the output page, e.g.
2364 // adding of CSS or Javascript by extensions.
2365 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2369 } catch ( Exception
$e ) {
2370 ob_end_clean(); // bug T129657
2376 // This hook allows last minute changes to final overall output by modifying output buffer
2377 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2378 } catch ( Exception
$e ) {
2379 ob_end_clean(); // bug T129657
2383 $this->sendCacheControl();
2386 return ob_get_clean();
2394 * Prepare this object to display an error page; disable caching and
2395 * indexing, clear the current text and redirect, set the page's title
2396 * and optionally an custom HTML title (content of the "<title>" tag).
2398 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2399 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2400 * optional, if not passed the "<title>" attribute will be
2401 * based on $pageTitle
2403 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2404 $this->setPageTitle( $pageTitle );
2405 if ( $htmlTitle !== false ) {
2406 $this->setHTMLTitle( $htmlTitle );
2408 $this->setRobotPolicy( 'noindex,nofollow' );
2409 $this->setArticleRelated( false );
2410 $this->enableClientCache( false );
2411 $this->mRedirect
= '';
2412 $this->clearSubtitle();
2417 * Output a standard error page
2419 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2420 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2421 * showErrorPage( 'titlemsg', $messageObject );
2422 * showErrorPage( $titleMessageObject, $messageObject );
2424 * @param string|Message $title Message key (string) for page title, or a Message object
2425 * @param string|Message $msg Message key (string) for page text, or a Message object
2426 * @param array $params Message parameters; ignored if $msg is a Message object
2428 public function showErrorPage( $title, $msg, $params = [] ) {
2429 if ( !$title instanceof Message
) {
2430 $title = $this->msg( $title );
2433 $this->prepareErrorPage( $title );
2435 if ( $msg instanceof Message
) {
2436 if ( $params !== [] ) {
2437 trigger_error( 'Argument ignored: $params. The message parameters argument '
2438 . 'is discarded when the $msg argument is a Message object instead of '
2439 . 'a string.', E_USER_NOTICE
);
2441 $this->addHTML( $msg->parseAsBlock() );
2443 $this->addWikiMsgArray( $msg, $params );
2446 $this->returnToMain();
2450 * Output a standard permission error page
2452 * @param array $errors Error message keys or [key, param...] arrays
2453 * @param string $action Action that was denied or null if unknown
2455 public function showPermissionsErrorPage( array $errors, $action = null ) {
2456 foreach ( $errors as $key => $error ) {
2457 $errors[$key] = (array)$error;
2460 // For some action (read, edit, create and upload), display a "login to do this action"
2461 // error if all of the following conditions are met:
2462 // 1. the user is not logged in
2463 // 2. the only error is insufficient permissions (i.e. no block or something else)
2464 // 3. the error can be avoided simply by logging in
2465 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2466 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2467 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2468 && ( User
::groupHasPermission( 'user', $action )
2469 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2471 $displayReturnto = null;
2473 # Due to bug 32276, if a user does not have read permissions,
2474 # $this->getTitle() will just give Special:Badtitle, which is
2475 # not especially useful as a returnto parameter. Use the title
2476 # from the request instead, if there was one.
2477 $request = $this->getRequest();
2478 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2479 if ( $action == 'edit' ) {
2480 $msg = 'whitelistedittext';
2481 $displayReturnto = $returnto;
2482 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2483 $msg = 'nocreatetext';
2484 } elseif ( $action == 'upload' ) {
2485 $msg = 'uploadnologintext';
2487 $msg = 'loginreqpagetext';
2488 $displayReturnto = Title
::newMainPage();
2494 $query['returnto'] = $returnto->getPrefixedText();
2496 if ( !$request->wasPosted() ) {
2497 $returntoquery = $request->getValues();
2498 unset( $returntoquery['title'] );
2499 unset( $returntoquery['returnto'] );
2500 unset( $returntoquery['returntoquery'] );
2501 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2504 $loginLink = Linker
::linkKnown(
2505 SpecialPage
::getTitleFor( 'Userlogin' ),
2506 $this->msg( 'loginreqlink' )->escaped(),
2511 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2512 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2514 # Don't return to a page the user can't read otherwise
2515 # we'll end up in a pointless loop
2516 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2517 $this->returnToMain( null, $displayReturnto );
2520 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2521 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2526 * Display an error page indicating that a given version of MediaWiki is
2527 * required to use it
2529 * @param mixed $version The version of MediaWiki needed to use the page
2531 public function versionRequired( $version ) {
2532 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2534 $this->addWikiMsg( 'versionrequiredtext', $version );
2535 $this->returnToMain();
2539 * Format a list of error messages
2541 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2542 * @param string $action Action that was denied or null if unknown
2543 * @return string The wikitext error-messages, formatted into a list.
2545 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2546 if ( $action == null ) {
2547 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2549 $action_desc = $this->msg( "action-$action" )->plain();
2551 'permissionserrorstext-withaction',
2554 )->plain() . "\n\n";
2557 if ( count( $errors ) > 1 ) {
2558 $text .= '<ul class="permissions-errors">' . "\n";
2560 foreach ( $errors as $error ) {
2562 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2567 $text .= "<div class=\"permissions-errors\">\n" .
2568 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2576 * Display a page stating that the Wiki is in read-only mode.
2577 * Should only be called after wfReadOnly() has returned true.
2579 * Historically, this function was used to show the source of the page that the user
2580 * was trying to edit and _also_ permissions error messages. The relevant code was
2581 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2583 * @deprecated since 1.25; throw the exception directly
2584 * @throws ReadOnlyError
2586 public function readOnlyPage() {
2587 if ( func_num_args() > 0 ) {
2588 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2591 throw new ReadOnlyError
;
2595 * Turn off regular page output and return an error response
2596 * for when rate limiting has triggered.
2598 * @deprecated since 1.25; throw the exception directly
2600 public function rateLimited() {
2601 wfDeprecated( __METHOD__
, '1.25' );
2602 throw new ThrottledError
;
2606 * Show a warning about replica DB lag
2608 * If the lag is higher than $wgSlaveLagCritical seconds,
2609 * then the warning is a bit more obvious. If the lag is
2610 * lower than $wgSlaveLagWarning, then no warning is shown.
2612 * @param int $lag Slave lag
2614 public function showLagWarning( $lag ) {
2615 $config = $this->getConfig();
2616 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2617 $lag = floor( $lag ); // floor to avoid nano seconds to display
2618 $message = $lag < $config->get( 'SlaveLagCritical' )
2621 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2622 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2626 public function showFatalError( $message ) {
2627 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2629 $this->addHTML( $message );
2632 public function showUnexpectedValueError( $name, $val ) {
2633 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2636 public function showFileCopyError( $old, $new ) {
2637 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2640 public function showFileRenameError( $old, $new ) {
2641 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2644 public function showFileDeleteError( $name ) {
2645 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2648 public function showFileNotFoundError( $name ) {
2649 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2653 * Add a "return to" link pointing to a specified title
2655 * @param Title $title Title to link
2656 * @param array $query Query string parameters
2657 * @param string $text Text of the link (input is not escaped)
2658 * @param array $options Options array to pass to Linker
2660 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2661 $link = $this->msg( 'returnto' )->rawParams(
2662 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2663 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2667 * Add a "return to" link pointing to a specified title,
2668 * or the title indicated in the request, or else the main page
2670 * @param mixed $unused
2671 * @param Title|string $returnto Title or String to return to
2672 * @param string $returntoquery Query string for the return to link
2674 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2675 if ( $returnto == null ) {
2676 $returnto = $this->getRequest()->getText( 'returnto' );
2679 if ( $returntoquery == null ) {
2680 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2683 if ( $returnto === '' ) {
2684 $returnto = Title
::newMainPage();
2687 if ( is_object( $returnto ) ) {
2688 $titleObj = $returnto;
2690 $titleObj = Title
::newFromText( $returnto );
2692 if ( !is_object( $titleObj ) ) {
2693 $titleObj = Title
::newMainPage();
2696 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2699 private function getRlClientContext() {
2700 if ( !$this->rlClientContext
) {
2701 $query = ResourceLoader
::makeLoaderQuery(
2702 [], // modules; not relevant
2703 $this->getLanguage()->getCode(),
2704 $this->getSkin()->getSkinName(),
2705 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2706 null, // version; not relevant
2707 ResourceLoader
::inDebugMode(),
2708 null, // only; not relevant
2709 $this->isPrintable(),
2710 $this->getRequest()->getBool( 'handheld' )
2712 $this->rlClientContext
= new ResourceLoaderContext(
2713 $this->getResourceLoader(),
2714 new FauxRequest( $query )
2717 return $this->rlClientContext
;
2721 * Call this to freeze the module queue and JS config and create a formatter.
2723 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2724 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2725 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2726 * the module filters retroactively. Skins and extension hooks may also add modules until very
2727 * late in the request lifecycle.
2729 * @return ResourceLoaderClientHtml
2731 public function getRlClient() {
2732 if ( !$this->rlClient
) {
2733 $context = $this->getRlClientContext();
2734 $rl = $this->getResourceLoader();
2735 $this->addModules( [
2739 $this->addModuleStyles( [
2745 $this->getSkin()->setupSkinUserCss( $this );
2747 // Prepare exempt modules for buildExemptModules()
2748 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2750 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2752 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2753 // Separate user-specific batch for improved cache-hit ratio.
2754 $userBatch = [ 'user.styles', 'user' ];
2755 $siteBatch = array_diff( $moduleStyles, $userBatch );
2756 $dbr = wfGetDB( DB_REPLICA
);
2757 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2758 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2760 // Filter out modules handled by buildExemptModules()
2761 $moduleStyles = array_filter( $moduleStyles,
2762 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2763 $module = $rl->getModule( $name );
2765 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2766 $exemptStates[$name] = 'ready';
2767 // Special case in buildExemptModules()
2770 $group = $module->getGroup();
2771 if ( isset( $exemptGroups[$group] ) ) {
2772 $exemptStates[$name] = 'ready';
2773 if ( !$module->isKnownEmpty( $context ) ) {
2774 // E.g. Don't output empty <styles>
2775 $exemptGroups[$group][] = $name;
2783 $this->rlExemptStyleModules
= $exemptGroups;
2785 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2786 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2787 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2788 if ( !$isUserModuleFiltered ) {
2789 // Manually handled by getBottomScripts()
2790 $userModule = $rl->getModule( 'user' );
2791 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2794 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2797 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2798 $rlClient->setConfig( $this->getJSVars() );
2799 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2800 $rlClient->setModuleStyles( $moduleStyles );
2801 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2802 $rlClient->setExemptStates( $exemptStates );
2803 $this->rlClient
= $rlClient;
2805 return $this->rlClient
;
2809 * @param Skin $sk The given Skin
2810 * @param bool $includeStyle Unused
2811 * @return string The doctype, opening "<html>", and head element.
2813 public function headElement( Skin
$sk, $includeStyle = true ) {
2816 $userdir = $this->getLanguage()->getDir();
2817 $sitedir = $wgContLang->getDir();
2820 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2821 $this->getRlClient()->getDocumentAttributes(),
2822 $sk->getHtmlElementAttributes()
2824 $pieces[] = Html
::openElement( 'head' );
2826 if ( $this->getHTMLTitle() == '' ) {
2827 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2830 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2831 // Add <meta charset="UTF-8">
2832 // This should be before <title> since it defines the charset used by
2833 // text including the text inside <title>.
2834 // The spec recommends defining XHTML5's charset using the XML declaration
2836 // Our XML declaration is output by Html::htmlHeader.
2837 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2838 // http://www.whatwg.org/html/semantics.html#charset
2839 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2842 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2843 $pieces[] = $this->getRlClient()->getHeadHtml();
2844 $pieces[] = $this->buildExemptModules();
2845 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2846 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2847 $pieces[] = Html
::closeElement( 'head' );
2850 $bodyClasses[] = 'mediawiki';
2852 # Classes for LTR/RTL directionality support
2853 $bodyClasses[] = $userdir;
2854 $bodyClasses[] = "sitedir-$sitedir";
2856 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2857 # A <body> class is probably not the best way to do this . . .
2858 $bodyClasses[] = 'capitalize-all-nouns';
2861 // Parser feature migration class
2862 // The idea is that this will eventually be removed, after the wikitext
2863 // which requires it is cleaned up.
2864 $bodyClasses[] = 'mw-hide-empty-elt';
2866 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2867 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2869 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2872 // While the implode() is not strictly needed, it's used for backwards compatibility
2873 // (this used to be built as a string and hooks likely still expect that).
2874 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2876 // Allow skins and extensions to add body attributes they need
2877 $sk->addToBodyAttributes( $this, $bodyAttrs );
2878 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2880 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2882 return self
::combineWrappedStrings( $pieces );
2886 * Get a ResourceLoader object associated with this OutputPage
2888 * @return ResourceLoader
2890 public function getResourceLoader() {
2891 if ( is_null( $this->mResourceLoader
) ) {
2892 $this->mResourceLoader
= new ResourceLoader(
2894 LoggerFactory
::getInstance( 'resourceloader' )
2897 return $this->mResourceLoader
;
2901 * Explicily load or embed modules on a page.
2903 * @param array|string $modules One or more module names
2904 * @param string $only ResourceLoaderModule TYPE_ class constant
2905 * @param array $extraQuery [optional] Array with extra query parameters for the request
2906 * @return string|WrappedStringList HTML
2908 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2909 // Apply 'target' and 'origin' filters
2910 $modules = $this->filterModules( (array)$modules, null, $only );
2912 return ResourceLoaderClientHtml
::makeLoad(
2913 $this->getRlClientContext(),
2921 * Combine WrappedString chunks and filter out empty ones
2923 * @param array $chunks
2924 * @return string|WrappedStringList HTML
2926 protected static function combineWrappedStrings( array $chunks ) {
2927 // Filter out empty values
2928 $chunks = array_filter( $chunks, 'strlen' );
2929 return WrappedString
::join( "\n", $chunks );
2932 private function isUserJsPreview() {
2933 return $this->getConfig()->get( 'AllowUserJs' )
2934 && $this->getTitle()
2935 && $this->getTitle()->isJsSubpage()
2936 && $this->userCanPreview();
2939 private function isUserCssPreview() {
2940 return $this->getConfig()->get( 'AllowUserCss' )
2941 && $this->getTitle()
2942 && $this->getTitle()->isCssSubpage()
2943 && $this->userCanPreview();
2947 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2948 * legacy scripts ($this->mScripts), and user JS.
2950 * @return string|WrappedStringList HTML
2952 public function getBottomScripts() {
2954 $chunks[] = $this->getRlClient()->getBodyHtml();
2956 // Legacy non-ResourceLoader scripts
2957 $chunks[] = $this->mScripts
;
2959 // Exempt 'user' module
2960 // - May need excludepages for live preview. (T28283)
2961 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2962 // ensures execution is scheduled after the "site" module.
2963 // - Don't load if module state is already resolved as "ready".
2964 if ( $this->rlUserModuleState
=== 'loading' ) {
2965 if ( $this->isUserJsPreview() ) {
2966 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
2967 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2969 $chunks[] = ResourceLoader
::makeInlineScript(
2970 Xml
::encodeJsCall( 'mw.loader.using', [
2974 . Xml
::encodeJsCall( '$.globalEval', [
2975 $this->getRequest()->getText( 'wpTextbox1' )
2981 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2982 // asynchronously and may arrive *after* the inline script here. So the previewed code
2983 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
2984 // Similarly, when previewing ./common.js and the user module does arrive first,
2985 // it will arrive without common.js and the inline script runs after.
2986 // Thus running common after the excluded subpage.
2989 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
2993 if ( $this->limitReportData
) {
2994 $chunks[] = ResourceLoader
::makeInlineScript(
2995 ResourceLoader
::makeConfigSetScript(
2996 [ 'wgPageParseReport' => $this->limitReportData
],
3002 return self
::combineWrappedStrings( $chunks );
3006 * Get the javascript config vars to include on this page
3008 * @return array Array of javascript config vars
3011 public function getJsConfigVars() {
3012 return $this->mJsConfigVars
;
3016 * Add one or more variables to be set in mw.config in JavaScript
3018 * @param string|array $keys Key or array of key/value pairs
3019 * @param mixed $value [optional] Value of the configuration variable
3021 public function addJsConfigVars( $keys, $value = null ) {
3022 if ( is_array( $keys ) ) {
3023 foreach ( $keys as $key => $value ) {
3024 $this->mJsConfigVars
[$key] = $value;
3029 $this->mJsConfigVars
[$keys] = $value;
3033 * Get an array containing the variables to be set in mw.config in JavaScript.
3035 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3036 * - in other words, page-independent/site-wide variables (without state).
3037 * You will only be adding bloat to the html page and causing page caches to
3038 * have to be purged on configuration changes.
3041 public function getJSVars() {
3046 $canonicalSpecialPageName = false; # bug 21115
3048 $title = $this->getTitle();
3049 $ns = $title->getNamespace();
3050 $canonicalNamespace = MWNamespace
::exists( $ns )
3051 ? MWNamespace
::getCanonicalName( $ns )
3052 : $title->getNsText();
3054 $sk = $this->getSkin();
3055 // Get the relevant title so that AJAX features can use the correct page name
3056 // when making API requests from certain special pages (bug 34972).
3057 $relevantTitle = $sk->getRelevantTitle();
3058 $relevantUser = $sk->getRelevantUser();
3060 if ( $ns == NS_SPECIAL
) {
3061 list( $canonicalSpecialPageName, /*...*/ ) =
3062 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3063 } elseif ( $this->canUseWikiPage() ) {
3064 $wikiPage = $this->getWikiPage();
3065 $curRevisionId = $wikiPage->getLatest();
3066 $articleId = $wikiPage->getId();
3069 $lang = $title->getPageViewLanguage();
3071 // Pre-process information
3072 $separatorTransTable = $lang->separatorTransformTable();
3073 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3074 $compactSeparatorTransTable = [
3075 implode( "\t", array_keys( $separatorTransTable ) ),
3076 implode( "\t", $separatorTransTable ),
3078 $digitTransTable = $lang->digitTransformTable();
3079 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3080 $compactDigitTransTable = [
3081 implode( "\t", array_keys( $digitTransTable ) ),
3082 implode( "\t", $digitTransTable ),
3085 $user = $this->getUser();
3088 'wgCanonicalNamespace' => $canonicalNamespace,
3089 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3090 'wgNamespaceNumber' => $title->getNamespace(),
3091 'wgPageName' => $title->getPrefixedDBkey(),
3092 'wgTitle' => $title->getText(),
3093 'wgCurRevisionId' => $curRevisionId,
3094 'wgRevisionId' => (int)$this->getRevisionId(),
3095 'wgArticleId' => $articleId,
3096 'wgIsArticle' => $this->isArticle(),
3097 'wgIsRedirect' => $title->isRedirect(),
3098 'wgAction' => Action
::getActionName( $this->getContext() ),
3099 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3100 'wgUserGroups' => $user->getEffectiveGroups(),
3101 'wgCategories' => $this->getCategories(),
3102 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3103 'wgPageContentLanguage' => $lang->getCode(),
3104 'wgPageContentModel' => $title->getContentModel(),
3105 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3106 'wgDigitTransformTable' => $compactDigitTransTable,
3107 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3108 'wgMonthNames' => $lang->getMonthNamesArray(),
3109 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3110 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3111 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3112 'wgRequestId' => WebRequest
::getRequestId(),
3115 if ( $user->isLoggedIn() ) {
3116 $vars['wgUserId'] = $user->getId();
3117 $vars['wgUserEditCount'] = $user->getEditCount();
3118 $userReg = $user->getRegistration();
3119 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3120 // Get the revision ID of the oldest new message on the user's talk
3121 // page. This can be used for constructing new message alerts on
3123 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3126 if ( $wgContLang->hasVariants() ) {
3127 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3129 // Same test as SkinTemplate
3130 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3131 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3133 foreach ( $title->getRestrictionTypes() as $type ) {
3134 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3137 if ( $title->isMainPage() ) {
3138 $vars['wgIsMainPage'] = true;
3141 if ( $this->mRedirectedFrom
) {
3142 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3145 if ( $relevantUser ) {
3146 $vars['wgRelevantUserName'] = $relevantUser->getName();
3149 // Allow extensions to add their custom variables to the mw.config map.
3150 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3151 // page-dependant but site-wide (without state).
3152 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3153 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3155 // Merge in variables from addJsConfigVars last
3156 return array_merge( $vars, $this->getJsConfigVars() );
3160 * To make it harder for someone to slip a user a fake
3161 * user-JavaScript or user-CSS preview, a random token
3162 * is associated with the login session. If it's not
3163 * passed back with the preview request, we won't render
3168 public function userCanPreview() {
3169 $request = $this->getRequest();
3171 $request->getVal( 'action' ) !== 'submit' ||
3172 !$request->getCheck( 'wpPreview' ) ||
3173 !$request->wasPosted()
3178 $user = $this->getUser();
3180 if ( !$user->isLoggedIn() ) {
3181 // Anons have predictable edit tokens
3184 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3188 $title = $this->getTitle();
3189 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3192 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3193 // Don't execute another user's CSS or JS on preview (T85855)
3197 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3198 if ( count( $errors ) !== 0 ) {
3206 * @return array Array in format "link name or number => 'link html'".
3208 public function getHeadLinksArray() {
3212 $config = $this->getConfig();
3214 $canonicalUrl = $this->mCanonicalUrl
;
3216 $tags['meta-generator'] = Html
::element( 'meta', [
3217 'name' => 'generator',
3218 'content' => "MediaWiki $wgVersion",
3221 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3222 $tags['meta-referrer'] = Html
::element( 'meta', [
3223 'name' => 'referrer',
3224 'content' => $config->get( 'ReferrerPolicy' )
3228 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3229 if ( $p !== 'index,follow' ) {
3230 // http://www.robotstxt.org/wc/meta-user.html
3231 // Only show if it's different from the default robots policy
3232 $tags['meta-robots'] = Html
::element( 'meta', [
3238 foreach ( $this->mMetatags
as $tag ) {
3239 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3241 $tag[0] = substr( $tag[0], 5 );
3245 $tagName = "meta-{$tag[0]}";
3246 if ( isset( $tags[$tagName] ) ) {
3247 $tagName .= $tag[1];
3249 $tags[$tagName] = Html
::element( 'meta',
3252 'content' => $tag[1]
3257 foreach ( $this->mLinktags
as $tag ) {
3258 $tags[] = Html
::element( 'link', $tag );
3261 # Universal edit button
3262 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3263 $user = $this->getUser();
3264 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3265 && ( $this->getTitle()->exists() ||
3266 $this->getTitle()->quickUserCan( 'create', $user ) )
3268 // Original UniversalEditButton
3269 $msg = $this->msg( 'edit' )->text();
3270 $tags['universal-edit-button'] = Html
::element( 'link', [
3271 'rel' => 'alternate',
3272 'type' => 'application/x-wiki',
3274 'href' => $this->getTitle()->getEditURL(),
3276 // Alternate edit link
3277 $tags['alternative-edit'] = Html
::element( 'link', [
3280 'href' => $this->getTitle()->getEditURL(),
3285 # Generally the order of the favicon and apple-touch-icon links
3286 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3287 # uses whichever one appears later in the HTML source. Make sure
3288 # apple-touch-icon is specified first to avoid this.
3289 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3290 $tags['apple-touch-icon'] = Html
::element( 'link', [
3291 'rel' => 'apple-touch-icon',
3292 'href' => $config->get( 'AppleTouchIcon' )
3296 if ( $config->get( 'Favicon' ) !== false ) {
3297 $tags['favicon'] = Html
::element( 'link', [
3298 'rel' => 'shortcut icon',
3299 'href' => $config->get( 'Favicon' )
3303 # OpenSearch description link
3304 $tags['opensearch'] = Html
::element( 'link', [
3306 'type' => 'application/opensearchdescription+xml',
3307 'href' => wfScript( 'opensearch_desc' ),
3308 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3311 if ( $config->get( 'EnableAPI' ) ) {
3312 # Real Simple Discovery link, provides auto-discovery information
3313 # for the MediaWiki API (and potentially additional custom API
3314 # support such as WordPress or Twitter-compatible APIs for a
3315 # blogging extension, etc)
3316 $tags['rsd'] = Html
::element( 'link', [
3318 'type' => 'application/rsd+xml',
3319 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3320 // Whether RSD accepts relative or protocol-relative URLs is completely
3321 // undocumented, though.
3322 'href' => wfExpandUrl( wfAppendQuery(
3324 [ 'action' => 'rsd' ] ),
3331 if ( !$config->get( 'DisableLangConversion' ) ) {
3332 $lang = $this->getTitle()->getPageLanguage();
3333 if ( $lang->hasVariants() ) {
3334 $variants = $lang->getVariants();
3335 foreach ( $variants as $variant ) {
3336 $tags["variant-$variant"] = Html
::element( 'link', [
3337 'rel' => 'alternate',
3338 'hreflang' => wfBCP47( $variant ),
3339 'href' => $this->getTitle()->getLocalURL(
3340 [ 'variant' => $variant ] )
3344 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3345 $tags["variant-x-default"] = Html
::element( 'link', [
3346 'rel' => 'alternate',
3347 'hreflang' => 'x-default',
3348 'href' => $this->getTitle()->getLocalURL() ] );
3353 if ( $this->copyrightUrl
!== null ) {
3354 $copyright = $this->copyrightUrl
;
3357 if ( $config->get( 'RightsPage' ) ) {
3358 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3361 $copyright = $copy->getLocalURL();
3365 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3366 $copyright = $config->get( 'RightsUrl' );
3371 $tags['copyright'] = Html
::element( 'link', [
3372 'rel' => 'copyright',
3373 'href' => $copyright ]
3378 if ( $config->get( 'Feed' ) ) {
3381 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3382 # Use the page name for the title. In principle, this could
3383 # lead to issues with having the same name for different feeds
3384 # corresponding to the same page, but we can't avoid that at
3387 $feedLinks[] = $this->feedLink(
3390 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3392 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3397 # Recent changes feed should appear on every page (except recentchanges,
3398 # that would be redundant). Put it after the per-page feed to avoid
3399 # changing existing behavior. It's still available, probably via a
3400 # menu in your browser. Some sites might have a different feed they'd
3401 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3402 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3403 # If so, use it instead.
3404 $sitename = $config->get( 'Sitename' );
3405 if ( $config->get( 'OverrideSiteFeed' ) ) {
3406 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3407 // Note, this->feedLink escapes the url.
3408 $feedLinks[] = $this->feedLink(
3411 $this->msg( "site-{$type}-feed", $sitename )->text()
3414 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3415 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3416 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3417 $feedLinks[] = $this->feedLink(
3419 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3420 # For grep: 'site-rss-feed', 'site-atom-feed'
3421 $this->msg( "site-{$format}-feed", $sitename )->text()
3426 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3427 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3428 # use OutputPage::addFeedLink() instead.
3429 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3431 $tags +
= $feedLinks;
3435 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3436 if ( $canonicalUrl !== false ) {
3437 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3439 if ( $this->isArticleRelated() ) {
3440 // This affects all requests where "setArticleRelated" is true. This is
3441 // typically all requests that show content (query title, curid, oldid, diff),
3442 // and all wikipage actions (edit, delete, purge, info, history etc.).
3443 // It does not apply to File pages and Special pages.
3444 // 'history' and 'info' actions address page metadata rather than the page
3445 // content itself, so they may not be canonicalized to the view page url.
3446 // TODO: this ought to be better encapsulated in the Action class.
3447 $action = Action
::getActionName( $this->getContext() );
3448 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3449 $query = "action={$action}";
3453 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3455 $reqUrl = $this->getRequest()->getRequestURL();
3456 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3460 if ( $canonicalUrl !== false ) {
3461 $tags[] = Html
::element( 'link', [
3462 'rel' => 'canonical',
3463 'href' => $canonicalUrl
3471 * @return string HTML tag links to be put in the header.
3472 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3473 * OutputPage::getHeadLinksArray directly.
3475 public function getHeadLinks() {
3476 wfDeprecated( __METHOD__
, '1.24' );
3477 return implode( "\n", $this->getHeadLinksArray() );
3481 * Generate a "<link rel/>" for a feed.
3483 * @param string $type Feed type
3484 * @param string $url URL to the feed
3485 * @param string $text Value of the "title" attribute
3486 * @return string HTML fragment
3488 private function feedLink( $type, $url, $text ) {
3489 return Html
::element( 'link', [
3490 'rel' => 'alternate',
3491 'type' => "application/$type+xml",
3498 * Add a local or specified stylesheet, with the given media options.
3499 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3501 * @param string $style URL to the file
3502 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3503 * @param string $condition For IE conditional comments, specifying an IE version
3504 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3506 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3509 $options['media'] = $media;
3512 $options['condition'] = $condition;
3515 $options['dir'] = $dir;
3517 $this->styles
[$style] = $options;
3521 * Adds inline CSS styles
3522 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3524 * @param mixed $style_css Inline CSS
3525 * @param string $flip Set to 'flip' to flip the CSS if needed
3527 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3528 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3529 # If wanted, and the interface is right-to-left, flip the CSS
3530 $style_css = CSSJanus
::transform( $style_css, true, false );
3532 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3536 * Build exempt modules and legacy non-ResourceLoader styles.
3538 * @return string|WrappedStringList HTML
3540 protected function buildExemptModules() {
3543 $resourceLoader = $this->getResourceLoader();
3545 // Things that go after the ResourceLoaderDynamicStyles marker
3548 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3549 if ( $this->isUserCssPreview() ) {
3550 $append[] = $this->makeResourceLoaderLink(
3552 ResourceLoaderModule
::TYPE_STYLES
,
3553 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3556 // Load the previewed CSS. Janus it if needed.
3557 // User-supplied CSS is assumed to in the wiki's content language.
3558 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3559 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3560 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3562 $append[] = Html
::inlineStyle( $previewedCSS );
3565 // We want site, private and user styles to override dynamically added styles from
3566 // general modules, but we want dynamically added styles to override statically added
3567 // style modules. So the order has to be:
3568 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3569 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3570 // - ResourceLoaderDynamicStyles marker
3571 // - site/private/user styles
3573 // Add legacy styles added through addStyle()/addInlineStyle() here
3574 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3576 $chunks[] = Html
::element(
3578 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3581 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3582 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3583 ResourceLoaderModule
::TYPE_STYLES
3587 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3593 public function buildCssLinksArray() {
3596 // Add any extension CSS
3597 foreach ( $this->mExtStyles
as $url ) {
3598 $this->addStyle( $url );
3600 $this->mExtStyles
= [];
3602 foreach ( $this->styles
as $file => $options ) {
3603 $link = $this->styleLink( $file, $options );
3605 $links[$file] = $link;
3612 * Generate \<link\> tags for stylesheets
3614 * @param string $style URL to the file
3615 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3616 * @return string HTML fragment
3618 protected function styleLink( $style, array $options ) {
3619 if ( isset( $options['dir'] ) ) {
3620 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3625 if ( isset( $options['media'] ) ) {
3626 $media = self
::transformCssMedia( $options['media'] );
3627 if ( is_null( $media ) ) {
3634 if ( substr( $style, 0, 1 ) == '/' ||
3635 substr( $style, 0, 5 ) == 'http:' ||
3636 substr( $style, 0, 6 ) == 'https:' ) {
3639 $config = $this->getConfig();
3640 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3641 $config->get( 'StyleVersion' );
3644 $link = Html
::linkedStyle( $url, $media );
3646 if ( isset( $options['condition'] ) ) {
3647 $condition = htmlspecialchars( $options['condition'] );
3648 $link = "<!--[if $condition]>$link<![endif]-->";
3654 * Transform path to web-accessible static resource.
3656 * This is used to add a validation hash as query string.
3657 * This aids various behaviors:
3659 * - Put long Cache-Control max-age headers on responses for improved
3660 * cache performance.
3661 * - Get the correct version of a file as expected by the current page.
3662 * - Instantly get the updated version of a file after deployment.
3664 * Avoid using this for urls included in HTML as otherwise clients may get different
3665 * versions of a resource when navigating the site depending on when the page was cached.
3666 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3667 * an external stylesheet).
3670 * @param Config $config
3671 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3672 * @return string URL
3674 public static function transformResourcePath( Config
$config, $path ) {
3676 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3677 if ( $remotePathPrefix === '' ) {
3678 // The configured base path is required to be empty string for
3679 // wikis in the domain root
3682 $remotePath = $remotePathPrefix;
3684 if ( strpos( $path, $remotePath ) !== 0 ) {
3685 // Path is outside wgResourceBasePath, ignore.
3688 $path = RelPath\
getRelativePath( $path, $remotePath );
3689 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3693 * Utility method for transformResourceFilePath().
3695 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3698 * @param string $remotePath URL path prefix that points to $localPath
3699 * @param string $localPath File directory exposed at $remotePath
3700 * @param string $file Path to target file relative to $localPath
3701 * @return string URL
3703 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3704 $hash = md5_file( "$localPath/$file" );
3705 if ( $hash === false ) {
3706 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3709 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3713 * Transform "media" attribute based on request parameters
3715 * @param string $media Current value of the "media" attribute
3716 * @return string Modified value of the "media" attribute, or null to skip
3719 public static function transformCssMedia( $media ) {
3722 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3723 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3725 // Switch in on-screen display for media testing
3727 'printable' => 'print',
3728 'handheld' => 'handheld',
3730 foreach ( $switches as $switch => $targetMedia ) {
3731 if ( $wgRequest->getBool( $switch ) ) {
3732 if ( $media == $targetMedia ) {
3734 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3735 /* This regex will not attempt to understand a comma-separated media_query_list
3737 * Example supported values for $media:
3738 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3739 * Example NOT supported value for $media:
3740 * '3d-glasses, screen, print and resolution > 90dpi'
3742 * If it's a print request, we never want any kind of screen stylesheets
3743 * If it's a handheld request (currently the only other choice with a switch),
3744 * we don't want simple 'screen' but we might want screen queries that
3745 * have a max-width or something, so we'll pass all others on and let the
3746 * client do the query.
3748 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3759 * Add a wikitext-formatted message to the output.
3760 * This is equivalent to:
3762 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3764 public function addWikiMsg( /*...*/ ) {
3765 $args = func_get_args();
3766 $name = array_shift( $args );
3767 $this->addWikiMsgArray( $name, $args );
3771 * Add a wikitext-formatted message to the output.
3772 * Like addWikiMsg() except the parameters are taken as an array
3773 * instead of a variable argument list.
3775 * @param string $name
3776 * @param array $args
3778 public function addWikiMsgArray( $name, $args ) {
3779 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3783 * This function takes a number of message/argument specifications, wraps them in
3784 * some overall structure, and then parses the result and adds it to the output.
3786 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3787 * and so on. The subsequent arguments may be either
3788 * 1) strings, in which case they are message names, or
3789 * 2) arrays, in which case, within each array, the first element is the message
3790 * name, and subsequent elements are the parameters to that message.
3792 * Don't use this for messages that are not in the user's interface language.
3796 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3800 * $wgOut->addWikiText( "<div class='error'>\n"
3801 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3803 * The newline after the opening div is needed in some wikitext. See bug 19226.
3805 * @param string $wrap
3807 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3808 $msgSpecs = func_get_args();
3809 array_shift( $msgSpecs );
3810 $msgSpecs = array_values( $msgSpecs );
3812 foreach ( $msgSpecs as $n => $spec ) {
3813 if ( is_array( $spec ) ) {
3815 $name = array_shift( $args );
3816 if ( isset( $args['options'] ) ) {
3817 unset( $args['options'] );
3819 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3827 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3829 $this->addWikiText( $s );
3833 * Enables/disables TOC, doesn't override __NOTOC__
3837 public function enableTOC( $flag = true ) {
3838 $this->mEnableTOC
= $flag;
3845 public function isTOCEnabled() {
3846 return $this->mEnableTOC
;
3850 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3854 public function enableSectionEditLinks( $flag = true ) {
3855 $this->mEnableSectionEditLinks
= $flag;
3862 public function sectionEditLinksEnabled() {
3863 return $this->mEnableSectionEditLinks
;
3867 * Helper function to setup the PHP implementation of OOUI to use in this request.
3870 * @param String $skinName The Skin name to determine the correct OOUI theme
3871 * @param String $dir Language direction
3873 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3874 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3875 // Make keys (skin names) lowercase for case-insensitive matching.
3876 $themes = array_change_key_case( $themes, CASE_LOWER
);
3877 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3878 // For example, 'OOUI\MediaWikiTheme'.
3879 $themeClass = "OOUI\\{$theme}Theme";
3880 OOUI\Theme
::setSingleton( new $themeClass() );
3881 OOUI\Element
::setDefaultDir( $dir );
3885 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3886 * MediaWiki and this OutputPage instance.
3890 public function enableOOUI() {
3892 strtolower( $this->getSkin()->getSkinName() ),
3893 $this->getLanguage()->getDir()
3895 $this->addModuleStyles( [
3896 'oojs-ui-core.styles',
3897 'oojs-ui.styles.icons',
3898 'oojs-ui.styles.indicators',
3899 'oojs-ui.styles.textures',
3900 'mediawiki.widgets.styles',
3905 * @param array $data Data from ParserOutput::getLimitReportData()
3908 public function setLimitReportData( array $data ) {
3909 $this->limitReportData
= $data;