3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use WrappedString\WrappedString
;
27 use WrappedString\WrappedStringList
;
30 * This class should be covered by a general architecture document which does
31 * not exist as of January 2011. This is one of the Core classes and should
32 * be read at least once by any new developers.
34 * This class is used to prepare the final rendering. A skin is then
35 * applied to the output parameters (links, javascript, html, categories ...).
37 * @todo FIXME: Another class handles sending the whole page to the client.
39 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
44 class OutputPage
extends ContextSource
{
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
49 protected $mLinktags = [];
52 protected $mCanonicalUrl = false;
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
58 protected $mExtStyles = [];
61 * @var string Should be private - has getter and setter. Contains
63 public $mPagetitle = '';
66 * @var string Contains all of the "<body>" content. Should be private we
67 * got set/get accessors and the append() method.
69 public $mBodytext = '';
71 /** @var string Stores contents of "<title>" tag */
72 private $mHTMLtitle = '';
75 * @var bool Is the displayed content related to the source of the
76 * corresponding wiki article.
78 private $mIsarticle = false;
80 /** @var bool Stores "article flag" toggle. */
81 private $mIsArticleRelated = true;
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
87 private $mPrintable = false;
90 * @var array Contains the page subtitle. Special pages usually have some
91 * links here. Don't confuse with site subtitle added by skins.
93 private $mSubtitle = [];
96 public $mRedirect = '';
99 protected $mStatusCode;
102 * @var string Used for sending cache control.
103 * The whole caching system should probably be moved into its own class.
105 protected $mLastModified = '';
108 protected $mCategoryLinks = [];
111 protected $mCategories = [
117 protected $mIndicators = [];
119 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
120 private $mLanguageLinks = [];
123 * Used for JavaScript (predates ResourceLoader)
124 * @todo We should split JS / CSS.
125 * mScripts content is inserted as is in "<head>" by Skin. This might
126 * contain either a link to a stylesheet or inline CSS.
128 private $mScripts = '';
130 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
131 protected $mInlineStyles = '';
134 * @var string Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 public $mPageLinkTitle = '';
139 /** @var array Array of elements in "<head>". Parser might add its own headers! */
140 protected $mHeadItems = [];
143 protected $mModules = [];
146 protected $mModuleScripts = [];
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
161 private $rlUserModuleState;
164 private $rlExemptStyleModules;
167 protected $mJsConfigVars = [];
170 protected $mTemplateIds = [];
173 protected $mImageTimeKeys = [];
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
181 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
182 * @see ResourceLoaderModule::$origin
183 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
185 protected $mAllowedModules = [
186 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
189 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
190 protected $mDoNothing = false;
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
201 protected $mParserOptions = null;
204 * Handles the Atom / RSS links.
205 * We probably only support Atom in 2011.
206 * @see $wgAdvertisedFeedTypes
208 private $mFeedLinks = [];
210 // Gwicke work on squid caching? Roughly from 2003.
211 protected $mEnableClientCache = true;
213 /** @var bool Flag if output should only contain the body of the article. */
214 private $mArticleBodyOnly = false;
217 protected $mNewSectionLink = false;
220 protected $mHideNewSectionLink = false;
223 * @var bool Comes from the parser. This was probably made to load CSS/JS
224 * only if we had "<gallery>". Used directly in CategoryPage.php.
225 * Looks like ResourceLoader can replace this.
227 public $mNoGallery = false;
230 private $mPageTitleActionText = '';
232 /** @var int Cache stuff. Looks like mEnableClientCache */
233 protected $mCdnMaxage = 0;
234 /** @var int Upper limit on mCdnMaxage */
235 protected $mCdnMaxageLimit = INF
;
238 * @var bool Controls if anti-clickjacking / frame-breaking headers will
239 * be sent. This should be done for pages where edit actions are possible.
240 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
242 protected $mPreventClickjacking = true;
244 /** @var int To include the variable {{REVISIONID}} */
245 private $mRevisionId = null;
248 private $mRevisionTimestamp = null;
251 protected $mFileVersion = null;
254 * @var array An array of stylesheet filenames (relative from skins path),
255 * with options for CSS media, IE conditions, and RTL/LTR direction.
256 * For internal use; add settings in the skin via $this->addStyle()
258 * Style again! This seems like a code duplication since we already have
259 * mStyles. This is what makes Open Source amazing.
261 protected $styles = [];
263 private $mIndexPolicy = 'index';
264 private $mFollowPolicy = 'follow';
265 private $mVaryHeader = [
266 'Accept-Encoding' => [ 'match=gzip' ],
270 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
275 private $mRedirectedFrom = null;
278 * Additional key => value data
280 private $mProperties = [];
283 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
285 private $mTarget = null;
288 * @var bool Whether parser output should contain table of contents
290 private $mEnableTOC = true;
293 * @var bool Whether parser output should contain section edit links
295 private $mEnableSectionEditLinks = true;
298 * @var string|null The URL to send in a <link> element with rel=copyright
300 private $copyrightUrl;
302 /** @var array Profiling data */
303 private $limitReportJSData = [];
306 * Constructor for OutputPage. This should not be called directly.
307 * Instead a new RequestContext should be created and it will implicitly create
308 * a OutputPage tied to that context.
309 * @param IContextSource|null $context
311 function __construct( IContextSource
$context = null ) {
312 if ( $context === null ) {
313 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
314 wfDeprecated( __METHOD__
, '1.18' );
316 $this->setContext( $context );
321 * Redirect to $url rather than displaying the normal page
323 * @param string $url URL
324 * @param string $responsecode HTTP status code
326 public function redirect( $url, $responsecode = '302' ) {
327 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
328 $this->mRedirect
= str_replace( "\n", '', $url );
329 $this->mRedirectCode
= $responsecode;
333 * Get the URL to redirect to, or an empty string if not redirect URL set
337 public function getRedirect() {
338 return $this->mRedirect
;
342 * Set the copyright URL to send with the output.
343 * Empty string to omit, null to reset.
347 * @param string|null $url
349 public function setCopyrightUrl( $url ) {
350 $this->copyrightUrl
= $url;
354 * Set the HTTP status code to send with the output.
356 * @param int $statusCode
358 public function setStatusCode( $statusCode ) {
359 $this->mStatusCode
= $statusCode;
363 * Add a new "<meta>" tag
364 * To add an http-equiv meta tag, precede the name with "http:"
366 * @param string $name Tag name
367 * @param string $val Tag value
369 function addMeta( $name, $val ) {
370 array_push( $this->mMetatags
, [ $name, $val ] );
374 * Returns the current <meta> tags
379 public function getMetaTags() {
380 return $this->mMetatags
;
384 * Add a new \<link\> tag to the page header.
386 * Note: use setCanonicalUrl() for rel=canonical.
388 * @param array $linkarr Associative array of attributes.
390 function addLink( array $linkarr ) {
391 array_push( $this->mLinktags
, $linkarr );
395 * Returns the current <link> tags
400 public function getLinkTags() {
401 return $this->mLinktags
;
405 * Add a new \<link\> with "rel" attribute set to "meta"
407 * @param array $linkarr Associative array mapping attribute names to their
408 * values, both keys and values will be escaped, and the
409 * "rel" attribute will be automatically added
411 function addMetadataLink( array $linkarr ) {
412 $linkarr['rel'] = $this->getMetadataAttribute();
413 $this->addLink( $linkarr );
417 * Set the URL to be used for the <link rel=canonical>. This should be used
418 * in preference to addLink(), to avoid duplicate link tags.
421 function setCanonicalUrl( $url ) {
422 $this->mCanonicalUrl
= $url;
426 * Returns the URL to be used for the <link rel=canonical> if
430 * @return bool|string
432 public function getCanonicalUrl() {
433 return $this->mCanonicalUrl
;
437 * Get the value of the "rel" attribute for metadata links
441 public function getMetadataAttribute() {
442 # note: buggy CC software only reads first "meta" link
443 static $haveMeta = false;
445 return 'alternate meta';
453 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
454 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
457 * @param string $script Raw HTML
459 function addScript( $script ) {
460 $this->mScripts
.= $script;
464 * Register and add a stylesheet from an extension directory.
466 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
467 * @param string $url Path to sheet. Provide either a full url (beginning
468 * with 'http', etc) or a relative path from the document root
469 * (beginning with '/'). Otherwise it behaves identically to
470 * addStyle() and draws from the /skins folder.
472 public function addExtensionStyle( $url ) {
473 wfDeprecated( __METHOD__
, '1.27' );
474 array_push( $this->mExtStyles
, $url );
478 * Get all styles added by extensions
480 * @deprecated since 1.27
483 function getExtStyle() {
484 wfDeprecated( __METHOD__
, '1.27' );
485 return $this->mExtStyles
;
489 * Add a JavaScript file out of skins/common, or a given relative path.
490 * Internal use only. Use OutputPage::addModules() if possible.
492 * @param string $file Filename in skins/common or complete on-server path
494 * @param string $version Style version of the file. Defaults to $wgStyleVersion
496 public function addScriptFile( $file, $version = null ) {
497 // See if $file parameter is an absolute URL or begins with a slash
498 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
501 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
503 if ( is_null( $version ) ) {
504 $version = $this->getConfig()->get( 'StyleVersion' );
506 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
510 * Add a self-contained script tag with the given contents
511 * Internal use only. Use OutputPage::addModules() if possible.
513 * @param string $script JavaScript text, no script tags
515 public function addInlineScript( $script ) {
516 $this->mScripts
.= Html
::inlineScript( $script );
520 * Filter an array of modules to remove insufficiently trustworthy members, and modules
521 * which are no longer registered (eg a page is cached before an extension is disabled)
522 * @param array $modules
523 * @param string|null $position If not null, only return modules with this position
524 * @param string $type
527 protected function filterModules( array $modules, $position = null,
528 $type = ResourceLoaderModule
::TYPE_COMBINED
530 $resourceLoader = $this->getResourceLoader();
531 $filteredModules = [];
532 foreach ( $modules as $val ) {
533 $module = $resourceLoader->getModule( $val );
534 if ( $module instanceof ResourceLoaderModule
535 && $module->getOrigin() <= $this->getAllowedModules( $type )
536 && ( is_null( $position ) ||
$module->getPosition() == $position )
538 if ( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) ) {
539 $this->warnModuleTargetFilter( $module->getName() );
542 $filteredModules[] = $val;
545 return $filteredModules;
548 private function warnModuleTargetFilter( $moduleName ) {
549 static $warnings = [];
550 if ( isset( $warnings[$this->mTarget
][$moduleName] ) ) {
553 $warnings[$this->mTarget
][$moduleName] = true;
554 $this->getResourceLoader()->getLogger()->debug(
555 'Module "{module}" not loadable on target "{target}".',
557 'module' => $moduleName,
558 'target' => $this->mTarget
,
564 * Get the list of modules to include on this page
566 * @param bool $filter Whether to filter out insufficiently trustworthy modules
567 * @param string|null $position If not null, only return modules with this position
568 * @param string $param
569 * @return array Array of module names
571 public function getModules( $filter = false, $position = null, $param = 'mModules',
572 $type = ResourceLoaderModule
::TYPE_COMBINED
574 $modules = array_values( array_unique( $this->$param ) );
576 ?
$this->filterModules( $modules, $position, $type )
581 * Add one or more modules recognized by ResourceLoader. Modules added
582 * through this function will be loaded by ResourceLoader when the
585 * @param string|array $modules Module name (string) or array of module names
587 public function addModules( $modules ) {
588 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
592 * Get the list of module JS to include on this page
594 * @param bool $filter
595 * @param string|null $position
596 * @return array Array of module names
598 public function getModuleScripts( $filter = false, $position = null ) {
599 return $this->getModules( $filter, $position, 'mModuleScripts',
600 ResourceLoaderModule
::TYPE_SCRIPTS
605 * Add only JS of one or more modules recognized by ResourceLoader. Module
606 * scripts added through this function will be loaded by ResourceLoader when
609 * @param string|array $modules Module name (string) or array of module names
611 public function addModuleScripts( $modules ) {
612 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
616 * Get the list of module CSS to include on this page
618 * @param bool $filter
619 * @param string|null $position
620 * @return array Array of module names
622 public function getModuleStyles( $filter = false, $position = null ) {
623 return $this->getModules( $filter, $position, 'mModuleStyles',
624 ResourceLoaderModule
::TYPE_STYLES
629 * Add only CSS of one or more modules recognized by ResourceLoader.
631 * Module styles added through this function will be added using standard link CSS
632 * tags, rather than as a combined Javascript and CSS package. Thus, they will
633 * load when JavaScript is disabled (unless CSS also happens to be disabled).
635 * @param string|array $modules Module name (string) or array of module names
637 public function addModuleStyles( $modules ) {
638 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
642 * @return null|string ResourceLoader target
644 public function getTarget() {
645 return $this->mTarget
;
649 * Sets ResourceLoader target for load.php links. If null, will be omitted
651 * @param string|null $target
653 public function setTarget( $target ) {
654 $this->mTarget
= $target;
658 * Get an array of head items
662 function getHeadItemsArray() {
663 return $this->mHeadItems
;
667 * Add or replace a head item to the output
669 * Whenever possible, use more specific options like ResourceLoader modules,
670 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
671 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
672 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
673 * This would be your very LAST fallback.
675 * @param string $name Item name
676 * @param string $value Raw HTML
678 public function addHeadItem( $name, $value ) {
679 $this->mHeadItems
[$name] = $value;
683 * Add one or more head items to the output
686 * @param string|string[] $value Raw HTML
688 public function addHeadItems( $values ) {
689 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$values );
693 * Check if the header item $name is already set
695 * @param string $name Item name
698 public function hasHeadItem( $name ) {
699 return isset( $this->mHeadItems
[$name] );
703 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
706 public function setETag( $tag ) {
710 * Set whether the output should only contain the body of the article,
711 * without any skin, sidebar, etc.
712 * Used e.g. when calling with "action=render".
714 * @param bool $only Whether to output only the body of the article
716 public function setArticleBodyOnly( $only ) {
717 $this->mArticleBodyOnly
= $only;
721 * Return whether the output will contain only the body of the article
725 public function getArticleBodyOnly() {
726 return $this->mArticleBodyOnly
;
730 * Set an additional output property
733 * @param string $name
734 * @param mixed $value
736 public function setProperty( $name, $value ) {
737 $this->mProperties
[$name] = $value;
741 * Get an additional output property
744 * @param string $name
745 * @return mixed Property value or null if not found
747 public function getProperty( $name ) {
748 if ( isset( $this->mProperties
[$name] ) ) {
749 return $this->mProperties
[$name];
756 * checkLastModified tells the client to use the client-cached page if
757 * possible. If successful, the OutputPage is disabled so that
758 * any future call to OutputPage->output() have no effect.
760 * Side effect: sets mLastModified for Last-Modified header
762 * @param string $timestamp
764 * @return bool True if cache-ok headers was sent.
766 public function checkLastModified( $timestamp ) {
767 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
768 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
771 $config = $this->getConfig();
772 if ( !$config->get( 'CachePages' ) ) {
773 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
777 $timestamp = wfTimestamp( TS_MW
, $timestamp );
779 'page' => $timestamp,
780 'user' => $this->getUser()->getTouched(),
781 'epoch' => $config->get( 'CacheEpoch' )
783 if ( $config->get( 'UseSquid' ) ) {
784 // bug 44570: the core page itself may not change, but resources might
785 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
787 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
789 $maxModified = max( $modifiedTimes );
790 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
792 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
793 if ( $clientHeader === false ) {
794 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
798 # IE sends sizes after the date like this:
799 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
800 # this breaks strtotime().
801 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
803 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
804 $clientHeaderTime = strtotime( $clientHeader );
805 MediaWiki\restoreWarnings
();
806 if ( !$clientHeaderTime ) {
808 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
811 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
815 foreach ( $modifiedTimes as $name => $value ) {
816 if ( $info !== '' ) {
819 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
822 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
823 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
824 wfDebug( __METHOD__
. ": effective Last-Modified: " .
825 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
826 if ( $clientHeaderTime < $maxModified ) {
827 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
832 # Give a 304 Not Modified response code and disable body output
833 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
834 ini_set( 'zlib.output_compression', 0 );
835 $this->getRequest()->response()->statusHeader( 304 );
836 $this->sendCacheControl();
839 // Don't output a compressed blob when using ob_gzhandler;
840 // it's technically against HTTP spec and seems to confuse
841 // Firefox when the response gets split over two packets.
842 wfClearOutputBuffers();
848 * Override the last modified timestamp
850 * @param string $timestamp New timestamp, in a format readable by
853 public function setLastModified( $timestamp ) {
854 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
858 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
860 * @param string $policy The literal string to output as the contents of
861 * the meta tag. Will be parsed according to the spec and output in
865 public function setRobotPolicy( $policy ) {
866 $policy = Article
::formatRobotPolicy( $policy );
868 if ( isset( $policy['index'] ) ) {
869 $this->setIndexPolicy( $policy['index'] );
871 if ( isset( $policy['follow'] ) ) {
872 $this->setFollowPolicy( $policy['follow'] );
877 * Set the index policy for the page, but leave the follow policy un-
880 * @param string $policy Either 'index' or 'noindex'.
883 public function setIndexPolicy( $policy ) {
884 $policy = trim( $policy );
885 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
886 $this->mIndexPolicy
= $policy;
891 * Set the follow policy for the page, but leave the index policy un-
894 * @param string $policy Either 'follow' or 'nofollow'.
897 public function setFollowPolicy( $policy ) {
898 $policy = trim( $policy );
899 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
900 $this->mFollowPolicy
= $policy;
905 * Set the new value of the "action text", this will be added to the
906 * "HTML title", separated from it with " - ".
908 * @param string $text New value of the "action text"
910 public function setPageTitleActionText( $text ) {
911 $this->mPageTitleActionText
= $text;
915 * Get the value of the "action text"
919 public function getPageTitleActionText() {
920 return $this->mPageTitleActionText
;
924 * "HTML title" means the contents of "<title>".
925 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
927 * @param string|Message $name
929 public function setHTMLTitle( $name ) {
930 if ( $name instanceof Message
) {
931 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
933 $this->mHTMLtitle
= $name;
938 * Return the "HTML title", i.e. the content of the "<title>" tag.
942 public function getHTMLTitle() {
943 return $this->mHTMLtitle
;
947 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
951 public function setRedirectedFrom( $t ) {
952 $this->mRedirectedFrom
= $t;
956 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
957 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
958 * but not bad tags like \<script\>. This function automatically sets
959 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
960 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
961 * good tags like \<i\> will be dropped entirely.
963 * @param string|Message $name
965 public function setPageTitle( $name ) {
966 if ( $name instanceof Message
) {
967 $name = $name->setContext( $this->getContext() )->text();
970 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
971 # but leave "<i>foobar</i>" alone
972 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
973 $this->mPagetitle
= $nameWithTags;
975 # change "<i>foo&bar</i>" to "foo&bar"
977 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
978 ->inContentLanguage()
983 * Return the "page title", i.e. the content of the \<h1\> tag.
987 public function getPageTitle() {
988 return $this->mPagetitle
;
992 * Set the Title object to use
996 public function setTitle( Title
$t ) {
997 $this->getContext()->setTitle( $t );
1001 * Replace the subtitle with $str
1003 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1005 public function setSubtitle( $str ) {
1006 $this->clearSubtitle();
1007 $this->addSubtitle( $str );
1011 * Add $str to the subtitle
1013 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1015 public function addSubtitle( $str ) {
1016 if ( $str instanceof Message
) {
1017 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1019 $this->mSubtitle
[] = $str;
1024 * Build message object for a subtitle containing a backlink to a page
1026 * @param Title $title Title to link to
1027 * @param array $query Array of additional parameters to include in the link
1031 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1032 if ( $title->isRedirect() ) {
1033 $query['redirect'] = 'no';
1035 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1036 return wfMessage( 'backlinksubtitle' )
1037 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1041 * Add a subtitle containing a backlink to a page
1043 * @param Title $title Title to link to
1044 * @param array $query Array of additional parameters to include in the link
1046 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1047 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1051 * Clear the subtitles
1053 public function clearSubtitle() {
1054 $this->mSubtitle
= [];
1062 public function getSubtitle() {
1063 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1067 * Set the page as printable, i.e. it'll be displayed with all
1068 * print styles included
1070 public function setPrintable() {
1071 $this->mPrintable
= true;
1075 * Return whether the page is "printable"
1079 public function isPrintable() {
1080 return $this->mPrintable
;
1084 * Disable output completely, i.e. calling output() will have no effect
1086 public function disable() {
1087 $this->mDoNothing
= true;
1091 * Return whether the output will be completely disabled
1095 public function isDisabled() {
1096 return $this->mDoNothing
;
1100 * Show an "add new section" link?
1104 public function showNewSectionLink() {
1105 return $this->mNewSectionLink
;
1109 * Forcibly hide the new section link?
1113 public function forceHideNewSectionLink() {
1114 return $this->mHideNewSectionLink
;
1118 * Add or remove feed links in the page header
1119 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1120 * for the new version
1121 * @see addFeedLink()
1123 * @param bool $show True: add default feeds, false: remove all feeds
1125 public function setSyndicated( $show = true ) {
1127 $this->setFeedAppendQuery( false );
1129 $this->mFeedLinks
= [];
1134 * Add default feeds to the page header
1135 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1136 * for the new version
1137 * @see addFeedLink()
1139 * @param string $val Query to append to feed links or false to output
1142 public function setFeedAppendQuery( $val ) {
1143 $this->mFeedLinks
= [];
1145 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1146 $query = "feed=$type";
1147 if ( is_string( $val ) ) {
1148 $query .= '&' . $val;
1150 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1155 * Add a feed link to the page header
1157 * @param string $format Feed type, should be a key of $wgFeedClasses
1158 * @param string $href URL
1160 public function addFeedLink( $format, $href ) {
1161 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1162 $this->mFeedLinks
[$format] = $href;
1167 * Should we output feed links for this page?
1170 public function isSyndicated() {
1171 return count( $this->mFeedLinks
) > 0;
1175 * Return URLs for each supported syndication format for this page.
1176 * @return array Associating format keys with URLs
1178 public function getSyndicationLinks() {
1179 return $this->mFeedLinks
;
1183 * Will currently always return null
1187 public function getFeedAppendQuery() {
1188 return $this->mFeedLinksAppendQuery
;
1192 * Set whether the displayed content is related to the source of the
1193 * corresponding article on the wiki
1194 * Setting true will cause the change "article related" toggle to true
1198 public function setArticleFlag( $v ) {
1199 $this->mIsarticle
= $v;
1201 $this->mIsArticleRelated
= $v;
1206 * Return whether the content displayed page is related to the source of
1207 * the corresponding article on the wiki
1211 public function isArticle() {
1212 return $this->mIsarticle
;
1216 * Set whether this page is related an article on the wiki
1217 * Setting false will cause the change of "article flag" toggle to false
1221 public function setArticleRelated( $v ) {
1222 $this->mIsArticleRelated
= $v;
1224 $this->mIsarticle
= false;
1229 * Return whether this page is related an article on the wiki
1233 public function isArticleRelated() {
1234 return $this->mIsArticleRelated
;
1238 * Add new language links
1240 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1241 * (e.g. 'fr:Test page')
1243 public function addLanguageLinks( array $newLinkArray ) {
1244 $this->mLanguageLinks +
= $newLinkArray;
1248 * Reset the language links and add new language links
1250 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1251 * (e.g. 'fr:Test page')
1253 public function setLanguageLinks( array $newLinkArray ) {
1254 $this->mLanguageLinks
= $newLinkArray;
1258 * Get the list of language links
1260 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1262 public function getLanguageLinks() {
1263 return $this->mLanguageLinks
;
1267 * Add an array of categories, with names in the keys
1269 * @param array $categories Mapping category name => sort key
1271 public function addCategoryLinks( array $categories ) {
1274 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1278 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1280 # Set all the values to 'normal'.
1281 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1283 # Mark hidden categories
1284 foreach ( $res as $row ) {
1285 if ( isset( $row->pp_value
) ) {
1286 $categories[$row->page_title
] = 'hidden';
1290 // Avoid PHP 7.1 warning of passing $this by reference
1291 $outputPage = $this;
1292 # Add the remaining categories to the skin
1294 'OutputPageMakeCategoryLinks',
1295 [ &$outputPage, $categories, &$this->mCategoryLinks
] )
1297 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1298 foreach ( $categories as $category => $type ) {
1299 // array keys will cast numeric category names to ints, so cast back to string
1300 $category = (string)$category;
1301 $origcategory = $category;
1302 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1306 $wgContLang->findVariantLink( $category, $title, true );
1307 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1310 $text = $wgContLang->convertHtml( $title->getText() );
1311 $this->mCategories
[$type][] = $title->getText();
1312 $this->mCategoryLinks
[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1318 * @param array $categories
1319 * @return bool|ResultWrapper
1321 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1322 # Add the links to a LinkBatch
1323 $arr = [ NS_CATEGORY
=> $categories ];
1324 $lb = new LinkBatch
;
1325 $lb->setArray( $arr );
1327 # Fetch existence plus the hiddencat property
1328 $dbr = wfGetDB( DB_REPLICA
);
1329 $fields = array_merge(
1330 LinkCache
::getSelectFields(),
1331 [ 'page_namespace', 'page_title', 'pp_value' ]
1334 $res = $dbr->select( [ 'page', 'page_props' ],
1336 $lb->constructSet( 'page', $dbr ),
1339 [ 'page_props' => [ 'LEFT JOIN', [
1340 'pp_propname' => 'hiddencat',
1345 # Add the results to the link cache
1346 $lb->addResultToCache( LinkCache
::singleton(), $res );
1352 * Reset the category links (but not the category list) and add $categories
1354 * @param array $categories Mapping category name => sort key
1356 public function setCategoryLinks( array $categories ) {
1357 $this->mCategoryLinks
= [];
1358 $this->addCategoryLinks( $categories );
1362 * Get the list of category links, in a 2-D array with the following format:
1363 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1364 * hidden categories) and $link a HTML fragment with a link to the category
1369 public function getCategoryLinks() {
1370 return $this->mCategoryLinks
;
1374 * Get the list of category names this page belongs to.
1376 * @param string $type The type of categories which should be returned. Possible values:
1377 * * all: all categories of all types
1378 * * hidden: only the hidden categories
1379 * * normal: all categories, except hidden categories
1380 * @return array Array of strings
1382 public function getCategories( $type = 'all' ) {
1383 if ( $type === 'all' ) {
1384 $allCategories = [];
1385 foreach ( $this->mCategories
as $categories ) {
1386 $allCategories = array_merge( $allCategories, $categories );
1388 return $allCategories;
1390 if ( !isset( $this->mCategories
[$type] ) ) {
1391 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1393 return $this->mCategories
[$type];
1397 * Add an array of indicators, with their identifiers as array
1398 * keys and HTML contents as values.
1400 * In case of duplicate keys, existing values are overwritten.
1402 * @param array $indicators
1405 public function setIndicators( array $indicators ) {
1406 $this->mIndicators
= $indicators +
$this->mIndicators
;
1407 // Keep ordered by key
1408 ksort( $this->mIndicators
);
1412 * Get the indicators associated with this page.
1414 * The array will be internally ordered by item keys.
1416 * @return array Keys: identifiers, values: HTML contents
1419 public function getIndicators() {
1420 return $this->mIndicators
;
1424 * Adds help link with an icon via page indicators.
1425 * Link target can be overridden by a local message containing a wikilink:
1426 * the message key is: lowercase action or special page name + '-helppage'.
1427 * @param string $to Target MediaWiki.org page title or encoded URL.
1428 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1431 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1432 $this->addModuleStyles( 'mediawiki.helplink' );
1433 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1435 if ( $overrideBaseUrl ) {
1438 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1439 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1442 $link = Html
::rawElement(
1446 'target' => '_blank',
1447 'class' => 'mw-helplink',
1452 $this->setIndicators( [ 'mw-helplink' => $link ] );
1456 * Do not allow scripts which can be modified by wiki users to load on this page;
1457 * only allow scripts bundled with, or generated by, the software.
1458 * Site-wide styles are controlled by a config setting, since they can be
1459 * used to create a custom skin/theme, but not user-specific ones.
1461 * @todo this should be given a more accurate name
1463 public function disallowUserJs() {
1464 $this->reduceAllowedModules(
1465 ResourceLoaderModule
::TYPE_SCRIPTS
,
1466 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1469 // Site-wide styles are controlled by a config setting, see bug 71621
1470 // for background on why. User styles are never allowed.
1471 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1472 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1474 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1476 $this->reduceAllowedModules(
1477 ResourceLoaderModule
::TYPE_STYLES
,
1483 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1484 * @see ResourceLoaderModule::$origin
1485 * @param string $type ResourceLoaderModule TYPE_ constant
1486 * @return int ResourceLoaderModule ORIGIN_ class constant
1488 public function getAllowedModules( $type ) {
1489 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1490 return min( array_values( $this->mAllowedModules
) );
1492 return isset( $this->mAllowedModules
[$type] )
1493 ?
$this->mAllowedModules
[$type]
1494 : ResourceLoaderModule
::ORIGIN_ALL
;
1499 * Limit the highest level of CSS/JS untrustworthiness allowed.
1501 * If passed the same or a higher level than the current level of untrustworthiness set, the
1502 * level will remain unchanged.
1504 * @param string $type
1505 * @param int $level ResourceLoaderModule class constant
1507 public function reduceAllowedModules( $type, $level ) {
1508 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1512 * Prepend $text to the body HTML
1514 * @param string $text HTML
1516 public function prependHTML( $text ) {
1517 $this->mBodytext
= $text . $this->mBodytext
;
1521 * Append $text to the body HTML
1523 * @param string $text HTML
1525 public function addHTML( $text ) {
1526 $this->mBodytext
.= $text;
1530 * Shortcut for adding an Html::element via addHTML.
1534 * @param string $element
1535 * @param array $attribs
1536 * @param string $contents
1538 public function addElement( $element, array $attribs = [], $contents = '' ) {
1539 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1543 * Clear the body HTML
1545 public function clearHTML() {
1546 $this->mBodytext
= '';
1552 * @return string HTML
1554 public function getHTML() {
1555 return $this->mBodytext
;
1559 * Get/set the ParserOptions object to use for wikitext parsing
1561 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1562 * current ParserOption object
1563 * @return ParserOptions
1565 public function parserOptions( $options = null ) {
1566 if ( $options !== null && !empty( $options->isBogus
) ) {
1567 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1568 // been changed somehow, and keep it if so.
1569 $anonPO = ParserOptions
::newFromAnon();
1570 $anonPO->setEditSection( false );
1571 if ( !$options->matches( $anonPO ) ) {
1572 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1573 $options->isBogus
= false;
1577 if ( !$this->mParserOptions
) {
1578 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1579 // $wgUser isn't unstubbable yet, so don't try to get a
1580 // ParserOptions for it. And don't cache this ParserOptions
1582 $po = ParserOptions
::newFromAnon();
1583 $po->setEditSection( false );
1584 $po->isBogus
= true;
1585 if ( $options !== null ) {
1586 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1591 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1592 $this->mParserOptions
->setEditSection( false );
1595 if ( $options !== null && !empty( $options->isBogus
) ) {
1596 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1598 return wfSetVar( $this->mParserOptions
, null, true );
1600 return wfSetVar( $this->mParserOptions
, $options );
1605 * Set the revision ID which will be seen by the wiki text parser
1606 * for things such as embedded {{REVISIONID}} variable use.
1608 * @param int|null $revid An positive integer, or null
1609 * @return mixed Previous value
1611 public function setRevisionId( $revid ) {
1612 $val = is_null( $revid ) ?
null : intval( $revid );
1613 return wfSetVar( $this->mRevisionId
, $val );
1617 * Get the displayed revision ID
1621 public function getRevisionId() {
1622 return $this->mRevisionId
;
1626 * Set the timestamp of the revision which will be displayed. This is used
1627 * to avoid a extra DB call in Skin::lastModified().
1629 * @param string|null $timestamp
1630 * @return mixed Previous value
1632 public function setRevisionTimestamp( $timestamp ) {
1633 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1637 * Get the timestamp of displayed revision.
1638 * This will be null if not filled by setRevisionTimestamp().
1640 * @return string|null
1642 public function getRevisionTimestamp() {
1643 return $this->mRevisionTimestamp
;
1647 * Set the displayed file version
1649 * @param File|bool $file
1650 * @return mixed Previous value
1652 public function setFileVersion( $file ) {
1654 if ( $file instanceof File
&& $file->exists() ) {
1655 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1657 return wfSetVar( $this->mFileVersion
, $val, true );
1661 * Get the displayed file version
1663 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1665 public function getFileVersion() {
1666 return $this->mFileVersion
;
1670 * Get the templates used on this page
1672 * @return array (namespace => dbKey => revId)
1675 public function getTemplateIds() {
1676 return $this->mTemplateIds
;
1680 * Get the files used on this page
1682 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1685 public function getFileSearchOptions() {
1686 return $this->mImageTimeKeys
;
1690 * Convert wikitext to HTML and add it to the buffer
1691 * Default assumes that the current page title will be used.
1693 * @param string $text
1694 * @param bool $linestart Is this the start of a line?
1695 * @param bool $interface Is this text in the user interface language?
1696 * @throws MWException
1698 public function addWikiText( $text, $linestart = true, $interface = true ) {
1699 $title = $this->getTitle(); // Work around E_STRICT
1701 throw new MWException( 'Title is null' );
1703 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1707 * Add wikitext with a custom Title object
1709 * @param string $text Wikitext
1710 * @param Title $title
1711 * @param bool $linestart Is this the start of a line?
1713 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1714 $this->addWikiTextTitle( $text, $title, $linestart );
1718 * Add wikitext with a custom Title object and tidy enabled.
1720 * @param string $text Wikitext
1721 * @param Title $title
1722 * @param bool $linestart Is this the start of a line?
1724 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1725 $this->addWikiTextTitle( $text, $title, $linestart, true );
1729 * Add wikitext with tidy enabled
1731 * @param string $text Wikitext
1732 * @param bool $linestart Is this the start of a line?
1734 public function addWikiTextTidy( $text, $linestart = true ) {
1735 $title = $this->getTitle();
1736 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1740 * Add wikitext with a custom Title object
1742 * @param string $text Wikitext
1743 * @param Title $title
1744 * @param bool $linestart Is this the start of a line?
1745 * @param bool $tidy Whether to use tidy
1746 * @param bool $interface Whether it is an interface message
1747 * (for example disables conversion)
1749 public function addWikiTextTitle( $text, Title
$title, $linestart,
1750 $tidy = false, $interface = false
1754 $popts = $this->parserOptions();
1755 $oldTidy = $popts->setTidy( $tidy );
1756 $popts->setInterfaceMessage( (bool)$interface );
1758 $parserOutput = $wgParser->getFreshParser()->parse(
1759 $text, $title, $popts,
1760 $linestart, true, $this->mRevisionId
1763 $popts->setTidy( $oldTidy );
1765 $this->addParserOutput( $parserOutput );
1769 * Add a ParserOutput object, but without Html.
1771 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1772 * @param ParserOutput $parserOutput
1774 public function addParserOutputNoText( $parserOutput ) {
1775 wfDeprecated( __METHOD__
, '1.24' );
1776 $this->addParserOutputMetadata( $parserOutput );
1780 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1781 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1785 * @param ParserOutput $parserOutput
1787 public function addParserOutputMetadata( $parserOutput ) {
1788 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1789 $this->addCategoryLinks( $parserOutput->getCategories() );
1790 $this->setIndicators( $parserOutput->getIndicators() );
1791 $this->mNewSectionLink
= $parserOutput->getNewSection();
1792 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1794 if ( !$parserOutput->isCacheable() ) {
1795 $this->enableClientCache( false );
1797 $this->mNoGallery
= $parserOutput->getNoGallery();
1798 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1799 $this->addModules( $parserOutput->getModules() );
1800 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1801 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1802 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1803 $this->mPreventClickjacking
= $this->mPreventClickjacking
1804 ||
$parserOutput->preventClickjacking();
1806 // Template versioning...
1807 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1808 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1809 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1811 $this->mTemplateIds
[$ns] = $dbks;
1814 // File versioning...
1815 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1816 $this->mImageTimeKeys
[$dbk] = $data;
1819 // Hooks registered in the object
1820 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1821 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1822 list( $hookName, $data ) = $hookInfo;
1823 if ( isset( $parserOutputHooks[$hookName] ) ) {
1824 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1828 // Enable OOUI if requested via ParserOutput
1829 if ( $parserOutput->getEnableOOUI() ) {
1830 $this->enableOOUI();
1833 // Include parser limit report
1834 if ( !$this->limitReportJSData
) {
1835 $this->limitReportJSData
= $parserOutput->getLimitReportJSData();
1838 // Link flags are ignored for now, but may in the future be
1839 // used to mark individual language links.
1841 // Avoid PHP 7.1 warning of passing $this by reference
1842 $outputPage = $this;
1843 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1844 Hooks
::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1848 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1849 * ParserOutput object, without any other metadata.
1852 * @param ParserOutput $parserOutput
1854 public function addParserOutputContent( $parserOutput ) {
1855 $this->addParserOutputText( $parserOutput );
1857 $this->addModules( $parserOutput->getModules() );
1858 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1859 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1861 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1865 * Add the HTML associated with a ParserOutput object, without any metadata.
1868 * @param ParserOutput $parserOutput
1870 public function addParserOutputText( $parserOutput ) {
1871 $text = $parserOutput->getText();
1872 // Avoid PHP 7.1 warning of passing $this by reference
1873 $outputPage = $this;
1874 Hooks
::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1875 $this->addHTML( $text );
1879 * Add everything from a ParserOutput object.
1881 * @param ParserOutput $parserOutput
1883 function addParserOutput( $parserOutput ) {
1884 $this->addParserOutputMetadata( $parserOutput );
1885 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1887 // Touch section edit links only if not previously disabled
1888 if ( $parserOutput->getEditSectionTokens() ) {
1889 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1892 $this->addParserOutputText( $parserOutput );
1896 * Add the output of a QuickTemplate to the output buffer
1898 * @param QuickTemplate $template
1900 public function addTemplate( &$template ) {
1901 $this->addHTML( $template->getHTML() );
1905 * Parse wikitext and return the HTML.
1907 * @param string $text
1908 * @param bool $linestart Is this the start of a line?
1909 * @param bool $interface Use interface language ($wgLang instead of
1910 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1911 * This also disables LanguageConverter.
1912 * @param Language $language Target language object, will override $interface
1913 * @throws MWException
1914 * @return string HTML
1916 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1919 if ( is_null( $this->getTitle() ) ) {
1920 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1923 $popts = $this->parserOptions();
1925 $popts->setInterfaceMessage( true );
1927 if ( $language !== null ) {
1928 $oldLang = $popts->setTargetLanguage( $language );
1931 $parserOutput = $wgParser->getFreshParser()->parse(
1932 $text, $this->getTitle(), $popts,
1933 $linestart, true, $this->mRevisionId
1937 $popts->setInterfaceMessage( false );
1939 if ( $language !== null ) {
1940 $popts->setTargetLanguage( $oldLang );
1943 return $parserOutput->getText();
1947 * Parse wikitext, strip paragraphs, and return the HTML.
1949 * @param string $text
1950 * @param bool $linestart Is this the start of a line?
1951 * @param bool $interface Use interface language ($wgLang instead of
1952 * $wgContLang) while parsing language sensitive magic
1953 * words like GRAMMAR and PLURAL
1954 * @return string HTML
1956 public function parseInline( $text, $linestart = true, $interface = false ) {
1957 $parsed = $this->parse( $text, $linestart, $interface );
1958 return Parser
::stripOuterParagraph( $parsed );
1963 * @deprecated since 1.27 Use setCdnMaxage() instead
1965 public function setSquidMaxage( $maxage ) {
1966 $this->setCdnMaxage( $maxage );
1970 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1972 * @param int $maxage Maximum cache time on the CDN, in seconds.
1974 public function setCdnMaxage( $maxage ) {
1975 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1979 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1981 * @param int $maxage Maximum cache time on the CDN, in seconds
1984 public function lowerCdnMaxage( $maxage ) {
1985 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1986 $this->setCdnMaxage( $this->mCdnMaxage
);
1990 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1992 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1993 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1994 * TTL is 90% of the age of the object, subject to the min and max.
1996 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1997 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1998 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1999 * @return integer TTL in seconds
2002 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2003 $minTTL = $minTTL ?
: IExpiringStore
::TTL_MINUTE
;
2004 $maxTTL = $maxTTL ?
: $this->getConfig()->get( 'SquidMaxage' );
2006 if ( $mtime === null ||
$mtime === false ) {
2007 return $minTTL; // entity does not exist
2010 $age = time() - wfTimestamp( TS_UNIX
, $mtime );
2011 $adaptiveTTL = max( .9 * $age, $minTTL );
2012 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2014 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2016 return $adaptiveTTL;
2020 * Use enableClientCache(false) to force it to send nocache headers
2022 * @param bool $state
2026 public function enableClientCache( $state ) {
2027 return wfSetVar( $this->mEnableClientCache
, $state );
2031 * Get the list of cookies that will influence on the cache
2035 function getCacheVaryCookies() {
2037 if ( $cookies === null ) {
2038 $config = $this->getConfig();
2039 $cookies = array_merge(
2040 SessionManager
::singleton()->getVaryCookies(),
2044 $config->get( 'CacheVaryCookies' )
2046 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2052 * Check if the request has a cache-varying cookie header
2053 * If it does, it's very important that we don't allow public caching
2057 function haveCacheVaryCookies() {
2058 $request = $this->getRequest();
2059 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2060 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2061 wfDebug( __METHOD__
. ": found $cookieName\n" );
2065 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2070 * Add an HTTP header that will influence on the cache
2072 * @param string $header Header name
2073 * @param string[]|null $option Options for the Key header. See
2074 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2075 * for the list of valid options.
2077 public function addVaryHeader( $header, array $option = null ) {
2078 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2079 $this->mVaryHeader
[$header] = [];
2081 if ( !is_array( $option ) ) {
2084 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2088 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2089 * such as Accept-Encoding or Cookie
2093 public function getVaryHeader() {
2094 // If we vary on cookies, let's make sure it's always included here too.
2095 if ( $this->getCacheVaryCookies() ) {
2096 $this->addVaryHeader( 'Cookie' );
2099 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2100 $this->addVaryHeader( $header, $options );
2102 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2106 * Get a complete Key header
2110 public function getKeyHeader() {
2111 $cvCookies = $this->getCacheVaryCookies();
2113 $cookiesOption = [];
2114 foreach ( $cvCookies as $cookieName ) {
2115 $cookiesOption[] = 'param=' . $cookieName;
2117 $this->addVaryHeader( 'Cookie', $cookiesOption );
2119 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2120 $this->addVaryHeader( $header, $options );
2124 foreach ( $this->mVaryHeader
as $header => $option ) {
2125 $newheader = $header;
2126 if ( is_array( $option ) && count( $option ) > 0 ) {
2127 $newheader .= ';' . implode( ';', $option );
2129 $headers[] = $newheader;
2131 $key = 'Key: ' . implode( ',', $headers );
2137 * T23672: Add Accept-Language to Vary and Key headers
2138 * if there's no 'variant' parameter existed in GET.
2141 * /w/index.php?title=Main_page should always be served; but
2142 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2144 function addAcceptLanguage() {
2145 $title = $this->getTitle();
2146 if ( !$title instanceof Title
) {
2150 $lang = $title->getPageLanguage();
2151 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2152 $variants = $lang->getVariants();
2154 foreach ( $variants as $variant ) {
2155 if ( $variant === $lang->getCode() ) {
2158 $aloption[] = 'substr=' . $variant;
2160 // IE and some other browsers use BCP 47 standards in
2161 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2162 // We should handle these too.
2163 $variantBCP47 = wfBCP47( $variant );
2164 if ( $variantBCP47 !== $variant ) {
2165 $aloption[] = 'substr=' . $variantBCP47;
2169 $this->addVaryHeader( 'Accept-Language', $aloption );
2174 * Set a flag which will cause an X-Frame-Options header appropriate for
2175 * edit pages to be sent. The header value is controlled by
2176 * $wgEditPageFrameOptions.
2178 * This is the default for special pages. If you display a CSRF-protected
2179 * form on an ordinary view page, then you need to call this function.
2181 * @param bool $enable
2183 public function preventClickjacking( $enable = true ) {
2184 $this->mPreventClickjacking
= $enable;
2188 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2189 * This can be called from pages which do not contain any CSRF-protected
2192 public function allowClickjacking() {
2193 $this->mPreventClickjacking
= false;
2197 * Get the prevent-clickjacking flag
2202 public function getPreventClickjacking() {
2203 return $this->mPreventClickjacking
;
2207 * Get the X-Frame-Options header value (without the name part), or false
2208 * if there isn't one. This is used by Skin to determine whether to enable
2209 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2211 * @return string|false
2213 public function getFrameOptions() {
2214 $config = $this->getConfig();
2215 if ( $config->get( 'BreakFrames' ) ) {
2217 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2218 return $config->get( 'EditPageFrameOptions' );
2224 * Send cache control HTTP headers
2226 public function sendCacheControl() {
2227 $response = $this->getRequest()->response();
2228 $config = $this->getConfig();
2230 $this->addVaryHeader( 'Cookie' );
2231 $this->addAcceptLanguage();
2233 # don't serve compressed data to clients who can't handle it
2234 # maintain different caches for logged-in users and non-logged in ones
2235 $response->header( $this->getVaryHeader() );
2237 if ( $config->get( 'UseKeyHeader' ) ) {
2238 $response->header( $this->getKeyHeader() );
2241 if ( $this->mEnableClientCache
) {
2243 $config->get( 'UseSquid' ) &&
2244 !$response->hasCookies() &&
2245 !SessionManager
::getGlobalSession()->isPersistent() &&
2246 !$this->isPrintable() &&
2247 $this->mCdnMaxage
!= 0 &&
2248 !$this->haveCacheVaryCookies()
2250 if ( $config->get( 'UseESI' ) ) {
2251 # We'll purge the proxy cache explicitly, but require end user agents
2252 # to revalidate against the proxy on each visit.
2253 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2254 wfDebug( __METHOD__
.
2255 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2256 # start with a shorter timeout for initial testing
2257 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2259 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2260 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2262 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2264 # We'll purge the proxy cache for anons explicitly, but require end user agents
2265 # to revalidate against the proxy on each visit.
2266 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2267 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2268 wfDebug( __METHOD__
.
2269 ": local proxy caching; {$this->mLastModified} **", 'private' );
2270 # start with a shorter timeout for initial testing
2271 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2272 $response->header( "Cache-Control: " .
2273 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2276 # We do want clients to cache if they can, but they *must* check for updates
2277 # on revisiting the page.
2278 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2279 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2280 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2282 if ( $this->mLastModified
) {
2283 $response->header( "Last-Modified: {$this->mLastModified}" );
2286 wfDebug( __METHOD__
. ": no caching **", 'private' );
2288 # In general, the absence of a last modified header should be enough to prevent
2289 # the client from using its cache. We send a few other things just to make sure.
2290 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2291 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2292 $response->header( 'Pragma: no-cache' );
2297 * Finally, all the text has been munged and accumulated into
2298 * the object, let's actually output it:
2300 * @param bool $return Set to true to get the result as a string rather than sending it
2301 * @return string|null
2303 * @throws FatalError
2304 * @throws MWException
2306 public function output( $return = false ) {
2309 if ( $this->mDoNothing
) {
2310 return $return ?
'' : null;
2313 $response = $this->getRequest()->response();
2314 $config = $this->getConfig();
2316 if ( $this->mRedirect
!= '' ) {
2317 # Standards require redirect URLs to be absolute
2318 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2320 $redirect = $this->mRedirect
;
2321 $code = $this->mRedirectCode
;
2323 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2324 if ( $code == '301' ||
$code == '303' ) {
2325 if ( !$config->get( 'DebugRedirects' ) ) {
2326 $response->statusHeader( $code );
2328 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2330 if ( $config->get( 'VaryOnXFP' ) ) {
2331 $this->addVaryHeader( 'X-Forwarded-Proto' );
2333 $this->sendCacheControl();
2335 $response->header( "Content-Type: text/html; charset=utf-8" );
2336 if ( $config->get( 'DebugRedirects' ) ) {
2337 $url = htmlspecialchars( $redirect );
2338 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2339 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2340 print "</body>\n</html>\n";
2342 $response->header( 'Location: ' . $redirect );
2346 return $return ?
'' : null;
2347 } elseif ( $this->mStatusCode
) {
2348 $response->statusHeader( $this->mStatusCode
);
2351 # Buffer output; final headers may depend on later processing
2354 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2355 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2357 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2358 // jQuery etc. can work correctly.
2359 $response->header( 'X-UA-Compatible: IE=Edge' );
2361 // Prevent framing, if requested
2362 $frameOptions = $this->getFrameOptions();
2363 if ( $frameOptions ) {
2364 $response->header( "X-Frame-Options: $frameOptions" );
2367 if ( $this->mArticleBodyOnly
) {
2368 echo $this->mBodytext
;
2370 $sk = $this->getSkin();
2371 // add skin specific modules
2372 $modules = $sk->getDefaultModules();
2374 // Enforce various default modules for all pages and all skins
2376 // Keep this list as small as possible
2378 'mediawiki.page.startup',
2382 // Support for high-density display images if enabled
2383 if ( $config->get( 'ResponsiveImages' ) ) {
2384 $coreModules[] = 'mediawiki.hidpi';
2387 $this->addModules( $coreModules );
2388 foreach ( $modules as $group ) {
2389 $this->addModules( $group );
2391 MWDebug
::addModules( $this );
2393 // Avoid PHP 7.1 warning of passing $this by reference
2394 $outputPage = $this;
2395 // Hook that allows last minute changes to the output page, e.g.
2396 // adding of CSS or Javascript by extensions.
2397 Hooks
::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2401 } catch ( Exception
$e ) {
2402 ob_end_clean(); // bug T129657
2408 // This hook allows last minute changes to final overall output by modifying output buffer
2409 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2410 } catch ( Exception
$e ) {
2411 ob_end_clean(); // bug T129657
2415 $this->sendCacheControl();
2418 return ob_get_clean();
2426 * Prepare this object to display an error page; disable caching and
2427 * indexing, clear the current text and redirect, set the page's title
2428 * and optionally an custom HTML title (content of the "<title>" tag).
2430 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2431 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2432 * optional, if not passed the "<title>" attribute will be
2433 * based on $pageTitle
2435 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2436 $this->setPageTitle( $pageTitle );
2437 if ( $htmlTitle !== false ) {
2438 $this->setHTMLTitle( $htmlTitle );
2440 $this->setRobotPolicy( 'noindex,nofollow' );
2441 $this->setArticleRelated( false );
2442 $this->enableClientCache( false );
2443 $this->mRedirect
= '';
2444 $this->clearSubtitle();
2449 * Output a standard error page
2451 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2452 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2453 * showErrorPage( 'titlemsg', $messageObject );
2454 * showErrorPage( $titleMessageObject, $messageObject );
2456 * @param string|Message $title Message key (string) for page title, or a Message object
2457 * @param string|Message $msg Message key (string) for page text, or a Message object
2458 * @param array $params Message parameters; ignored if $msg is a Message object
2460 public function showErrorPage( $title, $msg, $params = [] ) {
2461 if ( !$title instanceof Message
) {
2462 $title = $this->msg( $title );
2465 $this->prepareErrorPage( $title );
2467 if ( $msg instanceof Message
) {
2468 if ( $params !== [] ) {
2469 trigger_error( 'Argument ignored: $params. The message parameters argument '
2470 . 'is discarded when the $msg argument is a Message object instead of '
2471 . 'a string.', E_USER_NOTICE
);
2473 $this->addHTML( $msg->parseAsBlock() );
2475 $this->addWikiMsgArray( $msg, $params );
2478 $this->returnToMain();
2482 * Output a standard permission error page
2484 * @param array $errors Error message keys or [key, param...] arrays
2485 * @param string $action Action that was denied or null if unknown
2487 public function showPermissionsErrorPage( array $errors, $action = null ) {
2488 foreach ( $errors as $key => $error ) {
2489 $errors[$key] = (array)$error;
2492 // For some action (read, edit, create and upload), display a "login to do this action"
2493 // error if all of the following conditions are met:
2494 // 1. the user is not logged in
2495 // 2. the only error is insufficient permissions (i.e. no block or something else)
2496 // 3. the error can be avoided simply by logging in
2497 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2498 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2499 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2500 && ( User
::groupHasPermission( 'user', $action )
2501 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2503 $displayReturnto = null;
2505 # Due to bug 32276, if a user does not have read permissions,
2506 # $this->getTitle() will just give Special:Badtitle, which is
2507 # not especially useful as a returnto parameter. Use the title
2508 # from the request instead, if there was one.
2509 $request = $this->getRequest();
2510 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2511 if ( $action == 'edit' ) {
2512 $msg = 'whitelistedittext';
2513 $displayReturnto = $returnto;
2514 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2515 $msg = 'nocreatetext';
2516 } elseif ( $action == 'upload' ) {
2517 $msg = 'uploadnologintext';
2519 $msg = 'loginreqpagetext';
2520 $displayReturnto = Title
::newMainPage();
2526 $query['returnto'] = $returnto->getPrefixedText();
2528 if ( !$request->wasPosted() ) {
2529 $returntoquery = $request->getValues();
2530 unset( $returntoquery['title'] );
2531 unset( $returntoquery['returnto'] );
2532 unset( $returntoquery['returntoquery'] );
2533 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2536 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
2537 $loginLink = $linkRenderer->makeKnownLink(
2538 SpecialPage
::getTitleFor( 'Userlogin' ),
2539 $this->msg( 'loginreqlink' )->text(),
2544 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2545 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2547 # Don't return to a page the user can't read otherwise
2548 # we'll end up in a pointless loop
2549 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2550 $this->returnToMain( null, $displayReturnto );
2553 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2554 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2559 * Display an error page indicating that a given version of MediaWiki is
2560 * required to use it
2562 * @param mixed $version The version of MediaWiki needed to use the page
2564 public function versionRequired( $version ) {
2565 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2567 $this->addWikiMsg( 'versionrequiredtext', $version );
2568 $this->returnToMain();
2572 * Format a list of error messages
2574 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2575 * @param string $action Action that was denied or null if unknown
2576 * @return string The wikitext error-messages, formatted into a list.
2578 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2579 if ( $action == null ) {
2580 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2582 $action_desc = $this->msg( "action-$action" )->plain();
2584 'permissionserrorstext-withaction',
2587 )->plain() . "\n\n";
2590 if ( count( $errors ) > 1 ) {
2591 $text .= '<ul class="permissions-errors">' . "\n";
2593 foreach ( $errors as $error ) {
2595 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2600 $text .= "<div class=\"permissions-errors\">\n" .
2601 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2609 * Display a page stating that the Wiki is in read-only mode.
2610 * Should only be called after wfReadOnly() has returned true.
2612 * Historically, this function was used to show the source of the page that the user
2613 * was trying to edit and _also_ permissions error messages. The relevant code was
2614 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2616 * @deprecated since 1.25; throw the exception directly
2617 * @throws ReadOnlyError
2619 public function readOnlyPage() {
2620 if ( func_num_args() > 0 ) {
2621 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2624 throw new ReadOnlyError
;
2628 * Turn off regular page output and return an error response
2629 * for when rate limiting has triggered.
2631 * @deprecated since 1.25; throw the exception directly
2633 public function rateLimited() {
2634 wfDeprecated( __METHOD__
, '1.25' );
2635 throw new ThrottledError
;
2639 * Show a warning about replica DB lag
2641 * If the lag is higher than $wgSlaveLagCritical seconds,
2642 * then the warning is a bit more obvious. If the lag is
2643 * lower than $wgSlaveLagWarning, then no warning is shown.
2645 * @param int $lag Slave lag
2647 public function showLagWarning( $lag ) {
2648 $config = $this->getConfig();
2649 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2650 $lag = floor( $lag ); // floor to avoid nano seconds to display
2651 $message = $lag < $config->get( 'SlaveLagCritical' )
2654 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2655 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2659 public function showFatalError( $message ) {
2660 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2662 $this->addHTML( $message );
2665 public function showUnexpectedValueError( $name, $val ) {
2666 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2669 public function showFileCopyError( $old, $new ) {
2670 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2673 public function showFileRenameError( $old, $new ) {
2674 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2677 public function showFileDeleteError( $name ) {
2678 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2681 public function showFileNotFoundError( $name ) {
2682 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2686 * Add a "return to" link pointing to a specified title
2688 * @param Title $title Title to link
2689 * @param array $query Query string parameters
2690 * @param string $text Text of the link (input is not escaped)
2691 * @param array $options Options array to pass to Linker
2693 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2694 $linkRenderer = MediaWikiServices
::getInstance()
2695 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2696 $link = $this->msg( 'returnto' )->rawParams(
2697 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2698 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2702 * Add a "return to" link pointing to a specified title,
2703 * or the title indicated in the request, or else the main page
2705 * @param mixed $unused
2706 * @param Title|string $returnto Title or String to return to
2707 * @param string $returntoquery Query string for the return to link
2709 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2710 if ( $returnto == null ) {
2711 $returnto = $this->getRequest()->getText( 'returnto' );
2714 if ( $returntoquery == null ) {
2715 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2718 if ( $returnto === '' ) {
2719 $returnto = Title
::newMainPage();
2722 if ( is_object( $returnto ) ) {
2723 $titleObj = $returnto;
2725 $titleObj = Title
::newFromText( $returnto );
2727 if ( !is_object( $titleObj ) ) {
2728 $titleObj = Title
::newMainPage();
2731 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2734 private function getRlClientContext() {
2735 if ( !$this->rlClientContext
) {
2736 $query = ResourceLoader
::makeLoaderQuery(
2737 [], // modules; not relevant
2738 $this->getLanguage()->getCode(),
2739 $this->getSkin()->getSkinName(),
2740 $this->getUser()->isLoggedIn() ?
$this->getUser()->getName() : null,
2741 null, // version; not relevant
2742 ResourceLoader
::inDebugMode(),
2743 null, // only; not relevant
2744 $this->isPrintable(),
2745 $this->getRequest()->getBool( 'handheld' )
2747 $this->rlClientContext
= new ResourceLoaderContext(
2748 $this->getResourceLoader(),
2749 new FauxRequest( $query )
2752 return $this->rlClientContext
;
2756 * Call this to freeze the module queue and JS config and create a formatter.
2758 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2759 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2760 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2761 * the module filters retroactively. Skins and extension hooks may also add modules until very
2762 * late in the request lifecycle.
2764 * @return ResourceLoaderClientHtml
2766 public function getRlClient() {
2767 if ( !$this->rlClient
) {
2768 $context = $this->getRlClientContext();
2769 $rl = $this->getResourceLoader();
2770 $this->addModules( [
2774 $this->addModuleStyles( [
2779 $this->getSkin()->setupSkinUserCss( $this );
2781 // Prepare exempt modules for buildExemptModules()
2782 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2784 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2786 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2787 // Separate user-specific batch for improved cache-hit ratio.
2788 $userBatch = [ 'user.styles', 'user' ];
2789 $siteBatch = array_diff( $moduleStyles, $userBatch );
2790 $dbr = wfGetDB( DB_REPLICA
);
2791 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $siteBatch );
2792 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $userBatch );
2794 // Filter out modules handled by buildExemptModules()
2795 $moduleStyles = array_filter( $moduleStyles,
2796 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2797 $module = $rl->getModule( $name );
2799 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2800 $exemptStates[$name] = 'ready';
2801 // Special case in buildExemptModules()
2804 $group = $module->getGroup();
2805 if ( isset( $exemptGroups[$group] ) ) {
2806 $exemptStates[$name] = 'ready';
2807 if ( !$module->isKnownEmpty( $context ) ) {
2808 // E.g. Don't output empty <styles>
2809 $exemptGroups[$group][] = $name;
2817 $this->rlExemptStyleModules
= $exemptGroups;
2819 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2820 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2821 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2822 if ( !$isUserModuleFiltered ) {
2823 // Manually handled by getBottomScripts()
2824 $userModule = $rl->getModule( 'user' );
2825 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2828 $this->rlUserModuleState
= $exemptStates['user'] = $userState;
2831 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2832 $rlClient->setConfig( $this->getJSVars() );
2833 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2834 $rlClient->setModuleStyles( $moduleStyles );
2835 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2836 $rlClient->setExemptStates( $exemptStates );
2837 $this->rlClient
= $rlClient;
2839 return $this->rlClient
;
2843 * @param Skin $sk The given Skin
2844 * @param bool $includeStyle Unused
2845 * @return string The doctype, opening "<html>", and head element.
2847 public function headElement( Skin
$sk, $includeStyle = true ) {
2850 $userdir = $this->getLanguage()->getDir();
2851 $sitedir = $wgContLang->getDir();
2854 $pieces[] = Html
::htmlHeader( Sanitizer
::mergeAttributes(
2855 $this->getRlClient()->getDocumentAttributes(),
2856 $sk->getHtmlElementAttributes()
2858 $pieces[] = Html
::openElement( 'head' );
2860 if ( $this->getHTMLTitle() == '' ) {
2861 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2864 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2865 // Add <meta charset="UTF-8">
2866 // This should be before <title> since it defines the charset used by
2867 // text including the text inside <title>.
2868 // The spec recommends defining XHTML5's charset using the XML declaration
2870 // Our XML declaration is output by Html::htmlHeader.
2871 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2872 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2873 $pieces[] = Html
::element( 'meta', [ 'charset' => 'UTF-8' ] );
2876 $pieces[] = Html
::element( 'title', null, $this->getHTMLTitle() );
2877 $pieces[] = $this->getRlClient()->getHeadHtml();
2878 $pieces[] = $this->buildExemptModules();
2879 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2880 $pieces = array_merge( $pieces, array_values( $this->mHeadItems
) );
2881 $pieces[] = Html
::closeElement( 'head' );
2884 $bodyClasses[] = 'mediawiki';
2886 # Classes for LTR/RTL directionality support
2887 $bodyClasses[] = $userdir;
2888 $bodyClasses[] = "sitedir-$sitedir";
2890 $underline = $this->getUser()->getOption( 'underline' );
2891 if ( $underline < 2 ) {
2892 // The following classes can be used here:
2893 // * mw-underline-always
2894 // * mw-underline-never
2895 $bodyClasses[] = 'mw-underline-' . ( $underline ?
'always' : 'never' );
2898 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2899 # A <body> class is probably not the best way to do this . . .
2900 $bodyClasses[] = 'capitalize-all-nouns';
2903 // Parser feature migration class
2904 // The idea is that this will eventually be removed, after the wikitext
2905 // which requires it is cleaned up.
2906 $bodyClasses[] = 'mw-hide-empty-elt';
2908 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2909 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2911 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2914 // While the implode() is not strictly needed, it's used for backwards compatibility
2915 // (this used to be built as a string and hooks likely still expect that).
2916 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2918 // Allow skins and extensions to add body attributes they need
2919 $sk->addToBodyAttributes( $this, $bodyAttrs );
2920 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2922 $pieces[] = Html
::openElement( 'body', $bodyAttrs );
2924 return self
::combineWrappedStrings( $pieces );
2928 * Get a ResourceLoader object associated with this OutputPage
2930 * @return ResourceLoader
2932 public function getResourceLoader() {
2933 if ( is_null( $this->mResourceLoader
) ) {
2934 $this->mResourceLoader
= new ResourceLoader(
2936 LoggerFactory
::getInstance( 'resourceloader' )
2939 return $this->mResourceLoader
;
2943 * Explicily load or embed modules on a page.
2945 * @param array|string $modules One or more module names
2946 * @param string $only ResourceLoaderModule TYPE_ class constant
2947 * @param array $extraQuery [optional] Array with extra query parameters for the request
2948 * @return string|WrappedStringList HTML
2950 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2951 // Apply 'target' and 'origin' filters
2952 $modules = $this->filterModules( (array)$modules, null, $only );
2954 return ResourceLoaderClientHtml
::makeLoad(
2955 $this->getRlClientContext(),
2963 * Combine WrappedString chunks and filter out empty ones
2965 * @param array $chunks
2966 * @return string|WrappedStringList HTML
2968 protected static function combineWrappedStrings( array $chunks ) {
2969 // Filter out empty values
2970 $chunks = array_filter( $chunks, 'strlen' );
2971 return WrappedString
::join( "\n", $chunks );
2974 private function isUserJsPreview() {
2975 return $this->getConfig()->get( 'AllowUserJs' )
2976 && $this->getTitle()
2977 && $this->getTitle()->isJsSubpage()
2978 && $this->userCanPreview();
2981 private function isUserCssPreview() {
2982 return $this->getConfig()->get( 'AllowUserCss' )
2983 && $this->getTitle()
2984 && $this->getTitle()->isCssSubpage()
2985 && $this->userCanPreview();
2989 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2990 * legacy scripts ($this->mScripts), and user JS.
2992 * @return string|WrappedStringList HTML
2994 public function getBottomScripts() {
2996 $chunks[] = $this->getRlClient()->getBodyHtml();
2998 // Legacy non-ResourceLoader scripts
2999 $chunks[] = $this->mScripts
;
3001 // Exempt 'user' module
3002 // - May need excludepages for live preview. (T28283)
3003 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3004 // ensures execution is scheduled after the "site" module.
3005 // - Don't load if module state is already resolved as "ready".
3006 if ( $this->rlUserModuleState
=== 'loading' ) {
3007 if ( $this->isUserJsPreview() ) {
3008 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3009 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3011 $chunks[] = ResourceLoader
::makeInlineScript(
3012 Xml
::encodeJsCall( 'mw.loader.using', [
3016 . Xml
::encodeJsCall( '$.globalEval', [
3017 $this->getRequest()->getText( 'wpTextbox1' )
3023 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3024 // asynchronously and may arrive *after* the inline script here. So the previewed code
3025 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3026 // Similarly, when previewing ./common.js and the user module does arrive first,
3027 // it will arrive without common.js and the inline script runs after.
3028 // Thus running common after the excluded subpage.
3031 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3035 if ( $this->limitReportJSData
) {
3036 $chunks[] = ResourceLoader
::makeInlineScript(
3037 ResourceLoader
::makeConfigSetScript(
3038 [ 'wgPageParseReport' => $this->limitReportJSData
]
3043 return self
::combineWrappedStrings( $chunks );
3047 * Get the javascript config vars to include on this page
3049 * @return array Array of javascript config vars
3052 public function getJsConfigVars() {
3053 return $this->mJsConfigVars
;
3057 * Add one or more variables to be set in mw.config in JavaScript
3059 * @param string|array $keys Key or array of key/value pairs
3060 * @param mixed $value [optional] Value of the configuration variable
3062 public function addJsConfigVars( $keys, $value = null ) {
3063 if ( is_array( $keys ) ) {
3064 foreach ( $keys as $key => $value ) {
3065 $this->mJsConfigVars
[$key] = $value;
3070 $this->mJsConfigVars
[$keys] = $value;
3074 * Get an array containing the variables to be set in mw.config in JavaScript.
3076 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3077 * - in other words, page-independent/site-wide variables (without state).
3078 * You will only be adding bloat to the html page and causing page caches to
3079 * have to be purged on configuration changes.
3082 public function getJSVars() {
3087 $canonicalSpecialPageName = false; # bug 21115
3089 $title = $this->getTitle();
3090 $ns = $title->getNamespace();
3091 $canonicalNamespace = MWNamespace
::exists( $ns )
3092 ? MWNamespace
::getCanonicalName( $ns )
3093 : $title->getNsText();
3095 $sk = $this->getSkin();
3096 // Get the relevant title so that AJAX features can use the correct page name
3097 // when making API requests from certain special pages (bug 34972).
3098 $relevantTitle = $sk->getRelevantTitle();
3099 $relevantUser = $sk->getRelevantUser();
3101 if ( $ns == NS_SPECIAL
) {
3102 list( $canonicalSpecialPageName, /*...*/ ) =
3103 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3104 } elseif ( $this->canUseWikiPage() ) {
3105 $wikiPage = $this->getWikiPage();
3106 $curRevisionId = $wikiPage->getLatest();
3107 $articleId = $wikiPage->getId();
3110 $lang = $title->getPageViewLanguage();
3112 // Pre-process information
3113 $separatorTransTable = $lang->separatorTransformTable();
3114 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3115 $compactSeparatorTransTable = [
3116 implode( "\t", array_keys( $separatorTransTable ) ),
3117 implode( "\t", $separatorTransTable ),
3119 $digitTransTable = $lang->digitTransformTable();
3120 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3121 $compactDigitTransTable = [
3122 implode( "\t", array_keys( $digitTransTable ) ),
3123 implode( "\t", $digitTransTable ),
3126 $user = $this->getUser();
3129 'wgCanonicalNamespace' => $canonicalNamespace,
3130 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3131 'wgNamespaceNumber' => $title->getNamespace(),
3132 'wgPageName' => $title->getPrefixedDBkey(),
3133 'wgTitle' => $title->getText(),
3134 'wgCurRevisionId' => $curRevisionId,
3135 'wgRevisionId' => (int)$this->getRevisionId(),
3136 'wgArticleId' => $articleId,
3137 'wgIsArticle' => $this->isArticle(),
3138 'wgIsRedirect' => $title->isRedirect(),
3139 'wgAction' => Action
::getActionName( $this->getContext() ),
3140 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3141 'wgUserGroups' => $user->getEffectiveGroups(),
3142 'wgCategories' => $this->getCategories(),
3143 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3144 'wgPageContentLanguage' => $lang->getCode(),
3145 'wgPageContentModel' => $title->getContentModel(),
3146 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3147 'wgDigitTransformTable' => $compactDigitTransTable,
3148 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3149 'wgMonthNames' => $lang->getMonthNamesArray(),
3150 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3151 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3152 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3153 'wgRequestId' => WebRequest
::getRequestId(),
3156 if ( $user->isLoggedIn() ) {
3157 $vars['wgUserId'] = $user->getId();
3158 $vars['wgUserEditCount'] = $user->getEditCount();
3159 $userReg = $user->getRegistration();
3160 $vars['wgUserRegistration'] = $userReg ?
wfTimestamp( TS_UNIX
, $userReg ) * 1000 : null;
3161 // Get the revision ID of the oldest new message on the user's talk
3162 // page. This can be used for constructing new message alerts on
3164 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3167 if ( $wgContLang->hasVariants() ) {
3168 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3170 // Same test as SkinTemplate
3171 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3172 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3174 foreach ( $title->getRestrictionTypes() as $type ) {
3175 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3178 if ( $title->isMainPage() ) {
3179 $vars['wgIsMainPage'] = true;
3182 if ( $this->mRedirectedFrom
) {
3183 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3186 if ( $relevantUser ) {
3187 $vars['wgRelevantUserName'] = $relevantUser->getName();
3190 // Allow extensions to add their custom variables to the mw.config map.
3191 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3192 // page-dependant but site-wide (without state).
3193 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3194 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3196 // Merge in variables from addJsConfigVars last
3197 return array_merge( $vars, $this->getJsConfigVars() );
3201 * To make it harder for someone to slip a user a fake
3202 * user-JavaScript or user-CSS preview, a random token
3203 * is associated with the login session. If it's not
3204 * passed back with the preview request, we won't render
3209 public function userCanPreview() {
3210 $request = $this->getRequest();
3212 $request->getVal( 'action' ) !== 'submit' ||
3213 !$request->getCheck( 'wpPreview' ) ||
3214 !$request->wasPosted()
3219 $user = $this->getUser();
3221 if ( !$user->isLoggedIn() ) {
3222 // Anons have predictable edit tokens
3225 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3229 $title = $this->getTitle();
3230 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3233 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3234 // Don't execute another user's CSS or JS on preview (T85855)
3238 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3239 if ( count( $errors ) !== 0 ) {
3247 * @return array Array in format "link name or number => 'link html'".
3249 public function getHeadLinksArray() {
3253 $config = $this->getConfig();
3255 $canonicalUrl = $this->mCanonicalUrl
;
3257 $tags['meta-generator'] = Html
::element( 'meta', [
3258 'name' => 'generator',
3259 'content' => "MediaWiki $wgVersion",
3262 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3263 $tags['meta-referrer'] = Html
::element( 'meta', [
3264 'name' => 'referrer',
3265 'content' => $config->get( 'ReferrerPolicy' )
3269 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3270 if ( $p !== 'index,follow' ) {
3271 // http://www.robotstxt.org/wc/meta-user.html
3272 // Only show if it's different from the default robots policy
3273 $tags['meta-robots'] = Html
::element( 'meta', [
3279 foreach ( $this->mMetatags
as $tag ) {
3280 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3282 $tag[0] = substr( $tag[0], 5 );
3283 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3288 $tagName = "meta-{$tag[0]}";
3289 if ( isset( $tags[$tagName] ) ) {
3290 $tagName .= $tag[1];
3292 $tags[$tagName] = Html
::element( 'meta',
3295 'content' => $tag[1]
3300 foreach ( $this->mLinktags
as $tag ) {
3301 $tags[] = Html
::element( 'link', $tag );
3304 # Universal edit button
3305 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3306 $user = $this->getUser();
3307 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3308 && ( $this->getTitle()->exists() ||
3309 $this->getTitle()->quickUserCan( 'create', $user ) )
3311 // Original UniversalEditButton
3312 $msg = $this->msg( 'edit' )->text();
3313 $tags['universal-edit-button'] = Html
::element( 'link', [
3314 'rel' => 'alternate',
3315 'type' => 'application/x-wiki',
3317 'href' => $this->getTitle()->getEditURL(),
3319 // Alternate edit link
3320 $tags['alternative-edit'] = Html
::element( 'link', [
3323 'href' => $this->getTitle()->getEditURL(),
3328 # Generally the order of the favicon and apple-touch-icon links
3329 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3330 # uses whichever one appears later in the HTML source. Make sure
3331 # apple-touch-icon is specified first to avoid this.
3332 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3333 $tags['apple-touch-icon'] = Html
::element( 'link', [
3334 'rel' => 'apple-touch-icon',
3335 'href' => $config->get( 'AppleTouchIcon' )
3339 if ( $config->get( 'Favicon' ) !== false ) {
3340 $tags['favicon'] = Html
::element( 'link', [
3341 'rel' => 'shortcut icon',
3342 'href' => $config->get( 'Favicon' )
3346 # OpenSearch description link
3347 $tags['opensearch'] = Html
::element( 'link', [
3349 'type' => 'application/opensearchdescription+xml',
3350 'href' => wfScript( 'opensearch_desc' ),
3351 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3354 if ( $config->get( 'EnableAPI' ) ) {
3355 # Real Simple Discovery link, provides auto-discovery information
3356 # for the MediaWiki API (and potentially additional custom API
3357 # support such as WordPress or Twitter-compatible APIs for a
3358 # blogging extension, etc)
3359 $tags['rsd'] = Html
::element( 'link', [
3361 'type' => 'application/rsd+xml',
3362 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3363 // Whether RSD accepts relative or protocol-relative URLs is completely
3364 // undocumented, though.
3365 'href' => wfExpandUrl( wfAppendQuery(
3367 [ 'action' => 'rsd' ] ),
3374 if ( !$config->get( 'DisableLangConversion' ) ) {
3375 $lang = $this->getTitle()->getPageLanguage();
3376 if ( $lang->hasVariants() ) {
3377 $variants = $lang->getVariants();
3378 foreach ( $variants as $variant ) {
3379 $tags["variant-$variant"] = Html
::element( 'link', [
3380 'rel' => 'alternate',
3381 'hreflang' => wfBCP47( $variant ),
3382 'href' => $this->getTitle()->getLocalURL(
3383 [ 'variant' => $variant ] )
3387 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3388 $tags["variant-x-default"] = Html
::element( 'link', [
3389 'rel' => 'alternate',
3390 'hreflang' => 'x-default',
3391 'href' => $this->getTitle()->getLocalURL() ] );
3396 if ( $this->copyrightUrl
!== null ) {
3397 $copyright = $this->copyrightUrl
;
3400 if ( $config->get( 'RightsPage' ) ) {
3401 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3404 $copyright = $copy->getLocalURL();
3408 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3409 $copyright = $config->get( 'RightsUrl' );
3414 $tags['copyright'] = Html
::element( 'link', [
3415 'rel' => 'copyright',
3416 'href' => $copyright ]
3421 if ( $config->get( 'Feed' ) ) {
3424 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3425 # Use the page name for the title. In principle, this could
3426 # lead to issues with having the same name for different feeds
3427 # corresponding to the same page, but we can't avoid that at
3430 $feedLinks[] = $this->feedLink(
3433 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3435 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3440 # Recent changes feed should appear on every page (except recentchanges,
3441 # that would be redundant). Put it after the per-page feed to avoid
3442 # changing existing behavior. It's still available, probably via a
3443 # menu in your browser. Some sites might have a different feed they'd
3444 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3445 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3446 # If so, use it instead.
3447 $sitename = $config->get( 'Sitename' );
3448 if ( $config->get( 'OverrideSiteFeed' ) ) {
3449 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3450 // Note, this->feedLink escapes the url.
3451 $feedLinks[] = $this->feedLink(
3454 $this->msg( "site-{$type}-feed", $sitename )->text()
3457 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3458 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3459 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3460 $feedLinks[] = $this->feedLink(
3462 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3463 # For grep: 'site-rss-feed', 'site-atom-feed'
3464 $this->msg( "site-{$format}-feed", $sitename )->text()
3469 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3470 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3471 # use OutputPage::addFeedLink() instead.
3472 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3474 $tags +
= $feedLinks;
3478 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3479 if ( $canonicalUrl !== false ) {
3480 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3482 if ( $this->isArticleRelated() ) {
3483 // This affects all requests where "setArticleRelated" is true. This is
3484 // typically all requests that show content (query title, curid, oldid, diff),
3485 // and all wikipage actions (edit, delete, purge, info, history etc.).
3486 // It does not apply to File pages and Special pages.
3487 // 'history' and 'info' actions address page metadata rather than the page
3488 // content itself, so they may not be canonicalized to the view page url.
3489 // TODO: this ought to be better encapsulated in the Action class.
3490 $action = Action
::getActionName( $this->getContext() );
3491 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3492 $query = "action={$action}";
3496 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3498 $reqUrl = $this->getRequest()->getRequestURL();
3499 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3503 if ( $canonicalUrl !== false ) {
3504 $tags[] = Html
::element( 'link', [
3505 'rel' => 'canonical',
3506 'href' => $canonicalUrl
3514 * @return string HTML tag links to be put in the header.
3515 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3516 * OutputPage::getHeadLinksArray directly.
3518 public function getHeadLinks() {
3519 wfDeprecated( __METHOD__
, '1.24' );
3520 return implode( "\n", $this->getHeadLinksArray() );
3524 * Generate a "<link rel/>" for a feed.
3526 * @param string $type Feed type
3527 * @param string $url URL to the feed
3528 * @param string $text Value of the "title" attribute
3529 * @return string HTML fragment
3531 private function feedLink( $type, $url, $text ) {
3532 return Html
::element( 'link', [
3533 'rel' => 'alternate',
3534 'type' => "application/$type+xml",
3541 * Add a local or specified stylesheet, with the given media options.
3542 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3544 * @param string $style URL to the file
3545 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3546 * @param string $condition For IE conditional comments, specifying an IE version
3547 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3549 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3552 $options['media'] = $media;
3555 $options['condition'] = $condition;
3558 $options['dir'] = $dir;
3560 $this->styles
[$style] = $options;
3564 * Adds inline CSS styles
3565 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3567 * @param mixed $style_css Inline CSS
3568 * @param string $flip Set to 'flip' to flip the CSS if needed
3570 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3571 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3572 # If wanted, and the interface is right-to-left, flip the CSS
3573 $style_css = CSSJanus
::transform( $style_css, true, false );
3575 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3579 * Build exempt modules and legacy non-ResourceLoader styles.
3581 * @return string|WrappedStringList HTML
3583 protected function buildExemptModules() {
3587 // Things that go after the ResourceLoaderDynamicStyles marker
3590 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3591 if ( $this->isUserCssPreview() ) {
3592 $append[] = $this->makeResourceLoaderLink(
3594 ResourceLoaderModule
::TYPE_STYLES
,
3595 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3598 // Load the previewed CSS. Janus it if needed.
3599 // User-supplied CSS is assumed to in the wiki's content language.
3600 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3601 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3602 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3604 $append[] = Html
::inlineStyle( $previewedCSS );
3607 // We want site, private and user styles to override dynamically added styles from
3608 // general modules, but we want dynamically added styles to override statically added
3609 // style modules. So the order has to be:
3610 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3611 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3612 // - ResourceLoaderDynamicStyles marker
3613 // - site/private/user styles
3615 // Add legacy styles added through addStyle()/addInlineStyle() here
3616 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3618 $chunks[] = Html
::element(
3620 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3623 foreach ( $this->rlExemptStyleModules
as $group => $moduleNames ) {
3624 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3625 ResourceLoaderModule
::TYPE_STYLES
3629 return self
::combineWrappedStrings( array_merge( $chunks, $append ) );
3635 public function buildCssLinksArray() {
3638 // Add any extension CSS
3639 foreach ( $this->mExtStyles
as $url ) {
3640 $this->addStyle( $url );
3642 $this->mExtStyles
= [];
3644 foreach ( $this->styles
as $file => $options ) {
3645 $link = $this->styleLink( $file, $options );
3647 $links[$file] = $link;
3654 * Generate \<link\> tags for stylesheets
3656 * @param string $style URL to the file
3657 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3658 * @return string HTML fragment
3660 protected function styleLink( $style, array $options ) {
3661 if ( isset( $options['dir'] ) ) {
3662 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3667 if ( isset( $options['media'] ) ) {
3668 $media = self
::transformCssMedia( $options['media'] );
3669 if ( is_null( $media ) ) {
3676 if ( substr( $style, 0, 1 ) == '/' ||
3677 substr( $style, 0, 5 ) == 'http:' ||
3678 substr( $style, 0, 6 ) == 'https:' ) {
3681 $config = $this->getConfig();
3682 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3683 $config->get( 'StyleVersion' );
3686 $link = Html
::linkedStyle( $url, $media );
3688 if ( isset( $options['condition'] ) ) {
3689 $condition = htmlspecialchars( $options['condition'] );
3690 $link = "<!--[if $condition]>$link<![endif]-->";
3696 * Transform path to web-accessible static resource.
3698 * This is used to add a validation hash as query string.
3699 * This aids various behaviors:
3701 * - Put long Cache-Control max-age headers on responses for improved
3702 * cache performance.
3703 * - Get the correct version of a file as expected by the current page.
3704 * - Instantly get the updated version of a file after deployment.
3706 * Avoid using this for urls included in HTML as otherwise clients may get different
3707 * versions of a resource when navigating the site depending on when the page was cached.
3708 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3709 * an external stylesheet).
3712 * @param Config $config
3713 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3714 * @return string URL
3716 public static function transformResourcePath( Config
$config, $path ) {
3720 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3721 if ( $remotePathPrefix === '' ) {
3722 // The configured base path is required to be empty string for
3723 // wikis in the domain root
3726 $remotePath = $remotePathPrefix;
3728 if ( strpos( $path, $remotePath ) !== 0 ||
substr( $path, 0, 2 ) === '//' ) {
3729 // - Path is outside wgResourceBasePath, ignore.
3730 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3733 // For files in resources, extensions/ or skins/, ResourceBasePath is preferred here.
3734 // For other misc files in $IP, we'll fallback to that as well. There is, however, a fourth
3735 // supported dir/path pair in the configuration (wgUploadDirectory, wgUploadPath)
3736 // which is not expected to be in wgResourceBasePath on CDNs. (T155146)
3737 $uploadPath = $config->get( 'UploadPath' );
3738 if ( strpos( $path, $uploadPath ) === 0 ) {
3739 $localDir = $config->get( 'UploadDirectory' );
3740 $remotePathPrefix = $remotePath = $uploadPath;
3743 $path = RelPath\
getRelativePath( $path, $remotePath );
3744 return self
::transformFilePath( $remotePathPrefix, $localDir, $path );
3748 * Utility method for transformResourceFilePath().
3750 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3753 * @param string $remotePath URL path prefix that points to $localPath
3754 * @param string $localPath File directory exposed at $remotePath
3755 * @param string $file Path to target file relative to $localPath
3756 * @return string URL
3758 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3759 $hash = md5_file( "$localPath/$file" );
3760 if ( $hash === false ) {
3761 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3764 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3768 * Transform "media" attribute based on request parameters
3770 * @param string $media Current value of the "media" attribute
3771 * @return string Modified value of the "media" attribute, or null to skip
3774 public static function transformCssMedia( $media ) {
3777 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3778 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3780 // Switch in on-screen display for media testing
3782 'printable' => 'print',
3783 'handheld' => 'handheld',
3785 foreach ( $switches as $switch => $targetMedia ) {
3786 if ( $wgRequest->getBool( $switch ) ) {
3787 if ( $media == $targetMedia ) {
3789 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3790 /* This regex will not attempt to understand a comma-separated media_query_list
3792 * Example supported values for $media:
3793 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3794 * Example NOT supported value for $media:
3795 * '3d-glasses, screen, print and resolution > 90dpi'
3797 * If it's a print request, we never want any kind of screen stylesheets
3798 * If it's a handheld request (currently the only other choice with a switch),
3799 * we don't want simple 'screen' but we might want screen queries that
3800 * have a max-width or something, so we'll pass all others on and let the
3801 * client do the query.
3803 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3814 * Add a wikitext-formatted message to the output.
3815 * This is equivalent to:
3817 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3819 public function addWikiMsg( /*...*/ ) {
3820 $args = func_get_args();
3821 $name = array_shift( $args );
3822 $this->addWikiMsgArray( $name, $args );
3826 * Add a wikitext-formatted message to the output.
3827 * Like addWikiMsg() except the parameters are taken as an array
3828 * instead of a variable argument list.
3830 * @param string $name
3831 * @param array $args
3833 public function addWikiMsgArray( $name, $args ) {
3834 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3838 * This function takes a number of message/argument specifications, wraps them in
3839 * some overall structure, and then parses the result and adds it to the output.
3841 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3842 * and so on. The subsequent arguments may be either
3843 * 1) strings, in which case they are message names, or
3844 * 2) arrays, in which case, within each array, the first element is the message
3845 * name, and subsequent elements are the parameters to that message.
3847 * Don't use this for messages that are not in the user's interface language.
3851 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3855 * $wgOut->addWikiText( "<div class='error'>\n"
3856 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3858 * The newline after the opening div is needed in some wikitext. See bug 19226.
3860 * @param string $wrap
3862 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3863 $msgSpecs = func_get_args();
3864 array_shift( $msgSpecs );
3865 $msgSpecs = array_values( $msgSpecs );
3867 foreach ( $msgSpecs as $n => $spec ) {
3868 if ( is_array( $spec ) ) {
3870 $name = array_shift( $args );
3871 if ( isset( $args['options'] ) ) {
3872 unset( $args['options'] );
3874 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3882 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3884 $this->addWikiText( $s );
3888 * Enables/disables TOC, doesn't override __NOTOC__
3892 public function enableTOC( $flag = true ) {
3893 $this->mEnableTOC
= $flag;
3900 public function isTOCEnabled() {
3901 return $this->mEnableTOC
;
3905 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3909 public function enableSectionEditLinks( $flag = true ) {
3910 $this->mEnableSectionEditLinks
= $flag;
3917 public function sectionEditLinksEnabled() {
3918 return $this->mEnableSectionEditLinks
;
3922 * Helper function to setup the PHP implementation of OOUI to use in this request.
3925 * @param String $skinName The Skin name to determine the correct OOUI theme
3926 * @param String $dir Language direction
3928 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3929 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3930 // Make keys (skin names) lowercase for case-insensitive matching.
3931 $themes = array_change_key_case( $themes, CASE_LOWER
);
3932 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
3933 // For example, 'OOUI\MediaWikiTheme'.
3934 $themeClass = "OOUI\\{$theme}Theme";
3935 OOUI\Theme
::setSingleton( new $themeClass() );
3936 OOUI\Element
::setDefaultDir( $dir );
3940 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3941 * MediaWiki and this OutputPage instance.
3945 public function enableOOUI() {
3947 strtolower( $this->getSkin()->getSkinName() ),
3948 $this->getLanguage()->getDir()
3950 $this->addModuleStyles( [
3951 'oojs-ui-core.styles',
3952 'oojs-ui.styles.icons',
3953 'oojs-ui.styles.indicators',
3954 'oojs-ui.styles.textures',
3955 'mediawiki.widgets.styles',