Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / OutputPage.php
blob922960f98afc6814d43fad92c287237ad4978766
1 <?php
2 /**
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
20 * @file
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Session\SessionManager;
26 use WrappedString\WrappedString;
27 use WrappedString\WrappedStringList;
29 /**
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
40 * in November 2010.
42 * @todo document
44 class OutputPage extends ContextSource {
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
48 /** @var array */
49 protected $mLinktags = [];
51 /** @var bool */
52 protected $mCanonicalUrl = false;
54 /**
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
58 protected $mExtStyles = [];
60 /**
61 * @var string Should be private - has getter and setter. Contains
62 * the HTML title */
63 public $mPagetitle = '';
65 /**
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 = '';
74 /**
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;
83 /**
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
87 private $mPrintable = false;
89 /**
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 = [];
95 /** @var string */
96 public $mRedirect = '';
98 /** @var int */
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 = '';
107 /** @var array */
108 protected $mCategoryLinks = [];
110 /** @var array */
111 protected $mCategories = [
112 'hidden' => [],
113 'normal' => [],
116 /** @var array */
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 = [];
142 /** @var array */
143 protected $mModules = [];
145 /** @var array */
146 protected $mModuleScripts = [];
148 /** @var array */
149 protected $mModuleStyles = [];
151 /** @var ResourceLoader */
152 protected $mResourceLoader;
154 /** @var ResourceLoaderClientHtml */
155 private $rlClient;
157 /** @var ResourceLoaderContext */
158 private $rlClientContext;
160 /** @var string */
161 private $rlUserModuleState;
163 /** @var array */
164 private $rlExemptStyleModules;
166 /** @var array */
167 protected $mJsConfigVars = [];
169 /** @var array */
170 protected $mTemplateIds = [];
172 /** @var array */
173 protected $mImageTimeKeys = [];
175 /** @var string */
176 public $mRedirectCode = '';
178 protected $mFeedLinksAppendQuery = null;
180 /** @var array
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;
192 // Parser related.
194 /** @var int */
195 protected $mContainsNewMagic = 0;
198 * lazy initialised, use parserOptions()
199 * @var 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;
216 /** @var bool */
217 protected $mNewSectionLink = false;
219 /** @var bool */
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;
229 /** @var string */
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;
247 /** @var string */
248 private $mRevisionTimestamp = null;
250 /** @var array */
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
271 * of the redirect.
273 * @var 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' );
315 } else {
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
335 * @return string
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.
345 * @since 1.26
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
376 * @since 1.25
377 * @return array
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
397 * @since 1.25
398 * @return array
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.
419 * @param string $url
421 function setCanonicalUrl( $url ) {
422 $this->mCanonicalUrl = $url;
426 * Returns the URL to be used for the <link rel=canonical> if
427 * one is set.
429 * @since 1.25
430 * @return bool|string
432 public function getCanonicalUrl() {
433 return $this->mCanonicalUrl;
437 * Get the value of the "rel" attribute for metadata links
439 * @return string
441 public function getMetadataAttribute() {
442 # note: buggy CC software only reads first "meta" link
443 static $haveMeta = false;
444 if ( $haveMeta ) {
445 return 'alternate meta';
446 } else {
447 $haveMeta = true;
448 return 'meta';
453 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
454 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
455 * if possible.
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
481 * @return array
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
493 * (/foo/bar.js)
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 ) ) {
499 $path = $file;
500 } else {
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
525 * @return array
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 )
537 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) )
539 $filteredModules[] = $val;
542 return $filteredModules;
546 * Get the list of modules to include on this page
548 * @param bool $filter Whether to filter out insufficiently trustworthy modules
549 * @param string|null $position If not null, only return modules with this position
550 * @param string $param
551 * @return array Array of module names
553 public function getModules( $filter = false, $position = null, $param = 'mModules',
554 $type = ResourceLoaderModule::TYPE_COMBINED
556 $modules = array_values( array_unique( $this->$param ) );
557 return $filter
558 ? $this->filterModules( $modules, $position, $type )
559 : $modules;
563 * Add one or more modules recognized by ResourceLoader. Modules added
564 * through this function will be loaded by ResourceLoader when the
565 * page loads.
567 * @param string|array $modules Module name (string) or array of module names
569 public function addModules( $modules ) {
570 $this->mModules = array_merge( $this->mModules, (array)$modules );
574 * Get the list of module JS to include on this page
576 * @param bool $filter
577 * @param string|null $position
578 * @return array Array of module names
580 public function getModuleScripts( $filter = false, $position = null ) {
581 return $this->getModules( $filter, $position, 'mModuleScripts',
582 ResourceLoaderModule::TYPE_SCRIPTS
587 * Add only JS of one or more modules recognized by ResourceLoader. Module
588 * scripts added through this function will be loaded by ResourceLoader when
589 * the page loads.
591 * @param string|array $modules Module name (string) or array of module names
593 public function addModuleScripts( $modules ) {
594 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
598 * Get the list of module CSS to include on this page
600 * @param bool $filter
601 * @param string|null $position
602 * @return array Array of module names
604 public function getModuleStyles( $filter = false, $position = null ) {
605 return $this->getModules( $filter, $position, 'mModuleStyles',
606 ResourceLoaderModule::TYPE_STYLES
611 * Add only CSS of one or more modules recognized by ResourceLoader.
613 * Module styles added through this function will be added using standard link CSS
614 * tags, rather than as a combined Javascript and CSS package. Thus, they will
615 * load when JavaScript is disabled (unless CSS also happens to be disabled).
617 * @param string|array $modules Module name (string) or array of module names
619 public function addModuleStyles( $modules ) {
620 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
624 * @return null|string ResourceLoader target
626 public function getTarget() {
627 return $this->mTarget;
631 * Sets ResourceLoader target for load.php links. If null, will be omitted
633 * @param string|null $target
635 public function setTarget( $target ) {
636 $this->mTarget = $target;
640 * Get an array of head items
642 * @return array
644 function getHeadItemsArray() {
645 return $this->mHeadItems;
649 * Add or replace a head item to the output
651 * Whenever possible, use more specific options like ResourceLoader modules,
652 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
653 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
654 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
655 * This would be your very LAST fallback.
657 * @param string $name Item name
658 * @param string $value Raw HTML
660 public function addHeadItem( $name, $value ) {
661 $this->mHeadItems[$name] = $value;
665 * Add one or more head items to the output
667 * @since 1.28
668 * @param string|string[] $value Raw HTML
670 public function addHeadItems( $values ) {
671 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
675 * Check if the header item $name is already set
677 * @param string $name Item name
678 * @return bool
680 public function hasHeadItem( $name ) {
681 return isset( $this->mHeadItems[$name] );
685 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
686 * @param string $tag
688 public function setETag( $tag ) {
692 * Set whether the output should only contain the body of the article,
693 * without any skin, sidebar, etc.
694 * Used e.g. when calling with "action=render".
696 * @param bool $only Whether to output only the body of the article
698 public function setArticleBodyOnly( $only ) {
699 $this->mArticleBodyOnly = $only;
703 * Return whether the output will contain only the body of the article
705 * @return bool
707 public function getArticleBodyOnly() {
708 return $this->mArticleBodyOnly;
712 * Set an additional output property
713 * @since 1.21
715 * @param string $name
716 * @param mixed $value
718 public function setProperty( $name, $value ) {
719 $this->mProperties[$name] = $value;
723 * Get an additional output property
724 * @since 1.21
726 * @param string $name
727 * @return mixed Property value or null if not found
729 public function getProperty( $name ) {
730 if ( isset( $this->mProperties[$name] ) ) {
731 return $this->mProperties[$name];
732 } else {
733 return null;
738 * checkLastModified tells the client to use the client-cached page if
739 * possible. If successful, the OutputPage is disabled so that
740 * any future call to OutputPage->output() have no effect.
742 * Side effect: sets mLastModified for Last-Modified header
744 * @param string $timestamp
746 * @return bool True if cache-ok headers was sent.
748 public function checkLastModified( $timestamp ) {
749 if ( !$timestamp || $timestamp == '19700101000000' ) {
750 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
751 return false;
753 $config = $this->getConfig();
754 if ( !$config->get( 'CachePages' ) ) {
755 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
756 return false;
759 $timestamp = wfTimestamp( TS_MW, $timestamp );
760 $modifiedTimes = [
761 'page' => $timestamp,
762 'user' => $this->getUser()->getTouched(),
763 'epoch' => $config->get( 'CacheEpoch' )
765 if ( $config->get( 'UseSquid' ) ) {
766 // bug 44570: the core page itself may not change, but resources might
767 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
769 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
771 $maxModified = max( $modifiedTimes );
772 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
774 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
775 if ( $clientHeader === false ) {
776 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
777 return false;
780 # IE sends sizes after the date like this:
781 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
782 # this breaks strtotime().
783 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
785 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
786 $clientHeaderTime = strtotime( $clientHeader );
787 MediaWiki\restoreWarnings();
788 if ( !$clientHeaderTime ) {
789 wfDebug( __METHOD__
790 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
791 return false;
793 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
795 # Make debug info
796 $info = '';
797 foreach ( $modifiedTimes as $name => $value ) {
798 if ( $info !== '' ) {
799 $info .= ', ';
801 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
804 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
805 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
806 wfDebug( __METHOD__ . ": effective Last-Modified: " .
807 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
808 if ( $clientHeaderTime < $maxModified ) {
809 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
810 return false;
813 # Not modified
814 # Give a 304 Not Modified response code and disable body output
815 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
816 ini_set( 'zlib.output_compression', 0 );
817 $this->getRequest()->response()->statusHeader( 304 );
818 $this->sendCacheControl();
819 $this->disable();
821 // Don't output a compressed blob when using ob_gzhandler;
822 // it's technically against HTTP spec and seems to confuse
823 // Firefox when the response gets split over two packets.
824 wfClearOutputBuffers();
826 return true;
830 * Override the last modified timestamp
832 * @param string $timestamp New timestamp, in a format readable by
833 * wfTimestamp()
835 public function setLastModified( $timestamp ) {
836 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
840 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
842 * @param string $policy The literal string to output as the contents of
843 * the meta tag. Will be parsed according to the spec and output in
844 * standardized form.
845 * @return null
847 public function setRobotPolicy( $policy ) {
848 $policy = Article::formatRobotPolicy( $policy );
850 if ( isset( $policy['index'] ) ) {
851 $this->setIndexPolicy( $policy['index'] );
853 if ( isset( $policy['follow'] ) ) {
854 $this->setFollowPolicy( $policy['follow'] );
859 * Set the index policy for the page, but leave the follow policy un-
860 * touched.
862 * @param string $policy Either 'index' or 'noindex'.
863 * @return null
865 public function setIndexPolicy( $policy ) {
866 $policy = trim( $policy );
867 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
868 $this->mIndexPolicy = $policy;
873 * Set the follow policy for the page, but leave the index policy un-
874 * touched.
876 * @param string $policy Either 'follow' or 'nofollow'.
877 * @return null
879 public function setFollowPolicy( $policy ) {
880 $policy = trim( $policy );
881 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
882 $this->mFollowPolicy = $policy;
887 * Set the new value of the "action text", this will be added to the
888 * "HTML title", separated from it with " - ".
890 * @param string $text New value of the "action text"
892 public function setPageTitleActionText( $text ) {
893 $this->mPageTitleActionText = $text;
897 * Get the value of the "action text"
899 * @return string
901 public function getPageTitleActionText() {
902 return $this->mPageTitleActionText;
906 * "HTML title" means the contents of "<title>".
907 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
909 * @param string|Message $name
911 public function setHTMLTitle( $name ) {
912 if ( $name instanceof Message ) {
913 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
914 } else {
915 $this->mHTMLtitle = $name;
920 * Return the "HTML title", i.e. the content of the "<title>" tag.
922 * @return string
924 public function getHTMLTitle() {
925 return $this->mHTMLtitle;
929 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
931 * @param Title $t
933 public function setRedirectedFrom( $t ) {
934 $this->mRedirectedFrom = $t;
938 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
939 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
940 * but not bad tags like \<script\>. This function automatically sets
941 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
942 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
943 * good tags like \<i\> will be dropped entirely.
945 * @param string|Message $name
947 public function setPageTitle( $name ) {
948 if ( $name instanceof Message ) {
949 $name = $name->setContext( $this->getContext() )->text();
952 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
953 # but leave "<i>foobar</i>" alone
954 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
955 $this->mPagetitle = $nameWithTags;
957 # change "<i>foo&amp;bar</i>" to "foo&bar"
958 $this->setHTMLTitle(
959 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
960 ->inContentLanguage()
965 * Return the "page title", i.e. the content of the \<h1\> tag.
967 * @return string
969 public function getPageTitle() {
970 return $this->mPagetitle;
974 * Set the Title object to use
976 * @param Title $t
978 public function setTitle( Title $t ) {
979 $this->getContext()->setTitle( $t );
983 * Replace the subtitle with $str
985 * @param string|Message $str New value of the subtitle. String should be safe HTML.
987 public function setSubtitle( $str ) {
988 $this->clearSubtitle();
989 $this->addSubtitle( $str );
993 * Add $str to the subtitle
995 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
997 public function addSubtitle( $str ) {
998 if ( $str instanceof Message ) {
999 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1000 } else {
1001 $this->mSubtitle[] = $str;
1006 * Build message object for a subtitle containing a backlink to a page
1008 * @param Title $title Title to link to
1009 * @param array $query Array of additional parameters to include in the link
1010 * @return Message
1011 * @since 1.25
1013 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1014 if ( $title->isRedirect() ) {
1015 $query['redirect'] = 'no';
1017 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1018 return wfMessage( 'backlinksubtitle' )
1019 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1023 * Add a subtitle containing a backlink to a page
1025 * @param Title $title Title to link to
1026 * @param array $query Array of additional parameters to include in the link
1028 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1029 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1033 * Clear the subtitles
1035 public function clearSubtitle() {
1036 $this->mSubtitle = [];
1040 * Get the subtitle
1042 * @return string
1044 public function getSubtitle() {
1045 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1049 * Set the page as printable, i.e. it'll be displayed with all
1050 * print styles included
1052 public function setPrintable() {
1053 $this->mPrintable = true;
1057 * Return whether the page is "printable"
1059 * @return bool
1061 public function isPrintable() {
1062 return $this->mPrintable;
1066 * Disable output completely, i.e. calling output() will have no effect
1068 public function disable() {
1069 $this->mDoNothing = true;
1073 * Return whether the output will be completely disabled
1075 * @return bool
1077 public function isDisabled() {
1078 return $this->mDoNothing;
1082 * Show an "add new section" link?
1084 * @return bool
1086 public function showNewSectionLink() {
1087 return $this->mNewSectionLink;
1091 * Forcibly hide the new section link?
1093 * @return bool
1095 public function forceHideNewSectionLink() {
1096 return $this->mHideNewSectionLink;
1100 * Add or remove feed links in the page header
1101 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1102 * for the new version
1103 * @see addFeedLink()
1105 * @param bool $show True: add default feeds, false: remove all feeds
1107 public function setSyndicated( $show = true ) {
1108 if ( $show ) {
1109 $this->setFeedAppendQuery( false );
1110 } else {
1111 $this->mFeedLinks = [];
1116 * Add default feeds to the page header
1117 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1118 * for the new version
1119 * @see addFeedLink()
1121 * @param string $val Query to append to feed links or false to output
1122 * default links
1124 public function setFeedAppendQuery( $val ) {
1125 $this->mFeedLinks = [];
1127 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1128 $query = "feed=$type";
1129 if ( is_string( $val ) ) {
1130 $query .= '&' . $val;
1132 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1137 * Add a feed link to the page header
1139 * @param string $format Feed type, should be a key of $wgFeedClasses
1140 * @param string $href URL
1142 public function addFeedLink( $format, $href ) {
1143 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1144 $this->mFeedLinks[$format] = $href;
1149 * Should we output feed links for this page?
1150 * @return bool
1152 public function isSyndicated() {
1153 return count( $this->mFeedLinks ) > 0;
1157 * Return URLs for each supported syndication format for this page.
1158 * @return array Associating format keys with URLs
1160 public function getSyndicationLinks() {
1161 return $this->mFeedLinks;
1165 * Will currently always return null
1167 * @return null
1169 public function getFeedAppendQuery() {
1170 return $this->mFeedLinksAppendQuery;
1174 * Set whether the displayed content is related to the source of the
1175 * corresponding article on the wiki
1176 * Setting true will cause the change "article related" toggle to true
1178 * @param bool $v
1180 public function setArticleFlag( $v ) {
1181 $this->mIsarticle = $v;
1182 if ( $v ) {
1183 $this->mIsArticleRelated = $v;
1188 * Return whether the content displayed page is related to the source of
1189 * the corresponding article on the wiki
1191 * @return bool
1193 public function isArticle() {
1194 return $this->mIsarticle;
1198 * Set whether this page is related an article on the wiki
1199 * Setting false will cause the change of "article flag" toggle to false
1201 * @param bool $v
1203 public function setArticleRelated( $v ) {
1204 $this->mIsArticleRelated = $v;
1205 if ( !$v ) {
1206 $this->mIsarticle = false;
1211 * Return whether this page is related an article on the wiki
1213 * @return bool
1215 public function isArticleRelated() {
1216 return $this->mIsArticleRelated;
1220 * Add new language links
1222 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1223 * (e.g. 'fr:Test page')
1225 public function addLanguageLinks( array $newLinkArray ) {
1226 $this->mLanguageLinks += $newLinkArray;
1230 * Reset the language links and add new language links
1232 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1233 * (e.g. 'fr:Test page')
1235 public function setLanguageLinks( array $newLinkArray ) {
1236 $this->mLanguageLinks = $newLinkArray;
1240 * Get the list of language links
1242 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1244 public function getLanguageLinks() {
1245 return $this->mLanguageLinks;
1249 * Add an array of categories, with names in the keys
1251 * @param array $categories Mapping category name => sort key
1253 public function addCategoryLinks( array $categories ) {
1254 global $wgContLang;
1256 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1257 return;
1260 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1262 # Set all the values to 'normal'.
1263 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1265 # Mark hidden categories
1266 foreach ( $res as $row ) {
1267 if ( isset( $row->pp_value ) ) {
1268 $categories[$row->page_title] = 'hidden';
1272 // Avoid PHP 7.1 warning of passing $this by reference
1273 $outputPage = $this;
1274 # Add the remaining categories to the skin
1275 if ( Hooks::run(
1276 'OutputPageMakeCategoryLinks',
1277 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1279 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1280 foreach ( $categories as $category => $type ) {
1281 // array keys will cast numeric category names to ints, so cast back to string
1282 $category = (string)$category;
1283 $origcategory = $category;
1284 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1285 if ( !$title ) {
1286 continue;
1288 $wgContLang->findVariantLink( $category, $title, true );
1289 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1290 continue;
1292 $text = $wgContLang->convertHtml( $title->getText() );
1293 $this->mCategories[$type][] = $title->getText();
1294 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1300 * @param array $categories
1301 * @return bool|ResultWrapper
1303 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1304 # Add the links to a LinkBatch
1305 $arr = [ NS_CATEGORY => $categories ];
1306 $lb = new LinkBatch;
1307 $lb->setArray( $arr );
1309 # Fetch existence plus the hiddencat property
1310 $dbr = wfGetDB( DB_REPLICA );
1311 $fields = array_merge(
1312 LinkCache::getSelectFields(),
1313 [ 'page_namespace', 'page_title', 'pp_value' ]
1316 $res = $dbr->select( [ 'page', 'page_props' ],
1317 $fields,
1318 $lb->constructSet( 'page', $dbr ),
1319 __METHOD__,
1321 [ 'page_props' => [ 'LEFT JOIN', [
1322 'pp_propname' => 'hiddencat',
1323 'pp_page = page_id'
1324 ] ] ]
1327 # Add the results to the link cache
1328 $lb->addResultToCache( LinkCache::singleton(), $res );
1330 return $res;
1334 * Reset the category links (but not the category list) and add $categories
1336 * @param array $categories Mapping category name => sort key
1338 public function setCategoryLinks( array $categories ) {
1339 $this->mCategoryLinks = [];
1340 $this->addCategoryLinks( $categories );
1344 * Get the list of category links, in a 2-D array with the following format:
1345 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1346 * hidden categories) and $link a HTML fragment with a link to the category
1347 * page
1349 * @return array
1351 public function getCategoryLinks() {
1352 return $this->mCategoryLinks;
1356 * Get the list of category names this page belongs to.
1358 * @param string $type The type of categories which should be returned. Possible values:
1359 * * all: all categories of all types
1360 * * hidden: only the hidden categories
1361 * * normal: all categories, except hidden categories
1362 * @return array Array of strings
1364 public function getCategories( $type = 'all' ) {
1365 if ( $type === 'all' ) {
1366 $allCategories = [];
1367 foreach ( $this->mCategories as $categories ) {
1368 $allCategories = array_merge( $allCategories, $categories );
1370 return $allCategories;
1372 if ( !isset( $this->mCategories[$type] ) ) {
1373 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1375 return $this->mCategories[$type];
1379 * Add an array of indicators, with their identifiers as array
1380 * keys and HTML contents as values.
1382 * In case of duplicate keys, existing values are overwritten.
1384 * @param array $indicators
1385 * @since 1.25
1387 public function setIndicators( array $indicators ) {
1388 $this->mIndicators = $indicators + $this->mIndicators;
1389 // Keep ordered by key
1390 ksort( $this->mIndicators );
1394 * Get the indicators associated with this page.
1396 * The array will be internally ordered by item keys.
1398 * @return array Keys: identifiers, values: HTML contents
1399 * @since 1.25
1401 public function getIndicators() {
1402 return $this->mIndicators;
1406 * Adds help link with an icon via page indicators.
1407 * Link target can be overridden by a local message containing a wikilink:
1408 * the message key is: lowercase action or special page name + '-helppage'.
1409 * @param string $to Target MediaWiki.org page title or encoded URL.
1410 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1411 * @since 1.25
1413 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1414 $this->addModuleStyles( 'mediawiki.helplink' );
1415 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1417 if ( $overrideBaseUrl ) {
1418 $helpUrl = $to;
1419 } else {
1420 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1421 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1424 $link = Html::rawElement(
1425 'a',
1427 'href' => $helpUrl,
1428 'target' => '_blank',
1429 'class' => 'mw-helplink',
1431 $text
1434 $this->setIndicators( [ 'mw-helplink' => $link ] );
1438 * Do not allow scripts which can be modified by wiki users to load on this page;
1439 * only allow scripts bundled with, or generated by, the software.
1440 * Site-wide styles are controlled by a config setting, since they can be
1441 * used to create a custom skin/theme, but not user-specific ones.
1443 * @todo this should be given a more accurate name
1445 public function disallowUserJs() {
1446 $this->reduceAllowedModules(
1447 ResourceLoaderModule::TYPE_SCRIPTS,
1448 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1451 // Site-wide styles are controlled by a config setting, see bug 71621
1452 // for background on why. User styles are never allowed.
1453 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1454 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1455 } else {
1456 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1458 $this->reduceAllowedModules(
1459 ResourceLoaderModule::TYPE_STYLES,
1460 $styleOrigin
1465 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1466 * @see ResourceLoaderModule::$origin
1467 * @param string $type ResourceLoaderModule TYPE_ constant
1468 * @return int ResourceLoaderModule ORIGIN_ class constant
1470 public function getAllowedModules( $type ) {
1471 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1472 return min( array_values( $this->mAllowedModules ) );
1473 } else {
1474 return isset( $this->mAllowedModules[$type] )
1475 ? $this->mAllowedModules[$type]
1476 : ResourceLoaderModule::ORIGIN_ALL;
1481 * Limit the highest level of CSS/JS untrustworthiness allowed.
1483 * If passed the same or a higher level than the current level of untrustworthiness set, the
1484 * level will remain unchanged.
1486 * @param string $type
1487 * @param int $level ResourceLoaderModule class constant
1489 public function reduceAllowedModules( $type, $level ) {
1490 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1494 * Prepend $text to the body HTML
1496 * @param string $text HTML
1498 public function prependHTML( $text ) {
1499 $this->mBodytext = $text . $this->mBodytext;
1503 * Append $text to the body HTML
1505 * @param string $text HTML
1507 public function addHTML( $text ) {
1508 $this->mBodytext .= $text;
1512 * Shortcut for adding an Html::element via addHTML.
1514 * @since 1.19
1516 * @param string $element
1517 * @param array $attribs
1518 * @param string $contents
1520 public function addElement( $element, array $attribs = [], $contents = '' ) {
1521 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1525 * Clear the body HTML
1527 public function clearHTML() {
1528 $this->mBodytext = '';
1532 * Get the body HTML
1534 * @return string HTML
1536 public function getHTML() {
1537 return $this->mBodytext;
1541 * Get/set the ParserOptions object to use for wikitext parsing
1543 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1544 * current ParserOption object
1545 * @return ParserOptions
1547 public function parserOptions( $options = null ) {
1548 if ( $options !== null && !empty( $options->isBogus ) ) {
1549 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1550 // been changed somehow, and keep it if so.
1551 $anonPO = ParserOptions::newFromAnon();
1552 $anonPO->setEditSection( false );
1553 if ( !$options->matches( $anonPO ) ) {
1554 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1555 $options->isBogus = false;
1559 if ( !$this->mParserOptions ) {
1560 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1561 // $wgUser isn't unstubbable yet, so don't try to get a
1562 // ParserOptions for it. And don't cache this ParserOptions
1563 // either.
1564 $po = ParserOptions::newFromAnon();
1565 $po->setEditSection( false );
1566 $po->isBogus = true;
1567 if ( $options !== null ) {
1568 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1570 return $po;
1573 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1574 $this->mParserOptions->setEditSection( false );
1577 if ( $options !== null && !empty( $options->isBogus ) ) {
1578 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1579 // thing.
1580 return wfSetVar( $this->mParserOptions, null, true );
1581 } else {
1582 return wfSetVar( $this->mParserOptions, $options );
1587 * Set the revision ID which will be seen by the wiki text parser
1588 * for things such as embedded {{REVISIONID}} variable use.
1590 * @param int|null $revid An positive integer, or null
1591 * @return mixed Previous value
1593 public function setRevisionId( $revid ) {
1594 $val = is_null( $revid ) ? null : intval( $revid );
1595 return wfSetVar( $this->mRevisionId, $val );
1599 * Get the displayed revision ID
1601 * @return int
1603 public function getRevisionId() {
1604 return $this->mRevisionId;
1608 * Set the timestamp of the revision which will be displayed. This is used
1609 * to avoid a extra DB call in Skin::lastModified().
1611 * @param string|null $timestamp
1612 * @return mixed Previous value
1614 public function setRevisionTimestamp( $timestamp ) {
1615 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1619 * Get the timestamp of displayed revision.
1620 * This will be null if not filled by setRevisionTimestamp().
1622 * @return string|null
1624 public function getRevisionTimestamp() {
1625 return $this->mRevisionTimestamp;
1629 * Set the displayed file version
1631 * @param File|bool $file
1632 * @return mixed Previous value
1634 public function setFileVersion( $file ) {
1635 $val = null;
1636 if ( $file instanceof File && $file->exists() ) {
1637 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1639 return wfSetVar( $this->mFileVersion, $val, true );
1643 * Get the displayed file version
1645 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1647 public function getFileVersion() {
1648 return $this->mFileVersion;
1652 * Get the templates used on this page
1654 * @return array (namespace => dbKey => revId)
1655 * @since 1.18
1657 public function getTemplateIds() {
1658 return $this->mTemplateIds;
1662 * Get the files used on this page
1664 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1665 * @since 1.18
1667 public function getFileSearchOptions() {
1668 return $this->mImageTimeKeys;
1672 * Convert wikitext to HTML and add it to the buffer
1673 * Default assumes that the current page title will be used.
1675 * @param string $text
1676 * @param bool $linestart Is this the start of a line?
1677 * @param bool $interface Is this text in the user interface language?
1678 * @throws MWException
1680 public function addWikiText( $text, $linestart = true, $interface = true ) {
1681 $title = $this->getTitle(); // Work around E_STRICT
1682 if ( !$title ) {
1683 throw new MWException( 'Title is null' );
1685 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1689 * Add wikitext with a custom Title object
1691 * @param string $text Wikitext
1692 * @param Title $title
1693 * @param bool $linestart Is this the start of a line?
1695 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1696 $this->addWikiTextTitle( $text, $title, $linestart );
1700 * Add wikitext with a custom Title object and tidy enabled.
1702 * @param string $text Wikitext
1703 * @param Title $title
1704 * @param bool $linestart Is this the start of a line?
1706 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1707 $this->addWikiTextTitle( $text, $title, $linestart, true );
1711 * Add wikitext with tidy enabled
1713 * @param string $text Wikitext
1714 * @param bool $linestart Is this the start of a line?
1716 public function addWikiTextTidy( $text, $linestart = true ) {
1717 $title = $this->getTitle();
1718 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1722 * Add wikitext with a custom Title object
1724 * @param string $text Wikitext
1725 * @param Title $title
1726 * @param bool $linestart Is this the start of a line?
1727 * @param bool $tidy Whether to use tidy
1728 * @param bool $interface Whether it is an interface message
1729 * (for example disables conversion)
1731 public function addWikiTextTitle( $text, Title $title, $linestart,
1732 $tidy = false, $interface = false
1734 global $wgParser;
1736 $popts = $this->parserOptions();
1737 $oldTidy = $popts->setTidy( $tidy );
1738 $popts->setInterfaceMessage( (bool)$interface );
1740 $parserOutput = $wgParser->getFreshParser()->parse(
1741 $text, $title, $popts,
1742 $linestart, true, $this->mRevisionId
1745 $popts->setTidy( $oldTidy );
1747 $this->addParserOutput( $parserOutput );
1751 * Add a ParserOutput object, but without Html.
1753 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1754 * @param ParserOutput $parserOutput
1756 public function addParserOutputNoText( $parserOutput ) {
1757 wfDeprecated( __METHOD__, '1.24' );
1758 $this->addParserOutputMetadata( $parserOutput );
1762 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1763 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1764 * and so on.
1766 * @since 1.24
1767 * @param ParserOutput $parserOutput
1769 public function addParserOutputMetadata( $parserOutput ) {
1770 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1771 $this->addCategoryLinks( $parserOutput->getCategories() );
1772 $this->setIndicators( $parserOutput->getIndicators() );
1773 $this->mNewSectionLink = $parserOutput->getNewSection();
1774 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1776 if ( !$parserOutput->isCacheable() ) {
1777 $this->enableClientCache( false );
1779 $this->mNoGallery = $parserOutput->getNoGallery();
1780 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1781 $this->addModules( $parserOutput->getModules() );
1782 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1783 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1784 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1785 $this->mPreventClickjacking = $this->mPreventClickjacking
1786 || $parserOutput->preventClickjacking();
1788 // Template versioning...
1789 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1790 if ( isset( $this->mTemplateIds[$ns] ) ) {
1791 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1792 } else {
1793 $this->mTemplateIds[$ns] = $dbks;
1796 // File versioning...
1797 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1798 $this->mImageTimeKeys[$dbk] = $data;
1801 // Hooks registered in the object
1802 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1803 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1804 list( $hookName, $data ) = $hookInfo;
1805 if ( isset( $parserOutputHooks[$hookName] ) ) {
1806 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1810 // Enable OOUI if requested via ParserOutput
1811 if ( $parserOutput->getEnableOOUI() ) {
1812 $this->enableOOUI();
1815 // Include parser limit report
1816 if ( !$this->limitReportJSData ) {
1817 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1820 // Link flags are ignored for now, but may in the future be
1821 // used to mark individual language links.
1822 $linkFlags = [];
1823 // Avoid PHP 7.1 warning of passing $this by reference
1824 $outputPage = $this;
1825 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1826 Hooks::run( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1830 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1831 * ParserOutput object, without any other metadata.
1833 * @since 1.24
1834 * @param ParserOutput $parserOutput
1836 public function addParserOutputContent( $parserOutput ) {
1837 $this->addParserOutputText( $parserOutput );
1839 $this->addModules( $parserOutput->getModules() );
1840 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1841 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1843 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1847 * Add the HTML associated with a ParserOutput object, without any metadata.
1849 * @since 1.24
1850 * @param ParserOutput $parserOutput
1852 public function addParserOutputText( $parserOutput ) {
1853 $text = $parserOutput->getText();
1854 // Avoid PHP 7.1 warning of passing $this by reference
1855 $outputPage = $this;
1856 Hooks::run( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1857 $this->addHTML( $text );
1861 * Add everything from a ParserOutput object.
1863 * @param ParserOutput $parserOutput
1865 function addParserOutput( $parserOutput ) {
1866 $this->addParserOutputMetadata( $parserOutput );
1867 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1869 // Touch section edit links only if not previously disabled
1870 if ( $parserOutput->getEditSectionTokens() ) {
1871 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1874 $this->addParserOutputText( $parserOutput );
1878 * Add the output of a QuickTemplate to the output buffer
1880 * @param QuickTemplate $template
1882 public function addTemplate( &$template ) {
1883 $this->addHTML( $template->getHTML() );
1887 * Parse wikitext and return the HTML.
1889 * @param string $text
1890 * @param bool $linestart Is this the start of a line?
1891 * @param bool $interface Use interface language ($wgLang instead of
1892 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1893 * This also disables LanguageConverter.
1894 * @param Language $language Target language object, will override $interface
1895 * @throws MWException
1896 * @return string HTML
1898 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1899 global $wgParser;
1901 if ( is_null( $this->getTitle() ) ) {
1902 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1905 $popts = $this->parserOptions();
1906 if ( $interface ) {
1907 $popts->setInterfaceMessage( true );
1909 if ( $language !== null ) {
1910 $oldLang = $popts->setTargetLanguage( $language );
1913 $parserOutput = $wgParser->getFreshParser()->parse(
1914 $text, $this->getTitle(), $popts,
1915 $linestart, true, $this->mRevisionId
1918 if ( $interface ) {
1919 $popts->setInterfaceMessage( false );
1921 if ( $language !== null ) {
1922 $popts->setTargetLanguage( $oldLang );
1925 return $parserOutput->getText();
1929 * Parse wikitext, strip paragraphs, and return the HTML.
1931 * @param string $text
1932 * @param bool $linestart Is this the start of a line?
1933 * @param bool $interface Use interface language ($wgLang instead of
1934 * $wgContLang) while parsing language sensitive magic
1935 * words like GRAMMAR and PLURAL
1936 * @return string HTML
1938 public function parseInline( $text, $linestart = true, $interface = false ) {
1939 $parsed = $this->parse( $text, $linestart, $interface );
1940 return Parser::stripOuterParagraph( $parsed );
1944 * @param $maxage
1945 * @deprecated since 1.27 Use setCdnMaxage() instead
1947 public function setSquidMaxage( $maxage ) {
1948 $this->setCdnMaxage( $maxage );
1952 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1954 * @param int $maxage Maximum cache time on the CDN, in seconds.
1956 public function setCdnMaxage( $maxage ) {
1957 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1961 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1963 * @param int $maxage Maximum cache time on the CDN, in seconds
1964 * @since 1.27
1966 public function lowerCdnMaxage( $maxage ) {
1967 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1968 $this->setCdnMaxage( $this->mCdnMaxage );
1972 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
1974 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
1975 * the TTL is higher the older the $mtime timestamp is. Essentially, the
1976 * TTL is 90% of the age of the object, subject to the min and max.
1978 * @param string|integer|float|bool|null $mtime Last-Modified timestamp
1979 * @param integer $minTTL Mimimum TTL in seconds [default: 1 minute]
1980 * @param integer $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
1981 * @return integer TTL in seconds
1982 * @since 1.28
1984 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
1985 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
1986 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
1988 if ( $mtime === null || $mtime === false ) {
1989 return $minTTL; // entity does not exist
1992 $age = time() - wfTimestamp( TS_UNIX, $mtime );
1993 $adaptiveTTL = max( .9 * $age, $minTTL );
1994 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
1996 $this->lowerCdnMaxage( (int)$adaptiveTTL );
1998 return $adaptiveTTL;
2002 * Use enableClientCache(false) to force it to send nocache headers
2004 * @param bool $state
2006 * @return bool
2008 public function enableClientCache( $state ) {
2009 return wfSetVar( $this->mEnableClientCache, $state );
2013 * Get the list of cookies that will influence on the cache
2015 * @return array
2017 function getCacheVaryCookies() {
2018 static $cookies;
2019 if ( $cookies === null ) {
2020 $config = $this->getConfig();
2021 $cookies = array_merge(
2022 SessionManager::singleton()->getVaryCookies(),
2024 'forceHTTPS',
2026 $config->get( 'CacheVaryCookies' )
2028 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2030 return $cookies;
2034 * Check if the request has a cache-varying cookie header
2035 * If it does, it's very important that we don't allow public caching
2037 * @return bool
2039 function haveCacheVaryCookies() {
2040 $request = $this->getRequest();
2041 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2042 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2043 wfDebug( __METHOD__ . ": found $cookieName\n" );
2044 return true;
2047 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2048 return false;
2052 * Add an HTTP header that will influence on the cache
2054 * @param string $header Header name
2055 * @param string[]|null $option Options for the Key header. See
2056 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2057 * for the list of valid options.
2059 public function addVaryHeader( $header, array $option = null ) {
2060 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2061 $this->mVaryHeader[$header] = [];
2063 if ( !is_array( $option ) ) {
2064 $option = [];
2066 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2070 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2071 * such as Accept-Encoding or Cookie
2073 * @return string
2075 public function getVaryHeader() {
2076 // If we vary on cookies, let's make sure it's always included here too.
2077 if ( $this->getCacheVaryCookies() ) {
2078 $this->addVaryHeader( 'Cookie' );
2081 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2082 $this->addVaryHeader( $header, $options );
2084 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2088 * Get a complete Key header
2090 * @return string
2092 public function getKeyHeader() {
2093 $cvCookies = $this->getCacheVaryCookies();
2095 $cookiesOption = [];
2096 foreach ( $cvCookies as $cookieName ) {
2097 $cookiesOption[] = 'param=' . $cookieName;
2099 $this->addVaryHeader( 'Cookie', $cookiesOption );
2101 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2102 $this->addVaryHeader( $header, $options );
2105 $headers = [];
2106 foreach ( $this->mVaryHeader as $header => $option ) {
2107 $newheader = $header;
2108 if ( is_array( $option ) && count( $option ) > 0 ) {
2109 $newheader .= ';' . implode( ';', $option );
2111 $headers[] = $newheader;
2113 $key = 'Key: ' . implode( ',', $headers );
2115 return $key;
2119 * T23672: Add Accept-Language to Vary and Key headers
2120 * if there's no 'variant' parameter existed in GET.
2122 * For example:
2123 * /w/index.php?title=Main_page should always be served; but
2124 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2126 function addAcceptLanguage() {
2127 $title = $this->getTitle();
2128 if ( !$title instanceof Title ) {
2129 return;
2132 $lang = $title->getPageLanguage();
2133 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2134 $variants = $lang->getVariants();
2135 $aloption = [];
2136 foreach ( $variants as $variant ) {
2137 if ( $variant === $lang->getCode() ) {
2138 continue;
2139 } else {
2140 $aloption[] = 'substr=' . $variant;
2142 // IE and some other browsers use BCP 47 standards in
2143 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2144 // We should handle these too.
2145 $variantBCP47 = wfBCP47( $variant );
2146 if ( $variantBCP47 !== $variant ) {
2147 $aloption[] = 'substr=' . $variantBCP47;
2151 $this->addVaryHeader( 'Accept-Language', $aloption );
2156 * Set a flag which will cause an X-Frame-Options header appropriate for
2157 * edit pages to be sent. The header value is controlled by
2158 * $wgEditPageFrameOptions.
2160 * This is the default for special pages. If you display a CSRF-protected
2161 * form on an ordinary view page, then you need to call this function.
2163 * @param bool $enable
2165 public function preventClickjacking( $enable = true ) {
2166 $this->mPreventClickjacking = $enable;
2170 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2171 * This can be called from pages which do not contain any CSRF-protected
2172 * HTML form.
2174 public function allowClickjacking() {
2175 $this->mPreventClickjacking = false;
2179 * Get the prevent-clickjacking flag
2181 * @since 1.24
2182 * @return bool
2184 public function getPreventClickjacking() {
2185 return $this->mPreventClickjacking;
2189 * Get the X-Frame-Options header value (without the name part), or false
2190 * if there isn't one. This is used by Skin to determine whether to enable
2191 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2193 * @return string|false
2195 public function getFrameOptions() {
2196 $config = $this->getConfig();
2197 if ( $config->get( 'BreakFrames' ) ) {
2198 return 'DENY';
2199 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2200 return $config->get( 'EditPageFrameOptions' );
2202 return false;
2206 * Send cache control HTTP headers
2208 public function sendCacheControl() {
2209 $response = $this->getRequest()->response();
2210 $config = $this->getConfig();
2212 $this->addVaryHeader( 'Cookie' );
2213 $this->addAcceptLanguage();
2215 # don't serve compressed data to clients who can't handle it
2216 # maintain different caches for logged-in users and non-logged in ones
2217 $response->header( $this->getVaryHeader() );
2219 if ( $config->get( 'UseKeyHeader' ) ) {
2220 $response->header( $this->getKeyHeader() );
2223 if ( $this->mEnableClientCache ) {
2224 if (
2225 $config->get( 'UseSquid' ) &&
2226 !$response->hasCookies() &&
2227 !SessionManager::getGlobalSession()->isPersistent() &&
2228 !$this->isPrintable() &&
2229 $this->mCdnMaxage != 0 &&
2230 !$this->haveCacheVaryCookies()
2232 if ( $config->get( 'UseESI' ) ) {
2233 # We'll purge the proxy cache explicitly, but require end user agents
2234 # to revalidate against the proxy on each visit.
2235 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2236 wfDebug( __METHOD__ .
2237 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2238 # start with a shorter timeout for initial testing
2239 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2240 $response->header(
2241 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2242 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2244 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2245 } else {
2246 # We'll purge the proxy cache for anons explicitly, but require end user agents
2247 # to revalidate against the proxy on each visit.
2248 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2249 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2250 wfDebug( __METHOD__ .
2251 ": local proxy caching; {$this->mLastModified} **", 'private' );
2252 # start with a shorter timeout for initial testing
2253 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2254 $response->header( "Cache-Control: " .
2255 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2257 } else {
2258 # We do want clients to cache if they can, but they *must* check for updates
2259 # on revisiting the page.
2260 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2261 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2262 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2264 if ( $this->mLastModified ) {
2265 $response->header( "Last-Modified: {$this->mLastModified}" );
2267 } else {
2268 wfDebug( __METHOD__ . ": no caching **", 'private' );
2270 # In general, the absence of a last modified header should be enough to prevent
2271 # the client from using its cache. We send a few other things just to make sure.
2272 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2273 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2274 $response->header( 'Pragma: no-cache' );
2279 * Finally, all the text has been munged and accumulated into
2280 * the object, let's actually output it:
2282 * @param bool $return Set to true to get the result as a string rather than sending it
2283 * @return string|null
2284 * @throws Exception
2285 * @throws FatalError
2286 * @throws MWException
2288 public function output( $return = false ) {
2289 global $wgContLang;
2291 if ( $this->mDoNothing ) {
2292 return $return ? '' : null;
2295 $response = $this->getRequest()->response();
2296 $config = $this->getConfig();
2298 if ( $this->mRedirect != '' ) {
2299 # Standards require redirect URLs to be absolute
2300 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2302 $redirect = $this->mRedirect;
2303 $code = $this->mRedirectCode;
2305 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2306 if ( $code == '301' || $code == '303' ) {
2307 if ( !$config->get( 'DebugRedirects' ) ) {
2308 $response->statusHeader( $code );
2310 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2312 if ( $config->get( 'VaryOnXFP' ) ) {
2313 $this->addVaryHeader( 'X-Forwarded-Proto' );
2315 $this->sendCacheControl();
2317 $response->header( "Content-Type: text/html; charset=utf-8" );
2318 if ( $config->get( 'DebugRedirects' ) ) {
2319 $url = htmlspecialchars( $redirect );
2320 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2321 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2322 print "</body>\n</html>\n";
2323 } else {
2324 $response->header( 'Location: ' . $redirect );
2328 return $return ? '' : null;
2329 } elseif ( $this->mStatusCode ) {
2330 $response->statusHeader( $this->mStatusCode );
2333 # Buffer output; final headers may depend on later processing
2334 ob_start();
2336 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2337 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2339 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2340 // jQuery etc. can work correctly.
2341 $response->header( 'X-UA-Compatible: IE=Edge' );
2343 // Prevent framing, if requested
2344 $frameOptions = $this->getFrameOptions();
2345 if ( $frameOptions ) {
2346 $response->header( "X-Frame-Options: $frameOptions" );
2349 if ( $this->mArticleBodyOnly ) {
2350 echo $this->mBodytext;
2351 } else {
2352 $sk = $this->getSkin();
2353 // add skin specific modules
2354 $modules = $sk->getDefaultModules();
2356 // Enforce various default modules for all pages and all skins
2357 $coreModules = [
2358 // Keep this list as small as possible
2359 'site',
2360 'mediawiki.page.startup',
2361 'mediawiki.user',
2364 // Support for high-density display images if enabled
2365 if ( $config->get( 'ResponsiveImages' ) ) {
2366 $coreModules[] = 'mediawiki.hidpi';
2369 $this->addModules( $coreModules );
2370 foreach ( $modules as $group ) {
2371 $this->addModules( $group );
2373 MWDebug::addModules( $this );
2375 // Avoid PHP 7.1 warning of passing $this by reference
2376 $outputPage = $this;
2377 // Hook that allows last minute changes to the output page, e.g.
2378 // adding of CSS or Javascript by extensions.
2379 Hooks::run( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2381 try {
2382 $sk->outputPage();
2383 } catch ( Exception $e ) {
2384 ob_end_clean(); // bug T129657
2385 throw $e;
2389 try {
2390 // This hook allows last minute changes to final overall output by modifying output buffer
2391 Hooks::run( 'AfterFinalPageOutput', [ $this ] );
2392 } catch ( Exception $e ) {
2393 ob_end_clean(); // bug T129657
2394 throw $e;
2397 $this->sendCacheControl();
2399 if ( $return ) {
2400 return ob_get_clean();
2401 } else {
2402 ob_end_flush();
2403 return null;
2408 * Prepare this object to display an error page; disable caching and
2409 * indexing, clear the current text and redirect, set the page's title
2410 * and optionally an custom HTML title (content of the "<title>" tag).
2412 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2413 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2414 * optional, if not passed the "<title>" attribute will be
2415 * based on $pageTitle
2417 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2418 $this->setPageTitle( $pageTitle );
2419 if ( $htmlTitle !== false ) {
2420 $this->setHTMLTitle( $htmlTitle );
2422 $this->setRobotPolicy( 'noindex,nofollow' );
2423 $this->setArticleRelated( false );
2424 $this->enableClientCache( false );
2425 $this->mRedirect = '';
2426 $this->clearSubtitle();
2427 $this->clearHTML();
2431 * Output a standard error page
2433 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2434 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2435 * showErrorPage( 'titlemsg', $messageObject );
2436 * showErrorPage( $titleMessageObject, $messageObject );
2438 * @param string|Message $title Message key (string) for page title, or a Message object
2439 * @param string|Message $msg Message key (string) for page text, or a Message object
2440 * @param array $params Message parameters; ignored if $msg is a Message object
2442 public function showErrorPage( $title, $msg, $params = [] ) {
2443 if ( !$title instanceof Message ) {
2444 $title = $this->msg( $title );
2447 $this->prepareErrorPage( $title );
2449 if ( $msg instanceof Message ) {
2450 if ( $params !== [] ) {
2451 trigger_error( 'Argument ignored: $params. The message parameters argument '
2452 . 'is discarded when the $msg argument is a Message object instead of '
2453 . 'a string.', E_USER_NOTICE );
2455 $this->addHTML( $msg->parseAsBlock() );
2456 } else {
2457 $this->addWikiMsgArray( $msg, $params );
2460 $this->returnToMain();
2464 * Output a standard permission error page
2466 * @param array $errors Error message keys or [key, param...] arrays
2467 * @param string $action Action that was denied or null if unknown
2469 public function showPermissionsErrorPage( array $errors, $action = null ) {
2470 foreach ( $errors as $key => $error ) {
2471 $errors[$key] = (array)$error;
2474 // For some action (read, edit, create and upload), display a "login to do this action"
2475 // error if all of the following conditions are met:
2476 // 1. the user is not logged in
2477 // 2. the only error is insufficient permissions (i.e. no block or something else)
2478 // 3. the error can be avoided simply by logging in
2479 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2480 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2481 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2482 && ( User::groupHasPermission( 'user', $action )
2483 || User::groupHasPermission( 'autoconfirmed', $action ) )
2485 $displayReturnto = null;
2487 # Due to bug 32276, if a user does not have read permissions,
2488 # $this->getTitle() will just give Special:Badtitle, which is
2489 # not especially useful as a returnto parameter. Use the title
2490 # from the request instead, if there was one.
2491 $request = $this->getRequest();
2492 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2493 if ( $action == 'edit' ) {
2494 $msg = 'whitelistedittext';
2495 $displayReturnto = $returnto;
2496 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2497 $msg = 'nocreatetext';
2498 } elseif ( $action == 'upload' ) {
2499 $msg = 'uploadnologintext';
2500 } else { # Read
2501 $msg = 'loginreqpagetext';
2502 $displayReturnto = Title::newMainPage();
2505 $query = [];
2507 if ( $returnto ) {
2508 $query['returnto'] = $returnto->getPrefixedText();
2510 if ( !$request->wasPosted() ) {
2511 $returntoquery = $request->getValues();
2512 unset( $returntoquery['title'] );
2513 unset( $returntoquery['returnto'] );
2514 unset( $returntoquery['returntoquery'] );
2515 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2518 $loginLink = Linker::linkKnown(
2519 SpecialPage::getTitleFor( 'Userlogin' ),
2520 $this->msg( 'loginreqlink' )->escaped(),
2522 $query
2525 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2526 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2528 # Don't return to a page the user can't read otherwise
2529 # we'll end up in a pointless loop
2530 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2531 $this->returnToMain( null, $displayReturnto );
2533 } else {
2534 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2535 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2540 * Display an error page indicating that a given version of MediaWiki is
2541 * required to use it
2543 * @param mixed $version The version of MediaWiki needed to use the page
2545 public function versionRequired( $version ) {
2546 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2548 $this->addWikiMsg( 'versionrequiredtext', $version );
2549 $this->returnToMain();
2553 * Format a list of error messages
2555 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2556 * @param string $action Action that was denied or null if unknown
2557 * @return string The wikitext error-messages, formatted into a list.
2559 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2560 if ( $action == null ) {
2561 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2562 } else {
2563 $action_desc = $this->msg( "action-$action" )->plain();
2564 $text = $this->msg(
2565 'permissionserrorstext-withaction',
2566 count( $errors ),
2567 $action_desc
2568 )->plain() . "\n\n";
2571 if ( count( $errors ) > 1 ) {
2572 $text .= '<ul class="permissions-errors">' . "\n";
2574 foreach ( $errors as $error ) {
2575 $text .= '<li>';
2576 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2577 $text .= "</li>\n";
2579 $text .= '</ul>';
2580 } else {
2581 $text .= "<div class=\"permissions-errors\">\n" .
2582 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2583 "\n</div>";
2586 return $text;
2590 * Display a page stating that the Wiki is in read-only mode.
2591 * Should only be called after wfReadOnly() has returned true.
2593 * Historically, this function was used to show the source of the page that the user
2594 * was trying to edit and _also_ permissions error messages. The relevant code was
2595 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2597 * @deprecated since 1.25; throw the exception directly
2598 * @throws ReadOnlyError
2600 public function readOnlyPage() {
2601 if ( func_num_args() > 0 ) {
2602 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2605 throw new ReadOnlyError;
2609 * Turn off regular page output and return an error response
2610 * for when rate limiting has triggered.
2612 * @deprecated since 1.25; throw the exception directly
2614 public function rateLimited() {
2615 wfDeprecated( __METHOD__, '1.25' );
2616 throw new ThrottledError;
2620 * Show a warning about replica DB lag
2622 * If the lag is higher than $wgSlaveLagCritical seconds,
2623 * then the warning is a bit more obvious. If the lag is
2624 * lower than $wgSlaveLagWarning, then no warning is shown.
2626 * @param int $lag Slave lag
2628 public function showLagWarning( $lag ) {
2629 $config = $this->getConfig();
2630 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2631 $lag = floor( $lag ); // floor to avoid nano seconds to display
2632 $message = $lag < $config->get( 'SlaveLagCritical' )
2633 ? 'lag-warn-normal'
2634 : 'lag-warn-high';
2635 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2636 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2640 public function showFatalError( $message ) {
2641 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2643 $this->addHTML( $message );
2646 public function showUnexpectedValueError( $name, $val ) {
2647 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2650 public function showFileCopyError( $old, $new ) {
2651 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2654 public function showFileRenameError( $old, $new ) {
2655 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2658 public function showFileDeleteError( $name ) {
2659 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2662 public function showFileNotFoundError( $name ) {
2663 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2667 * Add a "return to" link pointing to a specified title
2669 * @param Title $title Title to link
2670 * @param array $query Query string parameters
2671 * @param string $text Text of the link (input is not escaped)
2672 * @param array $options Options array to pass to Linker
2674 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2675 $linkRenderer = MediaWikiServices::getInstance()
2676 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2677 $link = $this->msg( 'returnto' )->rawParams(
2678 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2679 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2683 * Add a "return to" link pointing to a specified title,
2684 * or the title indicated in the request, or else the main page
2686 * @param mixed $unused
2687 * @param Title|string $returnto Title or String to return to
2688 * @param string $returntoquery Query string for the return to link
2690 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2691 if ( $returnto == null ) {
2692 $returnto = $this->getRequest()->getText( 'returnto' );
2695 if ( $returntoquery == null ) {
2696 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2699 if ( $returnto === '' ) {
2700 $returnto = Title::newMainPage();
2703 if ( is_object( $returnto ) ) {
2704 $titleObj = $returnto;
2705 } else {
2706 $titleObj = Title::newFromText( $returnto );
2708 if ( !is_object( $titleObj ) ) {
2709 $titleObj = Title::newMainPage();
2712 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2715 private function getRlClientContext() {
2716 if ( !$this->rlClientContext ) {
2717 $query = ResourceLoader::makeLoaderQuery(
2718 [], // modules; not relevant
2719 $this->getLanguage()->getCode(),
2720 $this->getSkin()->getSkinName(),
2721 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2722 null, // version; not relevant
2723 ResourceLoader::inDebugMode(),
2724 null, // only; not relevant
2725 $this->isPrintable(),
2726 $this->getRequest()->getBool( 'handheld' )
2728 $this->rlClientContext = new ResourceLoaderContext(
2729 $this->getResourceLoader(),
2730 new FauxRequest( $query )
2733 return $this->rlClientContext;
2737 * Call this to freeze the module queue and JS config and create a formatter.
2739 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2740 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2741 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2742 * the module filters retroactively. Skins and extension hooks may also add modules until very
2743 * late in the request lifecycle.
2745 * @return ResourceLoaderClientHtml
2747 public function getRlClient() {
2748 if ( !$this->rlClient ) {
2749 $context = $this->getRlClientContext();
2750 $rl = $this->getResourceLoader();
2751 $this->addModules( [
2752 'user.options',
2753 'user.tokens',
2754 ] );
2755 $this->addModuleStyles( [
2756 'site.styles',
2757 'noscript',
2758 'user.styles',
2759 ] );
2760 $this->getSkin()->setupSkinUserCss( $this );
2762 // Prepare exempt modules for buildExemptModules()
2763 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2764 $exemptStates = [];
2765 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2767 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2768 // Separate user-specific batch for improved cache-hit ratio.
2769 $userBatch = [ 'user.styles', 'user' ];
2770 $siteBatch = array_diff( $moduleStyles, $userBatch );
2771 $dbr = wfGetDB( DB_REPLICA );
2772 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2773 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2775 // Filter out modules handled by buildExemptModules()
2776 $moduleStyles = array_filter( $moduleStyles,
2777 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2778 $module = $rl->getModule( $name );
2779 if ( $module ) {
2780 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2781 $exemptStates[$name] = 'ready';
2782 // Special case in buildExemptModules()
2783 return false;
2785 $group = $module->getGroup();
2786 if ( isset( $exemptGroups[$group] ) ) {
2787 $exemptStates[$name] = 'ready';
2788 if ( !$module->isKnownEmpty( $context ) ) {
2789 // E.g. Don't output empty <styles>
2790 $exemptGroups[$group][] = $name;
2792 return false;
2795 return true;
2798 $this->rlExemptStyleModules = $exemptGroups;
2800 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2801 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2802 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2803 if ( !$isUserModuleFiltered ) {
2804 // Manually handled by getBottomScripts()
2805 $userModule = $rl->getModule( 'user' );
2806 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2807 ? 'ready'
2808 : 'loading';
2809 $this->rlUserModuleState = $exemptStates['user'] = $userState;
2812 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2813 $rlClient->setConfig( $this->getJSVars() );
2814 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2815 $rlClient->setModuleStyles( $moduleStyles );
2816 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2817 $rlClient->setExemptStates( $exemptStates );
2818 $this->rlClient = $rlClient;
2820 return $this->rlClient;
2824 * @param Skin $sk The given Skin
2825 * @param bool $includeStyle Unused
2826 * @return string The doctype, opening "<html>", and head element.
2828 public function headElement( Skin $sk, $includeStyle = true ) {
2829 global $wgContLang;
2831 $userdir = $this->getLanguage()->getDir();
2832 $sitedir = $wgContLang->getDir();
2834 $pieces = [];
2835 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2836 $this->getRlClient()->getDocumentAttributes(),
2837 $sk->getHtmlElementAttributes()
2838 ) );
2839 $pieces[] = Html::openElement( 'head' );
2841 if ( $this->getHTMLTitle() == '' ) {
2842 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2845 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2846 // Add <meta charset="UTF-8">
2847 // This should be before <title> since it defines the charset used by
2848 // text including the text inside <title>.
2849 // The spec recommends defining XHTML5's charset using the XML declaration
2850 // instead of meta.
2851 // Our XML declaration is output by Html::htmlHeader.
2852 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2853 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2854 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2857 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2858 $pieces[] = $this->getRlClient()->getHeadHtml();
2859 $pieces[] = $this->buildExemptModules();
2860 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2861 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2862 $pieces[] = Html::closeElement( 'head' );
2864 $bodyClasses = [];
2865 $bodyClasses[] = 'mediawiki';
2867 # Classes for LTR/RTL directionality support
2868 $bodyClasses[] = $userdir;
2869 $bodyClasses[] = "sitedir-$sitedir";
2871 $underline = $this->getUser()->getOption( 'underline' );
2872 if ( $underline < 2 ) {
2873 // The following classes can be used here:
2874 // * mw-underline-always
2875 // * mw-underline-never
2876 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2879 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2880 # A <body> class is probably not the best way to do this . . .
2881 $bodyClasses[] = 'capitalize-all-nouns';
2884 // Parser feature migration class
2885 // The idea is that this will eventually be removed, after the wikitext
2886 // which requires it is cleaned up.
2887 $bodyClasses[] = 'mw-hide-empty-elt';
2889 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2890 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2891 $bodyClasses[] =
2892 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2894 $bodyAttrs = [];
2895 // While the implode() is not strictly needed, it's used for backwards compatibility
2896 // (this used to be built as a string and hooks likely still expect that).
2897 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2899 // Allow skins and extensions to add body attributes they need
2900 $sk->addToBodyAttributes( $this, $bodyAttrs );
2901 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2903 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2905 return self::combineWrappedStrings( $pieces );
2909 * Get a ResourceLoader object associated with this OutputPage
2911 * @return ResourceLoader
2913 public function getResourceLoader() {
2914 if ( is_null( $this->mResourceLoader ) ) {
2915 $this->mResourceLoader = new ResourceLoader(
2916 $this->getConfig(),
2917 LoggerFactory::getInstance( 'resourceloader' )
2920 return $this->mResourceLoader;
2924 * Explicily load or embed modules on a page.
2926 * @param array|string $modules One or more module names
2927 * @param string $only ResourceLoaderModule TYPE_ class constant
2928 * @param array $extraQuery [optional] Array with extra query parameters for the request
2929 * @return string|WrappedStringList HTML
2931 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2932 // Apply 'target' and 'origin' filters
2933 $modules = $this->filterModules( (array)$modules, null, $only );
2935 return ResourceLoaderClientHtml::makeLoad(
2936 $this->getRlClientContext(),
2937 $modules,
2938 $only,
2939 $extraQuery
2944 * Combine WrappedString chunks and filter out empty ones
2946 * @param array $chunks
2947 * @return string|WrappedStringList HTML
2949 protected static function combineWrappedStrings( array $chunks ) {
2950 // Filter out empty values
2951 $chunks = array_filter( $chunks, 'strlen' );
2952 return WrappedString::join( "\n", $chunks );
2955 private function isUserJsPreview() {
2956 return $this->getConfig()->get( 'AllowUserJs' )
2957 && $this->getTitle()
2958 && $this->getTitle()->isJsSubpage()
2959 && $this->userCanPreview();
2962 private function isUserCssPreview() {
2963 return $this->getConfig()->get( 'AllowUserCss' )
2964 && $this->getTitle()
2965 && $this->getTitle()->isCssSubpage()
2966 && $this->userCanPreview();
2970 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
2971 * legacy scripts ($this->mScripts), and user JS.
2973 * @return string|WrappedStringList HTML
2975 public function getBottomScripts() {
2976 $chunks = [];
2977 $chunks[] = $this->getRlClient()->getBodyHtml();
2979 // Legacy non-ResourceLoader scripts
2980 $chunks[] = $this->mScripts;
2982 // Exempt 'user' module
2983 // - May need excludepages for live preview. (T28283)
2984 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
2985 // ensures execution is scheduled after the "site" module.
2986 // - Don't load if module state is already resolved as "ready".
2987 if ( $this->rlUserModuleState === 'loading' ) {
2988 if ( $this->isUserJsPreview() ) {
2989 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
2990 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
2992 $chunks[] = ResourceLoader::makeInlineScript(
2993 Xml::encodeJsCall( 'mw.loader.using', [
2994 [ 'user', 'site' ],
2995 new XmlJsCode(
2996 'function () {'
2997 . Xml::encodeJsCall( '$.globalEval', [
2998 $this->getRequest()->getText( 'wpTextbox1' )
3000 . '}'
3004 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3005 // asynchronously and may arrive *after* the inline script here. So the previewed code
3006 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3007 // Similarly, when previewing ./common.js and the user module does arrive first,
3008 // it will arrive without common.js and the inline script runs after.
3009 // Thus running common after the excluded subpage.
3010 } else {
3011 // Load normally
3012 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3016 if ( $this->limitReportJSData ) {
3017 $chunks[] = ResourceLoader::makeInlineScript(
3018 ResourceLoader::makeConfigSetScript(
3019 [ 'wgPageParseReport' => $this->limitReportJSData ]
3024 return self::combineWrappedStrings( $chunks );
3028 * Get the javascript config vars to include on this page
3030 * @return array Array of javascript config vars
3031 * @since 1.23
3033 public function getJsConfigVars() {
3034 return $this->mJsConfigVars;
3038 * Add one or more variables to be set in mw.config in JavaScript
3040 * @param string|array $keys Key or array of key/value pairs
3041 * @param mixed $value [optional] Value of the configuration variable
3043 public function addJsConfigVars( $keys, $value = null ) {
3044 if ( is_array( $keys ) ) {
3045 foreach ( $keys as $key => $value ) {
3046 $this->mJsConfigVars[$key] = $value;
3048 return;
3051 $this->mJsConfigVars[$keys] = $value;
3055 * Get an array containing the variables to be set in mw.config in JavaScript.
3057 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3058 * - in other words, page-independent/site-wide variables (without state).
3059 * You will only be adding bloat to the html page and causing page caches to
3060 * have to be purged on configuration changes.
3061 * @return array
3063 public function getJSVars() {
3064 global $wgContLang;
3066 $curRevisionId = 0;
3067 $articleId = 0;
3068 $canonicalSpecialPageName = false; # bug 21115
3070 $title = $this->getTitle();
3071 $ns = $title->getNamespace();
3072 $canonicalNamespace = MWNamespace::exists( $ns )
3073 ? MWNamespace::getCanonicalName( $ns )
3074 : $title->getNsText();
3076 $sk = $this->getSkin();
3077 // Get the relevant title so that AJAX features can use the correct page name
3078 // when making API requests from certain special pages (bug 34972).
3079 $relevantTitle = $sk->getRelevantTitle();
3080 $relevantUser = $sk->getRelevantUser();
3082 if ( $ns == NS_SPECIAL ) {
3083 list( $canonicalSpecialPageName, /*...*/ ) =
3084 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3085 } elseif ( $this->canUseWikiPage() ) {
3086 $wikiPage = $this->getWikiPage();
3087 $curRevisionId = $wikiPage->getLatest();
3088 $articleId = $wikiPage->getId();
3091 $lang = $title->getPageViewLanguage();
3093 // Pre-process information
3094 $separatorTransTable = $lang->separatorTransformTable();
3095 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3096 $compactSeparatorTransTable = [
3097 implode( "\t", array_keys( $separatorTransTable ) ),
3098 implode( "\t", $separatorTransTable ),
3100 $digitTransTable = $lang->digitTransformTable();
3101 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3102 $compactDigitTransTable = [
3103 implode( "\t", array_keys( $digitTransTable ) ),
3104 implode( "\t", $digitTransTable ),
3107 $user = $this->getUser();
3109 $vars = [
3110 'wgCanonicalNamespace' => $canonicalNamespace,
3111 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3112 'wgNamespaceNumber' => $title->getNamespace(),
3113 'wgPageName' => $title->getPrefixedDBkey(),
3114 'wgTitle' => $title->getText(),
3115 'wgCurRevisionId' => $curRevisionId,
3116 'wgRevisionId' => (int)$this->getRevisionId(),
3117 'wgArticleId' => $articleId,
3118 'wgIsArticle' => $this->isArticle(),
3119 'wgIsRedirect' => $title->isRedirect(),
3120 'wgAction' => Action::getActionName( $this->getContext() ),
3121 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3122 'wgUserGroups' => $user->getEffectiveGroups(),
3123 'wgCategories' => $this->getCategories(),
3124 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3125 'wgPageContentLanguage' => $lang->getCode(),
3126 'wgPageContentModel' => $title->getContentModel(),
3127 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3128 'wgDigitTransformTable' => $compactDigitTransTable,
3129 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3130 'wgMonthNames' => $lang->getMonthNamesArray(),
3131 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3132 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3133 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3134 'wgRequestId' => WebRequest::getRequestId(),
3137 if ( $user->isLoggedIn() ) {
3138 $vars['wgUserId'] = $user->getId();
3139 $vars['wgUserEditCount'] = $user->getEditCount();
3140 $userReg = $user->getRegistration();
3141 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3142 // Get the revision ID of the oldest new message on the user's talk
3143 // page. This can be used for constructing new message alerts on
3144 // the client side.
3145 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3148 if ( $wgContLang->hasVariants() ) {
3149 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3151 // Same test as SkinTemplate
3152 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3153 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3155 foreach ( $title->getRestrictionTypes() as $type ) {
3156 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3159 if ( $title->isMainPage() ) {
3160 $vars['wgIsMainPage'] = true;
3163 if ( $this->mRedirectedFrom ) {
3164 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3167 if ( $relevantUser ) {
3168 $vars['wgRelevantUserName'] = $relevantUser->getName();
3171 // Allow extensions to add their custom variables to the mw.config map.
3172 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3173 // page-dependant but site-wide (without state).
3174 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3175 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3177 // Merge in variables from addJsConfigVars last
3178 return array_merge( $vars, $this->getJsConfigVars() );
3182 * To make it harder for someone to slip a user a fake
3183 * user-JavaScript or user-CSS preview, a random token
3184 * is associated with the login session. If it's not
3185 * passed back with the preview request, we won't render
3186 * the code.
3188 * @return bool
3190 public function userCanPreview() {
3191 $request = $this->getRequest();
3192 if (
3193 $request->getVal( 'action' ) !== 'submit' ||
3194 !$request->getCheck( 'wpPreview' ) ||
3195 !$request->wasPosted()
3197 return false;
3200 $user = $this->getUser();
3202 if ( !$user->isLoggedIn() ) {
3203 // Anons have predictable edit tokens
3204 return false;
3206 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3207 return false;
3210 $title = $this->getTitle();
3211 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3212 return false;
3214 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3215 // Don't execute another user's CSS or JS on preview (T85855)
3216 return false;
3219 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3220 if ( count( $errors ) !== 0 ) {
3221 return false;
3224 return true;
3228 * @return array Array in format "link name or number => 'link html'".
3230 public function getHeadLinksArray() {
3231 global $wgVersion;
3233 $tags = [];
3234 $config = $this->getConfig();
3236 $canonicalUrl = $this->mCanonicalUrl;
3238 $tags['meta-generator'] = Html::element( 'meta', [
3239 'name' => 'generator',
3240 'content' => "MediaWiki $wgVersion",
3241 ] );
3243 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3244 $tags['meta-referrer'] = Html::element( 'meta', [
3245 'name' => 'referrer',
3246 'content' => $config->get( 'ReferrerPolicy' )
3247 ] );
3250 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3251 if ( $p !== 'index,follow' ) {
3252 // http://www.robotstxt.org/wc/meta-user.html
3253 // Only show if it's different from the default robots policy
3254 $tags['meta-robots'] = Html::element( 'meta', [
3255 'name' => 'robots',
3256 'content' => $p,
3257 ] );
3260 foreach ( $this->mMetatags as $tag ) {
3261 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3262 $a = 'http-equiv';
3263 $tag[0] = substr( $tag[0], 5 );
3264 } else {
3265 $a = 'name';
3267 $tagName = "meta-{$tag[0]}";
3268 if ( isset( $tags[$tagName] ) ) {
3269 $tagName .= $tag[1];
3271 $tags[$tagName] = Html::element( 'meta',
3273 $a => $tag[0],
3274 'content' => $tag[1]
3279 foreach ( $this->mLinktags as $tag ) {
3280 $tags[] = Html::element( 'link', $tag );
3283 # Universal edit button
3284 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3285 $user = $this->getUser();
3286 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3287 && ( $this->getTitle()->exists() ||
3288 $this->getTitle()->quickUserCan( 'create', $user ) )
3290 // Original UniversalEditButton
3291 $msg = $this->msg( 'edit' )->text();
3292 $tags['universal-edit-button'] = Html::element( 'link', [
3293 'rel' => 'alternate',
3294 'type' => 'application/x-wiki',
3295 'title' => $msg,
3296 'href' => $this->getTitle()->getEditURL(),
3297 ] );
3298 // Alternate edit link
3299 $tags['alternative-edit'] = Html::element( 'link', [
3300 'rel' => 'edit',
3301 'title' => $msg,
3302 'href' => $this->getTitle()->getEditURL(),
3303 ] );
3307 # Generally the order of the favicon and apple-touch-icon links
3308 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3309 # uses whichever one appears later in the HTML source. Make sure
3310 # apple-touch-icon is specified first to avoid this.
3311 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3312 $tags['apple-touch-icon'] = Html::element( 'link', [
3313 'rel' => 'apple-touch-icon',
3314 'href' => $config->get( 'AppleTouchIcon' )
3315 ] );
3318 if ( $config->get( 'Favicon' ) !== false ) {
3319 $tags['favicon'] = Html::element( 'link', [
3320 'rel' => 'shortcut icon',
3321 'href' => $config->get( 'Favicon' )
3322 ] );
3325 # OpenSearch description link
3326 $tags['opensearch'] = Html::element( 'link', [
3327 'rel' => 'search',
3328 'type' => 'application/opensearchdescription+xml',
3329 'href' => wfScript( 'opensearch_desc' ),
3330 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3331 ] );
3333 if ( $config->get( 'EnableAPI' ) ) {
3334 # Real Simple Discovery link, provides auto-discovery information
3335 # for the MediaWiki API (and potentially additional custom API
3336 # support such as WordPress or Twitter-compatible APIs for a
3337 # blogging extension, etc)
3338 $tags['rsd'] = Html::element( 'link', [
3339 'rel' => 'EditURI',
3340 'type' => 'application/rsd+xml',
3341 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3342 // Whether RSD accepts relative or protocol-relative URLs is completely
3343 // undocumented, though.
3344 'href' => wfExpandUrl( wfAppendQuery(
3345 wfScript( 'api' ),
3346 [ 'action' => 'rsd' ] ),
3347 PROTO_RELATIVE
3349 ] );
3352 # Language variants
3353 if ( !$config->get( 'DisableLangConversion' ) ) {
3354 $lang = $this->getTitle()->getPageLanguage();
3355 if ( $lang->hasVariants() ) {
3356 $variants = $lang->getVariants();
3357 foreach ( $variants as $variant ) {
3358 $tags["variant-$variant"] = Html::element( 'link', [
3359 'rel' => 'alternate',
3360 'hreflang' => wfBCP47( $variant ),
3361 'href' => $this->getTitle()->getLocalURL(
3362 [ 'variant' => $variant ] )
3366 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3367 $tags["variant-x-default"] = Html::element( 'link', [
3368 'rel' => 'alternate',
3369 'hreflang' => 'x-default',
3370 'href' => $this->getTitle()->getLocalURL() ] );
3374 # Copyright
3375 if ( $this->copyrightUrl !== null ) {
3376 $copyright = $this->copyrightUrl;
3377 } else {
3378 $copyright = '';
3379 if ( $config->get( 'RightsPage' ) ) {
3380 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3382 if ( $copy ) {
3383 $copyright = $copy->getLocalURL();
3387 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3388 $copyright = $config->get( 'RightsUrl' );
3392 if ( $copyright ) {
3393 $tags['copyright'] = Html::element( 'link', [
3394 'rel' => 'copyright',
3395 'href' => $copyright ]
3399 # Feeds
3400 if ( $config->get( 'Feed' ) ) {
3401 $feedLinks = [];
3403 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3404 # Use the page name for the title. In principle, this could
3405 # lead to issues with having the same name for different feeds
3406 # corresponding to the same page, but we can't avoid that at
3407 # this low a level.
3409 $feedLinks[] = $this->feedLink(
3410 $format,
3411 $link,
3412 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3413 $this->msg(
3414 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3415 )->text()
3419 # Recent changes feed should appear on every page (except recentchanges,
3420 # that would be redundant). Put it after the per-page feed to avoid
3421 # changing existing behavior. It's still available, probably via a
3422 # menu in your browser. Some sites might have a different feed they'd
3423 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3424 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3425 # If so, use it instead.
3426 $sitename = $config->get( 'Sitename' );
3427 if ( $config->get( 'OverrideSiteFeed' ) ) {
3428 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3429 // Note, this->feedLink escapes the url.
3430 $feedLinks[] = $this->feedLink(
3431 $type,
3432 $feedUrl,
3433 $this->msg( "site-{$type}-feed", $sitename )->text()
3436 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3437 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3438 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3439 $feedLinks[] = $this->feedLink(
3440 $format,
3441 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3442 # For grep: 'site-rss-feed', 'site-atom-feed'
3443 $this->msg( "site-{$format}-feed", $sitename )->text()
3448 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3449 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3450 # use OutputPage::addFeedLink() instead.
3451 Hooks::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3453 $tags += $feedLinks;
3456 # Canonical URL
3457 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3458 if ( $canonicalUrl !== false ) {
3459 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3460 } else {
3461 if ( $this->isArticleRelated() ) {
3462 // This affects all requests where "setArticleRelated" is true. This is
3463 // typically all requests that show content (query title, curid, oldid, diff),
3464 // and all wikipage actions (edit, delete, purge, info, history etc.).
3465 // It does not apply to File pages and Special pages.
3466 // 'history' and 'info' actions address page metadata rather than the page
3467 // content itself, so they may not be canonicalized to the view page url.
3468 // TODO: this ought to be better encapsulated in the Action class.
3469 $action = Action::getActionName( $this->getContext() );
3470 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3471 $query = "action={$action}";
3472 } else {
3473 $query = '';
3475 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3476 } else {
3477 $reqUrl = $this->getRequest()->getRequestURL();
3478 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3482 if ( $canonicalUrl !== false ) {
3483 $tags[] = Html::element( 'link', [
3484 'rel' => 'canonical',
3485 'href' => $canonicalUrl
3486 ] );
3489 return $tags;
3493 * @return string HTML tag links to be put in the header.
3494 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3495 * OutputPage::getHeadLinksArray directly.
3497 public function getHeadLinks() {
3498 wfDeprecated( __METHOD__, '1.24' );
3499 return implode( "\n", $this->getHeadLinksArray() );
3503 * Generate a "<link rel/>" for a feed.
3505 * @param string $type Feed type
3506 * @param string $url URL to the feed
3507 * @param string $text Value of the "title" attribute
3508 * @return string HTML fragment
3510 private function feedLink( $type, $url, $text ) {
3511 return Html::element( 'link', [
3512 'rel' => 'alternate',
3513 'type' => "application/$type+xml",
3514 'title' => $text,
3515 'href' => $url ]
3520 * Add a local or specified stylesheet, with the given media options.
3521 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3523 * @param string $style URL to the file
3524 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3525 * @param string $condition For IE conditional comments, specifying an IE version
3526 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3528 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3529 $options = [];
3530 if ( $media ) {
3531 $options['media'] = $media;
3533 if ( $condition ) {
3534 $options['condition'] = $condition;
3536 if ( $dir ) {
3537 $options['dir'] = $dir;
3539 $this->styles[$style] = $options;
3543 * Adds inline CSS styles
3544 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3546 * @param mixed $style_css Inline CSS
3547 * @param string $flip Set to 'flip' to flip the CSS if needed
3549 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3550 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3551 # If wanted, and the interface is right-to-left, flip the CSS
3552 $style_css = CSSJanus::transform( $style_css, true, false );
3554 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3558 * Build exempt modules and legacy non-ResourceLoader styles.
3560 * @return string|WrappedStringList HTML
3562 protected function buildExemptModules() {
3563 global $wgContLang;
3565 $chunks = [];
3566 // Things that go after the ResourceLoaderDynamicStyles marker
3567 $append = [];
3569 // Exempt 'user' styles module (may need 'excludepages' for live preview)
3570 if ( $this->isUserCssPreview() ) {
3571 $append[] = $this->makeResourceLoaderLink(
3572 'user.styles',
3573 ResourceLoaderModule::TYPE_STYLES,
3574 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3577 // Load the previewed CSS. Janus it if needed.
3578 // User-supplied CSS is assumed to in the wiki's content language.
3579 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3580 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3581 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3583 $append[] = Html::inlineStyle( $previewedCSS );
3586 // We want site, private and user styles to override dynamically added styles from
3587 // general modules, but we want dynamically added styles to override statically added
3588 // style modules. So the order has to be:
3589 // - page style modules (formatted by ResourceLoaderClientHtml::getHeadHtml())
3590 // - dynamically loaded styles (added by mw.loader before ResourceLoaderDynamicStyles)
3591 // - ResourceLoaderDynamicStyles marker
3592 // - site/private/user styles
3594 // Add legacy styles added through addStyle()/addInlineStyle() here
3595 $chunks[] = implode( '', $this->buildCssLinksArray() ) . $this->mInlineStyles;
3597 $chunks[] = Html::element(
3598 'meta',
3599 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3602 foreach ( $this->rlExemptStyleModules as $group => $moduleNames ) {
3603 $chunks[] = $this->makeResourceLoaderLink( $moduleNames,
3604 ResourceLoaderModule::TYPE_STYLES
3608 return self::combineWrappedStrings( array_merge( $chunks, $append ) );
3612 * @return array
3614 public function buildCssLinksArray() {
3615 $links = [];
3617 // Add any extension CSS
3618 foreach ( $this->mExtStyles as $url ) {
3619 $this->addStyle( $url );
3621 $this->mExtStyles = [];
3623 foreach ( $this->styles as $file => $options ) {
3624 $link = $this->styleLink( $file, $options );
3625 if ( $link ) {
3626 $links[$file] = $link;
3629 return $links;
3633 * Generate \<link\> tags for stylesheets
3635 * @param string $style URL to the file
3636 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3637 * @return string HTML fragment
3639 protected function styleLink( $style, array $options ) {
3640 if ( isset( $options['dir'] ) ) {
3641 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3642 return '';
3646 if ( isset( $options['media'] ) ) {
3647 $media = self::transformCssMedia( $options['media'] );
3648 if ( is_null( $media ) ) {
3649 return '';
3651 } else {
3652 $media = 'all';
3655 if ( substr( $style, 0, 1 ) == '/' ||
3656 substr( $style, 0, 5 ) == 'http:' ||
3657 substr( $style, 0, 6 ) == 'https:' ) {
3658 $url = $style;
3659 } else {
3660 $config = $this->getConfig();
3661 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3662 $config->get( 'StyleVersion' );
3665 $link = Html::linkedStyle( $url, $media );
3667 if ( isset( $options['condition'] ) ) {
3668 $condition = htmlspecialchars( $options['condition'] );
3669 $link = "<!--[if $condition]>$link<![endif]-->";
3671 return $link;
3675 * Transform path to web-accessible static resource.
3677 * This is used to add a validation hash as query string.
3678 * This aids various behaviors:
3680 * - Put long Cache-Control max-age headers on responses for improved
3681 * cache performance.
3682 * - Get the correct version of a file as expected by the current page.
3683 * - Instantly get the updated version of a file after deployment.
3685 * Avoid using this for urls included in HTML as otherwise clients may get different
3686 * versions of a resource when navigating the site depending on when the page was cached.
3687 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3688 * an external stylesheet).
3690 * @since 1.27
3691 * @param Config $config
3692 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3693 * @return string URL
3695 public static function transformResourcePath( Config $config, $path ) {
3696 global $IP;
3697 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3698 if ( $remotePathPrefix === '' ) {
3699 // The configured base path is required to be empty string for
3700 // wikis in the domain root
3701 $remotePath = '/';
3702 } else {
3703 $remotePath = $remotePathPrefix;
3705 if ( strpos( $path, $remotePath ) !== 0 || substr( $path, 0, 2 ) === '//' ) {
3706 // - Path is outside wgResourceBasePath, ignore.
3707 // - Path is protocol-relative. Fixes T155310. Not supported by RelPath lib.
3708 return $path;
3710 $path = RelPath\getRelativePath( $path, $remotePath );
3711 return self::transformFilePath( $remotePathPrefix, $IP, $path );
3715 * Utility method for transformResourceFilePath().
3717 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3719 * @since 1.27
3720 * @param string $remotePath URL path prefix that points to $localPath
3721 * @param string $localPath File directory exposed at $remotePath
3722 * @param string $file Path to target file relative to $localPath
3723 * @return string URL
3725 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3726 $hash = md5_file( "$localPath/$file" );
3727 if ( $hash === false ) {
3728 wfLogWarning( __METHOD__ . ": Failed to hash $localPath/$file" );
3729 $hash = '';
3731 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3735 * Transform "media" attribute based on request parameters
3737 * @param string $media Current value of the "media" attribute
3738 * @return string Modified value of the "media" attribute, or null to skip
3739 * this stylesheet
3741 public static function transformCssMedia( $media ) {
3742 global $wgRequest;
3744 // https://www.w3.org/TR/css3-mediaqueries/#syntax
3745 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3747 // Switch in on-screen display for media testing
3748 $switches = [
3749 'printable' => 'print',
3750 'handheld' => 'handheld',
3752 foreach ( $switches as $switch => $targetMedia ) {
3753 if ( $wgRequest->getBool( $switch ) ) {
3754 if ( $media == $targetMedia ) {
3755 $media = '';
3756 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3757 /* This regex will not attempt to understand a comma-separated media_query_list
3759 * Example supported values for $media:
3760 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3761 * Example NOT supported value for $media:
3762 * '3d-glasses, screen, print and resolution > 90dpi'
3764 * If it's a print request, we never want any kind of screen stylesheets
3765 * If it's a handheld request (currently the only other choice with a switch),
3766 * we don't want simple 'screen' but we might want screen queries that
3767 * have a max-width or something, so we'll pass all others on and let the
3768 * client do the query.
3770 if ( $targetMedia == 'print' || $media == 'screen' ) {
3771 return null;
3777 return $media;
3781 * Add a wikitext-formatted message to the output.
3782 * This is equivalent to:
3784 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3786 public function addWikiMsg( /*...*/ ) {
3787 $args = func_get_args();
3788 $name = array_shift( $args );
3789 $this->addWikiMsgArray( $name, $args );
3793 * Add a wikitext-formatted message to the output.
3794 * Like addWikiMsg() except the parameters are taken as an array
3795 * instead of a variable argument list.
3797 * @param string $name
3798 * @param array $args
3800 public function addWikiMsgArray( $name, $args ) {
3801 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3805 * This function takes a number of message/argument specifications, wraps them in
3806 * some overall structure, and then parses the result and adds it to the output.
3808 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3809 * and so on. The subsequent arguments may be either
3810 * 1) strings, in which case they are message names, or
3811 * 2) arrays, in which case, within each array, the first element is the message
3812 * name, and subsequent elements are the parameters to that message.
3814 * Don't use this for messages that are not in the user's interface language.
3816 * For example:
3818 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3820 * Is equivalent to:
3822 * $wgOut->addWikiText( "<div class='error'>\n"
3823 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3825 * The newline after the opening div is needed in some wikitext. See bug 19226.
3827 * @param string $wrap
3829 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3830 $msgSpecs = func_get_args();
3831 array_shift( $msgSpecs );
3832 $msgSpecs = array_values( $msgSpecs );
3833 $s = $wrap;
3834 foreach ( $msgSpecs as $n => $spec ) {
3835 if ( is_array( $spec ) ) {
3836 $args = $spec;
3837 $name = array_shift( $args );
3838 if ( isset( $args['options'] ) ) {
3839 unset( $args['options'] );
3840 wfDeprecated(
3841 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3842 '1.20'
3845 } else {
3846 $args = [];
3847 $name = $spec;
3849 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3851 $this->addWikiText( $s );
3855 * Enables/disables TOC, doesn't override __NOTOC__
3856 * @param bool $flag
3857 * @since 1.22
3859 public function enableTOC( $flag = true ) {
3860 $this->mEnableTOC = $flag;
3864 * @return bool
3865 * @since 1.22
3867 public function isTOCEnabled() {
3868 return $this->mEnableTOC;
3872 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3873 * @param bool $flag
3874 * @since 1.23
3876 public function enableSectionEditLinks( $flag = true ) {
3877 $this->mEnableSectionEditLinks = $flag;
3881 * @return bool
3882 * @since 1.23
3884 public function sectionEditLinksEnabled() {
3885 return $this->mEnableSectionEditLinks;
3889 * Helper function to setup the PHP implementation of OOUI to use in this request.
3891 * @since 1.26
3892 * @param String $skinName The Skin name to determine the correct OOUI theme
3893 * @param String $dir Language direction
3895 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3896 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
3897 // Make keys (skin names) lowercase for case-insensitive matching.
3898 $themes = array_change_key_case( $themes, CASE_LOWER );
3899 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
3900 // For example, 'OOUI\MediaWikiTheme'.
3901 $themeClass = "OOUI\\{$theme}Theme";
3902 OOUI\Theme::setSingleton( new $themeClass() );
3903 OOUI\Element::setDefaultDir( $dir );
3907 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3908 * MediaWiki and this OutputPage instance.
3910 * @since 1.25
3912 public function enableOOUI() {
3913 self::setupOOUI(
3914 strtolower( $this->getSkin()->getSkinName() ),
3915 $this->getLanguage()->getDir()
3917 $this->addModuleStyles( [
3918 'oojs-ui-core.styles',
3919 'oojs-ui.styles.icons',
3920 'oojs-ui.styles.indicators',
3921 'oojs-ui.styles.textures',
3922 'mediawiki.widgets.styles',
3923 ] );