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
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @var string Variable mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
126 protected $mIndicators = array();
128 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
129 private $mLanguageLinks = array();
132 * Used for JavaScript (pre resource loader)
133 * @todo We should split JS / CSS.
134 * mScripts content is inserted as is in "<head>" by Skin. This might
135 * contain either a link to a stylesheet or inline CSS.
137 private $mScripts = '';
139 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
140 protected $mInlineStyles = '';
143 private $mLinkColours;
146 * @var string Used by skin template.
147 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
149 public $mPageLinkTitle = '';
151 /** @var array Array of elements in "<head>". Parser might add its own headers! */
152 protected $mHeadItems = array();
154 // @todo FIXME: Next 5 variables probably come from the resource loader
157 protected $mModules = array();
160 protected $mModuleScripts = array();
163 protected $mModuleStyles = array();
166 protected $mModuleMessages = array();
168 /** @var ResourceLoader */
169 protected $mResourceLoader;
172 protected $mJsConfigVars = array();
175 protected $mTemplateIds = array();
178 protected $mImageTimeKeys = array();
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = array(
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
203 private $mContainsOldMagic = 0;
206 protected $mContainsNewMagic = 0;
209 * lazy initialised, use parserOptions()
212 protected $mParserOptions = null;
215 * Handles the Atom / RSS links.
216 * We probably only support Atom in 2011.
217 * @see $wgAdvertisedFeedTypes
219 private $mFeedLinks = array();
221 // Gwicke work on squid caching? Roughly from 2003.
222 protected $mEnableClientCache = true;
224 /** @var bool Flag if output should only contain the body of the article. */
225 private $mArticleBodyOnly = false;
228 protected $mNewSectionLink = false;
231 protected $mHideNewSectionLink = false;
234 * @var bool Comes from the parser. This was probably made to load CSS/JS
235 * only if we had "<gallery>". Used directly in CategoryPage.php.
236 * Looks like resource loader can replace this.
238 public $mNoGallery = false;
241 private $mPageTitleActionText = '';
244 private $mParseWarnings = array();
246 /** @var int Cache stuff. Looks like mEnableClientCache */
247 protected $mSquidMaxage = 0;
253 protected $mPreventClickjacking = true;
255 /** @var int To include the variable {{REVISIONID}} */
256 private $mRevisionId = null;
259 private $mRevisionTimestamp = null;
262 protected $mFileVersion = null;
265 * @var array An array of stylesheet filenames (relative from skins path),
266 * with options for CSS media, IE conditions, and RTL/LTR direction.
267 * For internal use; add settings in the skin via $this->addStyle()
269 * Style again! This seems like a code duplication since we already have
270 * mStyles. This is what makes Open Source amazing.
272 protected $styles = array();
275 * Whether jQuery is already handled.
277 protected $mJQueryDone = false;
279 private $mIndexPolicy = 'index';
280 private $mFollowPolicy = 'follow';
281 private $mVaryHeader = array(
282 'Accept-Encoding' => array( 'list-contains=gzip' ),
286 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
291 private $mRedirectedFrom = null;
294 * Additional key => value data
296 private $mProperties = array();
299 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
301 private $mTarget = null;
304 * @var bool Whether parser output should contain table of contents
306 private $mEnableTOC = true;
309 * @var bool Whether parser output should contain section edit links
311 private $mEnableSectionEditLinks = true;
314 * Constructor for OutputPage. This should not be called directly.
315 * Instead a new RequestContext should be created and it will implicitly create
316 * a OutputPage tied to that context.
317 * @param IContextSource|null $context
319 function __construct( IContextSource
$context = null ) {
320 if ( $context === null ) {
321 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
322 wfDeprecated( __METHOD__
, '1.18' );
324 $this->setContext( $context );
329 * Redirect to $url rather than displaying the normal page
331 * @param string $url URL
332 * @param string $responsecode HTTP status code
334 public function redirect( $url, $responsecode = '302' ) {
335 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
336 $this->mRedirect
= str_replace( "\n", '', $url );
337 $this->mRedirectCode
= $responsecode;
341 * Get the URL to redirect to, or an empty string if not redirect URL set
345 public function getRedirect() {
346 return $this->mRedirect
;
350 * Set the HTTP status code to send with the output.
352 * @param int $statusCode
354 public function setStatusCode( $statusCode ) {
355 $this->mStatusCode
= $statusCode;
359 * Add a new "<meta>" tag
360 * To add an http-equiv meta tag, precede the name with "http:"
362 * @param string $name Tag name
363 * @param string $val Tag value
365 function addMeta( $name, $val ) {
366 array_push( $this->mMetatags
, array( $name, $val ) );
370 * Add a new \<link\> tag to the page header.
372 * Note: use setCanonicalUrl() for rel=canonical.
374 * @param array $linkarr Associative array of attributes.
376 function addLink( array $linkarr ) {
377 array_push( $this->mLinktags
, $linkarr );
381 * Add a new \<link\> with "rel" attribute set to "meta"
383 * @param array $linkarr Associative array mapping attribute names to their
384 * values, both keys and values will be escaped, and the
385 * "rel" attribute will be automatically added
387 function addMetadataLink( array $linkarr ) {
388 $linkarr['rel'] = $this->getMetadataAttribute();
389 $this->addLink( $linkarr );
393 * Set the URL to be used for the <link rel=canonical>. This should be used
394 * in preference to addLink(), to avoid duplicate link tags.
397 function setCanonicalUrl( $url ) {
398 $this->mCanonicalUrl
= $url;
402 * Get the value of the "rel" attribute for metadata links
406 public function getMetadataAttribute() {
407 # note: buggy CC software only reads first "meta" link
408 static $haveMeta = false;
410 return 'alternate meta';
418 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
420 * @param string $script Raw HTML
422 function addScript( $script ) {
423 $this->mScripts
.= $script . "\n";
427 * Register and add a stylesheet from an extension directory.
429 * @param string $url Path to sheet. Provide either a full url (beginning
430 * with 'http', etc) or a relative path from the document root
431 * (beginning with '/'). Otherwise it behaves identically to
432 * addStyle() and draws from the /skins folder.
434 public function addExtensionStyle( $url ) {
435 array_push( $this->mExtStyles
, $url );
439 * Get all styles added by extensions
443 function getExtStyle() {
444 return $this->mExtStyles
;
448 * Add a JavaScript file out of skins/common, or a given relative path.
450 * @param string $file Filename in skins/common or complete on-server path
452 * @param string $version Style version of the file. Defaults to $wgStyleVersion
454 public function addScriptFile( $file, $version = null ) {
455 // See if $file parameter is an absolute URL or begins with a slash
456 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
459 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
461 if ( is_null( $version ) ) {
462 $version = $this->getConfig()->get( 'StyleVersion' );
464 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
468 * Add a self-contained script tag with the given contents
470 * @param string $script JavaScript text, no "<script>" tags
472 public function addInlineScript( $script ) {
473 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
477 * Get all registered JS and CSS tags for the header.
480 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
482 function getScript() {
483 wfDeprecated( __METHOD__
, '1.24' );
484 return $this->mScripts
. $this->getHeadItems();
488 * Filter an array of modules to remove insufficiently trustworthy members, and modules
489 * which are no longer registered (eg a page is cached before an extension is disabled)
490 * @param array $modules
491 * @param string|null $position If not null, only return modules with this position
492 * @param string $type
495 protected function filterModules( array $modules, $position = null,
496 $type = ResourceLoaderModule
::TYPE_COMBINED
498 $resourceLoader = $this->getResourceLoader();
499 $filteredModules = array();
500 foreach ( $modules as $val ) {
501 $module = $resourceLoader->getModule( $val );
502 if ( $module instanceof ResourceLoaderModule
503 && $module->getOrigin() <= $this->getAllowedModules( $type )
504 && ( is_null( $position ) ||
$module->getPosition() == $position )
505 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
507 $filteredModules[] = $val;
510 return $filteredModules;
514 * Get the list of modules to include on this page
516 * @param bool $filter Whether to filter out insufficiently trustworthy modules
517 * @param string|null $position If not null, only return modules with this position
518 * @param string $param
519 * @return array Array of module names
521 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
522 $modules = array_values( array_unique( $this->$param ) );
524 ?
$this->filterModules( $modules, $position )
529 * Add one or more modules recognized by the resource loader. Modules added
530 * through this function will be loaded by the resource loader when the
533 * @param string|array $modules Module name (string) or array of module names
535 public function addModules( $modules ) {
536 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
540 * Get the list of module JS to include on this page
542 * @param bool $filter
543 * @param string|null $position
545 * @return array Array of module names
547 public function getModuleScripts( $filter = false, $position = null ) {
548 return $this->getModules( $filter, $position, 'mModuleScripts' );
552 * Add only JS of one or more modules recognized by the resource loader. Module
553 * scripts added through this function will be loaded by the resource loader when
556 * @param string|array $modules Module name (string) or array of module names
558 public function addModuleScripts( $modules ) {
559 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
563 * Get the list of module CSS to include on this page
565 * @param bool $filter
566 * @param string|null $position
568 * @return array Array of module names
570 public function getModuleStyles( $filter = false, $position = null ) {
571 return $this->getModules( $filter, $position, 'mModuleStyles' );
575 * Add only CSS of one or more modules recognized by the resource loader.
577 * Module styles added through this function will be added using standard link CSS
578 * tags, rather than as a combined Javascript and CSS package. Thus, they will
579 * load when JavaScript is disabled (unless CSS also happens to be disabled).
581 * @param string|array $modules Module name (string) or array of module names
583 public function addModuleStyles( $modules ) {
584 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
588 * Get the list of module messages to include on this page
590 * @param bool $filter
591 * @param string|null $position
593 * @return array Array of module names
595 public function getModuleMessages( $filter = false, $position = null ) {
596 return $this->getModules( $filter, $position, 'mModuleMessages' );
600 * Add only messages of one or more modules recognized by the resource loader.
601 * Module messages added through this function will be loaded by the resource
602 * loader when the page loads.
604 * @param string|array $modules Module name (string) or array of module names
606 public function addModuleMessages( $modules ) {
607 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
611 * @return null|string ResourceLoader target
613 public function getTarget() {
614 return $this->mTarget
;
618 * Sets ResourceLoader target for load.php links. If null, will be omitted
620 * @param string|null $target
622 public function setTarget( $target ) {
623 $this->mTarget
= $target;
627 * Get an array of head items
631 function getHeadItemsArray() {
632 return $this->mHeadItems
;
636 * Get all header items in a string
639 * @deprecated since 1.24 Use OutputPage::headElement or
640 * if absolutely necessary use OutputPage::getHeadItemsArray
642 function getHeadItems() {
643 wfDeprecated( __METHOD__
, '1.24' );
645 foreach ( $this->mHeadItems
as $item ) {
652 * Add or replace an header item to the output
654 * @param string $name Item name
655 * @param string $value Raw HTML
657 public function addHeadItem( $name, $value ) {
658 $this->mHeadItems
[$name] = $value;
662 * Check if the header item $name is already set
664 * @param string $name Item name
667 public function hasHeadItem( $name ) {
668 return isset( $this->mHeadItems
[$name] );
672 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
674 * @param string $tag Value of "ETag" header
676 function setETag( $tag ) {
681 * Set whether the output should only contain the body of the article,
682 * without any skin, sidebar, etc.
683 * Used e.g. when calling with "action=render".
685 * @param bool $only Whether to output only the body of the article
687 public function setArticleBodyOnly( $only ) {
688 $this->mArticleBodyOnly
= $only;
692 * Return whether the output will contain only the body of the article
696 public function getArticleBodyOnly() {
697 return $this->mArticleBodyOnly
;
701 * Set an additional output property
704 * @param string $name
705 * @param mixed $value
707 public function setProperty( $name, $value ) {
708 $this->mProperties
[$name] = $value;
712 * Get an additional output property
715 * @param string $name
716 * @return mixed Property value or null if not found
718 public function getProperty( $name ) {
719 if ( isset( $this->mProperties
[$name] ) ) {
720 return $this->mProperties
[$name];
727 * checkLastModified tells the client to use the client-cached page if
728 * possible. If successful, the OutputPage is disabled so that
729 * any future call to OutputPage->output() have no effect.
731 * Side effect: sets mLastModified for Last-Modified header
733 * @param string $timestamp
735 * @return bool True if cache-ok headers was sent.
737 public function checkLastModified( $timestamp ) {
738 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
739 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
742 $config = $this->getConfig();
743 if ( !$config->get( 'CachePages' ) ) {
744 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
748 $timestamp = wfTimestamp( TS_MW
, $timestamp );
749 $modifiedTimes = array(
750 'page' => $timestamp,
751 'user' => $this->getUser()->getTouched(),
752 'epoch' => $config->get( 'CacheEpoch' )
754 if ( $config->get( 'UseSquid' ) ) {
755 // bug 44570: the core page itself may not change, but resources might
756 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
758 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
760 $maxModified = max( $modifiedTimes );
761 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
763 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
764 if ( $clientHeader === false ) {
765 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
769 # IE sends sizes after the date like this:
770 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
771 # this breaks strtotime().
772 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
774 wfSuppressWarnings(); // E_STRICT system time bitching
775 $clientHeaderTime = strtotime( $clientHeader );
777 if ( !$clientHeaderTime ) {
779 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
782 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
786 foreach ( $modifiedTimes as $name => $value ) {
787 if ( $info !== '' ) {
790 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
793 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
794 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
795 wfDebug( __METHOD__
. ": effective Last-Modified: " .
796 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
797 if ( $clientHeaderTime < $maxModified ) {
798 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
803 # Give a 304 response code and disable body output
804 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
805 ini_set( 'zlib.output_compression', 0 );
806 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
807 $this->sendCacheControl();
810 // Don't output a compressed blob when using ob_gzhandler;
811 // it's technically against HTTP spec and seems to confuse
812 // Firefox when the response gets split over two packets.
813 wfClearOutputBuffers();
819 * Override the last modified timestamp
821 * @param string $timestamp New timestamp, in a format readable by
824 public function setLastModified( $timestamp ) {
825 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
829 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
831 * @param string $policy The literal string to output as the contents of
832 * the meta tag. Will be parsed according to the spec and output in
836 public function setRobotPolicy( $policy ) {
837 $policy = Article
::formatRobotPolicy( $policy );
839 if ( isset( $policy['index'] ) ) {
840 $this->setIndexPolicy( $policy['index'] );
842 if ( isset( $policy['follow'] ) ) {
843 $this->setFollowPolicy( $policy['follow'] );
848 * Set the index policy for the page, but leave the follow policy un-
851 * @param string $policy Either 'index' or 'noindex'.
854 public function setIndexPolicy( $policy ) {
855 $policy = trim( $policy );
856 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
857 $this->mIndexPolicy
= $policy;
862 * Set the follow policy for the page, but leave the index policy un-
865 * @param string $policy Either 'follow' or 'nofollow'.
868 public function setFollowPolicy( $policy ) {
869 $policy = trim( $policy );
870 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
871 $this->mFollowPolicy
= $policy;
876 * Set the new value of the "action text", this will be added to the
877 * "HTML title", separated from it with " - ".
879 * @param string $text New value of the "action text"
881 public function setPageTitleActionText( $text ) {
882 $this->mPageTitleActionText
= $text;
886 * Get the value of the "action text"
890 public function getPageTitleActionText() {
891 return $this->mPageTitleActionText
;
895 * "HTML title" means the contents of "<title>".
896 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
898 * @param string|Message $name
900 public function setHTMLTitle( $name ) {
901 if ( $name instanceof Message
) {
902 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
904 $this->mHTMLtitle
= $name;
909 * Return the "HTML title", i.e. the content of the "<title>" tag.
913 public function getHTMLTitle() {
914 return $this->mHTMLtitle
;
918 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
922 public function setRedirectedFrom( $t ) {
923 $this->mRedirectedFrom
= $t;
927 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
928 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
929 * but not bad tags like \<script\>. This function automatically sets
930 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
931 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
932 * good tags like \<i\> will be dropped entirely.
934 * @param string|Message $name
936 public function setPageTitle( $name ) {
937 if ( $name instanceof Message
) {
938 $name = $name->setContext( $this->getContext() )->text();
941 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
942 # but leave "<i>foobar</i>" alone
943 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
944 $this->mPagetitle
= $nameWithTags;
946 # change "<i>foo&bar</i>" to "foo&bar"
948 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
949 ->inContentLanguage()
954 * Return the "page title", i.e. the content of the \<h1\> tag.
958 public function getPageTitle() {
959 return $this->mPagetitle
;
963 * Set the Title object to use
967 public function setTitle( Title
$t ) {
968 $this->getContext()->setTitle( $t );
972 * Replace the subtitle with $str
974 * @param string|Message $str New value of the subtitle. String should be safe HTML.
976 public function setSubtitle( $str ) {
977 $this->clearSubtitle();
978 $this->addSubtitle( $str );
982 * Add $str to the subtitle
984 * @deprecated since 1.19; use addSubtitle() instead
985 * @param string|Message $str String or Message to add to the subtitle
987 public function appendSubtitle( $str ) {
988 $this->addSubtitle( $str );
992 * Add $str to the subtitle
994 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
996 public function addSubtitle( $str ) {
997 if ( $str instanceof Message
) {
998 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1000 $this->mSubtitle
[] = $str;
1005 * Add a subtitle containing a backlink to a page
1007 * @param Title $title Title to link to
1008 * @param array $query Array of additional parameters to include in the link
1010 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1011 if ( $title->isRedirect() ) {
1012 $query['redirect'] = 'no';
1014 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1015 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1019 * Clear the subtitles
1021 public function clearSubtitle() {
1022 $this->mSubtitle
= array();
1030 public function getSubtitle() {
1031 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1035 * Set the page as printable, i.e. it'll be displayed with with all
1036 * print styles included
1038 public function setPrintable() {
1039 $this->mPrintable
= true;
1043 * Return whether the page is "printable"
1047 public function isPrintable() {
1048 return $this->mPrintable
;
1052 * Disable output completely, i.e. calling output() will have no effect
1054 public function disable() {
1055 $this->mDoNothing
= true;
1059 * Return whether the output will be completely disabled
1063 public function isDisabled() {
1064 return $this->mDoNothing
;
1068 * Show an "add new section" link?
1072 public function showNewSectionLink() {
1073 return $this->mNewSectionLink
;
1077 * Forcibly hide the new section link?
1081 public function forceHideNewSectionLink() {
1082 return $this->mHideNewSectionLink
;
1086 * Add or remove feed links in the page header
1087 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1088 * for the new version
1089 * @see addFeedLink()
1091 * @param bool $show True: add default feeds, false: remove all feeds
1093 public function setSyndicated( $show = true ) {
1095 $this->setFeedAppendQuery( false );
1097 $this->mFeedLinks
= array();
1102 * Add default feeds to the page header
1103 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1104 * for the new version
1105 * @see addFeedLink()
1107 * @param string $val Query to append to feed links or false to output
1110 public function setFeedAppendQuery( $val ) {
1111 $this->mFeedLinks
= array();
1113 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1114 $query = "feed=$type";
1115 if ( is_string( $val ) ) {
1116 $query .= '&' . $val;
1118 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1123 * Add a feed link to the page header
1125 * @param string $format Feed type, should be a key of $wgFeedClasses
1126 * @param string $href URL
1128 public function addFeedLink( $format, $href ) {
1129 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1130 $this->mFeedLinks
[$format] = $href;
1135 * Should we output feed links for this page?
1138 public function isSyndicated() {
1139 return count( $this->mFeedLinks
) > 0;
1143 * Return URLs for each supported syndication format for this page.
1144 * @return array Associating format keys with URLs
1146 public function getSyndicationLinks() {
1147 return $this->mFeedLinks
;
1151 * Will currently always return null
1155 public function getFeedAppendQuery() {
1156 return $this->mFeedLinksAppendQuery
;
1160 * Set whether the displayed content is related to the source of the
1161 * corresponding article on the wiki
1162 * Setting true will cause the change "article related" toggle to true
1166 public function setArticleFlag( $v ) {
1167 $this->mIsarticle
= $v;
1169 $this->mIsArticleRelated
= $v;
1174 * Return whether the content displayed page is related to the source of
1175 * the corresponding article on the wiki
1179 public function isArticle() {
1180 return $this->mIsarticle
;
1184 * Set whether this page is related an article on the wiki
1185 * Setting false will cause the change of "article flag" toggle to false
1189 public function setArticleRelated( $v ) {
1190 $this->mIsArticleRelated
= $v;
1192 $this->mIsarticle
= false;
1197 * Return whether this page is related an article on the wiki
1201 public function isArticleRelated() {
1202 return $this->mIsArticleRelated
;
1206 * Add new language links
1208 * @param array $newLinkArray Associative array mapping language code to the page
1211 public function addLanguageLinks( array $newLinkArray ) {
1212 $this->mLanguageLinks +
= $newLinkArray;
1216 * Reset the language links and add new language links
1218 * @param array $newLinkArray Associative array mapping language code to the page
1221 public function setLanguageLinks( array $newLinkArray ) {
1222 $this->mLanguageLinks
= $newLinkArray;
1226 * Get the list of language links
1228 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1230 public function getLanguageLinks() {
1231 return $this->mLanguageLinks
;
1235 * Add an array of categories, with names in the keys
1237 * @param array $categories Mapping category name => sort key
1239 public function addCategoryLinks( array $categories ) {
1242 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1246 # Add the links to a LinkBatch
1247 $arr = array( NS_CATEGORY
=> $categories );
1248 $lb = new LinkBatch
;
1249 $lb->setArray( $arr );
1251 # Fetch existence plus the hiddencat property
1252 $dbr = wfGetDB( DB_SLAVE
);
1253 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1254 'page_is_redirect', 'page_latest', 'pp_value' );
1256 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1257 $fields[] = 'page_content_model';
1260 $res = $dbr->select( array( 'page', 'page_props' ),
1262 $lb->constructSet( 'page', $dbr ),
1265 array( 'page_props' => array( 'LEFT JOIN', array(
1266 'pp_propname' => 'hiddencat',
1271 # Add the results to the link cache
1272 $lb->addResultToCache( LinkCache
::singleton(), $res );
1274 # Set all the values to 'normal'.
1275 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1277 # Mark hidden categories
1278 foreach ( $res as $row ) {
1279 if ( isset( $row->pp_value
) ) {
1280 $categories[$row->page_title
] = 'hidden';
1284 # Add the remaining categories to the skin
1286 'OutputPageMakeCategoryLinks',
1287 array( &$this, $categories, &$this->mCategoryLinks
) )
1289 foreach ( $categories as $category => $type ) {
1290 $origcategory = $category;
1291 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1295 $wgContLang->findVariantLink( $category, $title, true );
1296 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1299 $text = $wgContLang->convertHtml( $title->getText() );
1300 $this->mCategories
[] = $title->getText();
1301 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1307 * Reset the category links (but not the category list) and add $categories
1309 * @param array $categories Mapping category name => sort key
1311 public function setCategoryLinks( array $categories ) {
1312 $this->mCategoryLinks
= array();
1313 $this->addCategoryLinks( $categories );
1317 * Get the list of category links, in a 2-D array with the following format:
1318 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1319 * hidden categories) and $link a HTML fragment with a link to the category
1324 public function getCategoryLinks() {
1325 return $this->mCategoryLinks
;
1329 * Get the list of category names this page belongs to
1331 * @return array Array of strings
1333 public function getCategories() {
1334 return $this->mCategories
;
1338 * Add an array of indicators, with their identifiers as array keys and HTML contents as values.
1340 * In case of duplicate keys, existing values are overwritten.
1342 * @param array $indicators
1345 public function setIndicators( array $indicators ) {
1346 $this->mIndicators
= $indicators +
$this->mIndicators
;
1347 // Keep ordered by key
1348 ksort( $this->mIndicators
);
1352 * Get the indicators associated with this page.
1354 * The array will be internally ordered by item keys.
1356 * @return array Keys: identifiers, values: HTML contents
1359 public function getIndicators() {
1360 return $this->mIndicators
;
1364 * Do not allow scripts which can be modified by wiki users to load on this page;
1365 * only allow scripts bundled with, or generated by, the software.
1366 * Site-wide styles are controlled by a config setting, since they can be
1367 * used to create a custom skin/theme, but not user-specific ones.
1369 * @todo this should be given a more accurate name
1371 public function disallowUserJs() {
1372 $this->reduceAllowedModules(
1373 ResourceLoaderModule
::TYPE_SCRIPTS
,
1374 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1377 // Site-wide styles are controlled by a config setting, see bug 71621
1378 // for background on why. User styles are never allowed.
1379 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1380 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1382 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1384 $this->reduceAllowedModules(
1385 ResourceLoaderModule
::TYPE_STYLES
,
1391 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1392 * @see ResourceLoaderModule::$origin
1393 * @param string $type ResourceLoaderModule TYPE_ constant
1394 * @return int ResourceLoaderModule ORIGIN_ class constant
1396 public function getAllowedModules( $type ) {
1397 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1398 return min( array_values( $this->mAllowedModules
) );
1400 return isset( $this->mAllowedModules
[$type] )
1401 ?
$this->mAllowedModules
[$type]
1402 : ResourceLoaderModule
::ORIGIN_ALL
;
1407 * Set the highest level of CSS/JS untrustworthiness allowed
1409 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1410 * Use reduceAllowedModules() instead
1411 * @param string $type ResourceLoaderModule TYPE_ constant
1412 * @param int $level ResourceLoaderModule class constant
1414 public function setAllowedModules( $type, $level ) {
1415 wfDeprecated( __METHOD__
, '1.24' );
1416 $this->reduceAllowedModules( $type, $level );
1420 * Limit the highest level of CSS/JS untrustworthiness allowed.
1422 * If passed the same or a higher level than the current level of untrustworthiness set, the
1423 * level will remain unchanged.
1425 * @param string $type
1426 * @param int $level ResourceLoaderModule class constant
1428 public function reduceAllowedModules( $type, $level ) {
1429 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1433 * Prepend $text to the body HTML
1435 * @param string $text HTML
1437 public function prependHTML( $text ) {
1438 $this->mBodytext
= $text . $this->mBodytext
;
1442 * Append $text to the body HTML
1444 * @param string $text HTML
1446 public function addHTML( $text ) {
1447 $this->mBodytext
.= $text;
1451 * Shortcut for adding an Html::element via addHTML.
1455 * @param string $element
1456 * @param array $attribs
1457 * @param string $contents
1459 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1460 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1464 * Clear the body HTML
1466 public function clearHTML() {
1467 $this->mBodytext
= '';
1473 * @return string HTML
1475 public function getHTML() {
1476 return $this->mBodytext
;
1480 * Get/set the ParserOptions object to use for wikitext parsing
1482 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1483 * current ParserOption object
1484 * @return ParserOptions
1486 public function parserOptions( $options = null ) {
1487 if ( !$this->mParserOptions
) {
1488 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1489 $this->mParserOptions
->setEditSection( false );
1491 return wfSetVar( $this->mParserOptions
, $options );
1495 * Set the revision ID which will be seen by the wiki text parser
1496 * for things such as embedded {{REVISIONID}} variable use.
1498 * @param int|null $revid An positive integer, or null
1499 * @return mixed Previous value
1501 public function setRevisionId( $revid ) {
1502 $val = is_null( $revid ) ?
null : intval( $revid );
1503 return wfSetVar( $this->mRevisionId
, $val );
1507 * Get the displayed revision ID
1511 public function getRevisionId() {
1512 return $this->mRevisionId
;
1516 * Set the timestamp of the revision which will be displayed. This is used
1517 * to avoid a extra DB call in Skin::lastModified().
1519 * @param string|null $timestamp
1520 * @return mixed Previous value
1522 public function setRevisionTimestamp( $timestamp ) {
1523 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1527 * Get the timestamp of displayed revision.
1528 * This will be null if not filled by setRevisionTimestamp().
1530 * @return string|null
1532 public function getRevisionTimestamp() {
1533 return $this->mRevisionTimestamp
;
1537 * Set the displayed file version
1539 * @param File|bool $file
1540 * @return mixed Previous value
1542 public function setFileVersion( $file ) {
1544 if ( $file instanceof File
&& $file->exists() ) {
1545 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1547 return wfSetVar( $this->mFileVersion
, $val, true );
1551 * Get the displayed file version
1553 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1555 public function getFileVersion() {
1556 return $this->mFileVersion
;
1560 * Get the templates used on this page
1562 * @return array (namespace => dbKey => revId)
1565 public function getTemplateIds() {
1566 return $this->mTemplateIds
;
1570 * Get the files used on this page
1572 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1575 public function getFileSearchOptions() {
1576 return $this->mImageTimeKeys
;
1580 * Convert wikitext to HTML and add it to the buffer
1581 * Default assumes that the current page title will be used.
1583 * @param string $text
1584 * @param bool $linestart Is this the start of a line?
1585 * @param bool $interface Is this text in the user interface language?
1587 public function addWikiText( $text, $linestart = true, $interface = true ) {
1588 $title = $this->getTitle(); // Work around E_STRICT
1590 throw new MWException( 'Title is null' );
1592 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1596 * Add wikitext with a custom Title object
1598 * @param string $text Wikitext
1599 * @param Title $title
1600 * @param bool $linestart Is this the start of a line?
1602 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1603 $this->addWikiTextTitle( $text, $title, $linestart );
1607 * Add wikitext with a custom Title object and tidy enabled.
1609 * @param string $text Wikitext
1610 * @param Title $title
1611 * @param bool $linestart Is this the start of a line?
1613 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1614 $this->addWikiTextTitle( $text, $title, $linestart, true );
1618 * Add wikitext with tidy enabled
1620 * @param string $text Wikitext
1621 * @param bool $linestart Is this the start of a line?
1623 public function addWikiTextTidy( $text, $linestart = true ) {
1624 $title = $this->getTitle();
1625 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1629 * Add wikitext with a custom Title object
1631 * @param string $text Wikitext
1632 * @param Title $title
1633 * @param bool $linestart Is this the start of a line?
1634 * @param bool $tidy Whether to use tidy
1635 * @param bool $interface Whether it is an interface message
1636 * (for example disables conversion)
1638 public function addWikiTextTitle( $text, Title
$title, $linestart,
1639 $tidy = false, $interface = false
1643 wfProfileIn( __METHOD__
);
1645 $popts = $this->parserOptions();
1646 $oldTidy = $popts->setTidy( $tidy );
1647 $popts->setInterfaceMessage( (bool)$interface );
1649 $parserOutput = $wgParser->getFreshParser()->parse(
1650 $text, $title, $popts,
1651 $linestart, true, $this->mRevisionId
1654 $popts->setTidy( $oldTidy );
1656 $this->addParserOutput( $parserOutput );
1658 wfProfileOut( __METHOD__
);
1662 * Add a ParserOutput object, but without Html.
1664 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1665 * @param ParserOutput $parserOutput
1667 public function addParserOutputNoText( $parserOutput ) {
1668 $this->addParserOutputMetadata( $parserOutput );
1672 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1673 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1677 * @param ParserOutput $parserOutput
1679 public function addParserOutputMetadata( $parserOutput ) {
1680 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1681 $this->addCategoryLinks( $parserOutput->getCategories() );
1682 $this->setIndicators( $parserOutput->getIndicators() );
1683 $this->mNewSectionLink
= $parserOutput->getNewSection();
1684 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1686 $this->mParseWarnings
= $parserOutput->getWarnings();
1687 if ( !$parserOutput->isCacheable() ) {
1688 $this->enableClientCache( false );
1690 $this->mNoGallery
= $parserOutput->getNoGallery();
1691 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1692 $this->addModules( $parserOutput->getModules() );
1693 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1694 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1695 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1696 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1697 $this->mPreventClickjacking
= $this->mPreventClickjacking
1698 ||
$parserOutput->preventClickjacking();
1700 // Template versioning...
1701 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1702 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1703 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1705 $this->mTemplateIds
[$ns] = $dbks;
1708 // File versioning...
1709 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1710 $this->mImageTimeKeys
[$dbk] = $data;
1713 // Hooks registered in the object
1714 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1715 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1716 list( $hookName, $data ) = $hookInfo;
1717 if ( isset( $parserOutputHooks[$hookName] ) ) {
1718 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1722 // Link flags are ignored for now, but may in the future be
1723 // used to mark individual language links.
1724 $linkFlags = array();
1725 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1726 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1730 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1731 * ParserOutput object, without any other metadata.
1734 * @param ParserOutput $parserOutput
1736 public function addParserOutputContent( $parserOutput ) {
1737 $this->addParserOutputText( $parserOutput );
1739 $this->addModules( $parserOutput->getModules() );
1740 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1741 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1742 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1744 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1748 * Add the HTML associated with a ParserOutput object, without any metadata.
1751 * @param ParserOutput $parserOutput
1753 public function addParserOutputText( $parserOutput ) {
1754 $text = $parserOutput->getText();
1755 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1756 $this->addHTML( $text );
1760 * Add everything from a ParserOutput object.
1762 * @param ParserOutput $parserOutput
1764 function addParserOutput( $parserOutput ) {
1765 $this->addParserOutputMetadata( $parserOutput );
1766 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1768 // Touch section edit links only if not previously disabled
1769 if ( $parserOutput->getEditSectionTokens() ) {
1770 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1773 $this->addParserOutputText( $parserOutput );
1777 * Add the output of a QuickTemplate to the output buffer
1779 * @param QuickTemplate $template
1781 public function addTemplate( &$template ) {
1782 $this->addHTML( $template->getHTML() );
1786 * Parse wikitext and return the HTML.
1788 * @param string $text
1789 * @param bool $linestart Is this the start of a line?
1790 * @param bool $interface Use interface language ($wgLang instead of
1791 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1792 * This also disables LanguageConverter.
1793 * @param Language $language Target language object, will override $interface
1794 * @throws MWException
1795 * @return string HTML
1797 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1800 if ( is_null( $this->getTitle() ) ) {
1801 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1804 $popts = $this->parserOptions();
1806 $popts->setInterfaceMessage( true );
1808 if ( $language !== null ) {
1809 $oldLang = $popts->setTargetLanguage( $language );
1812 $parserOutput = $wgParser->getFreshParser()->parse(
1813 $text, $this->getTitle(), $popts,
1814 $linestart, true, $this->mRevisionId
1818 $popts->setInterfaceMessage( false );
1820 if ( $language !== null ) {
1821 $popts->setTargetLanguage( $oldLang );
1824 return $parserOutput->getText();
1828 * Parse wikitext, strip paragraphs, and return the HTML.
1830 * @param string $text
1831 * @param bool $linestart Is this the start of a line?
1832 * @param bool $interface Use interface language ($wgLang instead of
1833 * $wgContLang) while parsing language sensitive magic
1834 * words like GRAMMAR and PLURAL
1835 * @return string HTML
1837 public function parseInline( $text, $linestart = true, $interface = false ) {
1838 $parsed = $this->parse( $text, $linestart, $interface );
1839 return Parser
::stripOuterParagraph( $parsed );
1843 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1845 * @param int $maxage Maximum cache time on the Squid, in seconds.
1847 public function setSquidMaxage( $maxage ) {
1848 $this->mSquidMaxage
= $maxage;
1852 * Use enableClientCache(false) to force it to send nocache headers
1854 * @param bool $state
1858 public function enableClientCache( $state ) {
1859 return wfSetVar( $this->mEnableClientCache
, $state );
1863 * Get the list of cookies that will influence on the cache
1867 function getCacheVaryCookies() {
1869 if ( $cookies === null ) {
1870 $config = $this->getConfig();
1871 $cookies = array_merge(
1873 $config->get( 'CookiePrefix' ) . 'Token',
1874 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1878 $config->get( 'CacheVaryCookies' )
1880 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1886 * Check if the request has a cache-varying cookie header
1887 * If it does, it's very important that we don't allow public caching
1891 function haveCacheVaryCookies() {
1892 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1893 if ( $cookieHeader === false ) {
1896 $cvCookies = $this->getCacheVaryCookies();
1897 foreach ( $cvCookies as $cookieName ) {
1898 # Check for a simple string match, like the way squid does it
1899 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1900 wfDebug( __METHOD__
. ": found $cookieName\n" );
1904 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1909 * Add an HTTP header that will influence on the cache
1911 * @param string $header Header name
1912 * @param array|null $option
1913 * @todo FIXME: Document the $option parameter; it appears to be for
1914 * X-Vary-Options but what format is acceptable?
1916 public function addVaryHeader( $header, $option = null ) {
1917 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1918 $this->mVaryHeader
[$header] = (array)$option;
1919 } elseif ( is_array( $option ) ) {
1920 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1921 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1923 $this->mVaryHeader
[$header] = $option;
1926 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1930 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1931 * such as Accept-Encoding or Cookie
1935 public function getVaryHeader() {
1936 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1940 * Get a complete X-Vary-Options header
1944 public function getXVO() {
1945 $cvCookies = $this->getCacheVaryCookies();
1947 $cookiesOption = array();
1948 foreach ( $cvCookies as $cookieName ) {
1949 $cookiesOption[] = 'string-contains=' . $cookieName;
1951 $this->addVaryHeader( 'Cookie', $cookiesOption );
1954 foreach ( $this->mVaryHeader
as $header => $option ) {
1955 $newheader = $header;
1956 if ( is_array( $option ) && count( $option ) > 0 ) {
1957 $newheader .= ';' . implode( ';', $option );
1959 $headers[] = $newheader;
1961 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1967 * bug 21672: Add Accept-Language to Vary and XVO headers
1968 * if there's no 'variant' parameter existed in GET.
1971 * /w/index.php?title=Main_page should always be served; but
1972 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1974 function addAcceptLanguage() {
1975 $title = $this->getTitle();
1976 if ( !$title instanceof Title
) {
1980 $lang = $title->getPageLanguage();
1981 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1982 $variants = $lang->getVariants();
1983 $aloption = array();
1984 foreach ( $variants as $variant ) {
1985 if ( $variant === $lang->getCode() ) {
1988 $aloption[] = 'string-contains=' . $variant;
1990 // IE and some other browsers use BCP 47 standards in
1991 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1992 // We should handle these too.
1993 $variantBCP47 = wfBCP47( $variant );
1994 if ( $variantBCP47 !== $variant ) {
1995 $aloption[] = 'string-contains=' . $variantBCP47;
1999 $this->addVaryHeader( 'Accept-Language', $aloption );
2004 * Set a flag which will cause an X-Frame-Options header appropriate for
2005 * edit pages to be sent. The header value is controlled by
2006 * $wgEditPageFrameOptions.
2008 * This is the default for special pages. If you display a CSRF-protected
2009 * form on an ordinary view page, then you need to call this function.
2011 * @param bool $enable
2013 public function preventClickjacking( $enable = true ) {
2014 $this->mPreventClickjacking
= $enable;
2018 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2019 * This can be called from pages which do not contain any CSRF-protected
2022 public function allowClickjacking() {
2023 $this->mPreventClickjacking
= false;
2027 * Get the prevent-clickjacking flag
2032 public function getPreventClickjacking() {
2033 return $this->mPreventClickjacking
;
2037 * Get the X-Frame-Options header value (without the name part), or false
2038 * if there isn't one. This is used by Skin to determine whether to enable
2039 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2043 public function getFrameOptions() {
2044 $config = $this->getConfig();
2045 if ( $config->get( 'BreakFrames' ) ) {
2047 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2048 return $config->get( 'EditPageFrameOptions' );
2054 * Send cache control HTTP headers
2056 public function sendCacheControl() {
2057 $response = $this->getRequest()->response();
2058 $config = $this->getConfig();
2059 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2060 $response->header( "ETag: $this->mETag" );
2063 $this->addVaryHeader( 'Cookie' );
2064 $this->addAcceptLanguage();
2066 # don't serve compressed data to clients who can't handle it
2067 # maintain different caches for logged-in users and non-logged in ones
2068 $response->header( $this->getVaryHeader() );
2070 if ( $config->get( 'UseXVO' ) ) {
2071 # Add an X-Vary-Options header for Squid with Wikimedia patches
2072 $response->header( $this->getXVO() );
2075 if ( $this->mEnableClientCache
) {
2077 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2078 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2080 if ( $config->get( 'UseESI' ) ) {
2081 # We'll purge the proxy cache explicitly, but require end user agents
2082 # to revalidate against the proxy on each visit.
2083 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2084 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2085 # start with a shorter timeout for initial testing
2086 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2087 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2088 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2089 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2091 # We'll purge the proxy cache for anons explicitly, but require end user agents
2092 # to revalidate against the proxy on each visit.
2093 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2094 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2095 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2096 # start with a shorter timeout for initial testing
2097 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2098 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2099 . ', must-revalidate, max-age=0' );
2102 # We do want clients to cache if they can, but they *must* check for updates
2103 # on revisiting the page.
2104 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2105 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2106 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2108 if ( $this->mLastModified
) {
2109 $response->header( "Last-Modified: {$this->mLastModified}" );
2112 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2114 # In general, the absence of a last modified header should be enough to prevent
2115 # the client from using its cache. We send a few other things just to make sure.
2116 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2117 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2118 $response->header( 'Pragma: no-cache' );
2123 * Finally, all the text has been munged and accumulated into
2124 * the object, let's actually output it:
2126 public function output() {
2127 if ( $this->mDoNothing
) {
2131 wfProfileIn( __METHOD__
);
2133 $response = $this->getRequest()->response();
2134 $config = $this->getConfig();
2136 if ( $this->mRedirect
!= '' ) {
2137 # Standards require redirect URLs to be absolute
2138 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2140 $redirect = $this->mRedirect
;
2141 $code = $this->mRedirectCode
;
2143 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2144 if ( $code == '301' ||
$code == '303' ) {
2145 if ( !$config->get( 'DebugRedirects' ) ) {
2146 $message = HttpStatus
::getMessage( $code );
2147 $response->header( "HTTP/1.1 $code $message" );
2149 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2151 if ( $config->get( 'VaryOnXFP' ) ) {
2152 $this->addVaryHeader( 'X-Forwarded-Proto' );
2154 $this->sendCacheControl();
2156 $response->header( "Content-Type: text/html; charset=utf-8" );
2157 if ( $config->get( 'DebugRedirects' ) ) {
2158 $url = htmlspecialchars( $redirect );
2159 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2160 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2161 print "</body>\n</html>\n";
2163 $response->header( 'Location: ' . $redirect );
2167 wfProfileOut( __METHOD__
);
2169 } elseif ( $this->mStatusCode
) {
2170 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2172 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2176 # Buffer output; final headers may depend on later processing
2179 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2180 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2182 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2183 // jQuery etc. can work correctly.
2184 $response->header( 'X-UA-Compatible: IE=Edge' );
2186 // Prevent framing, if requested
2187 $frameOptions = $this->getFrameOptions();
2188 if ( $frameOptions ) {
2189 $response->header( "X-Frame-Options: $frameOptions" );
2192 if ( $this->mArticleBodyOnly
) {
2193 echo $this->mBodytext
;
2196 $sk = $this->getSkin();
2197 // add skin specific modules
2198 $modules = $sk->getDefaultModules();
2200 // enforce various default modules for all skins
2201 $coreModules = array(
2202 // keep this list as small as possible
2203 'mediawiki.page.startup',
2207 // Support for high-density display images if enabled
2208 if ( $config->get( 'ResponsiveImages' ) ) {
2209 $coreModules[] = 'mediawiki.hidpi';
2212 $this->addModules( $coreModules );
2213 foreach ( $modules as $group ) {
2214 $this->addModules( $group );
2216 MWDebug
::addModules( $this );
2218 // Hook that allows last minute changes to the output page, e.g.
2219 // adding of CSS or Javascript by extensions.
2220 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2222 wfProfileIn( 'Output-skin' );
2224 wfProfileOut( 'Output-skin' );
2227 // This hook allows last minute changes to final overall output by modifying output buffer
2228 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2230 $this->sendCacheControl();
2234 wfProfileOut( __METHOD__
);
2238 * Actually output something with print.
2240 * @param string $ins The string to output
2241 * @deprecated since 1.22 Use echo yourself.
2243 public function out( $ins ) {
2244 wfDeprecated( __METHOD__
, '1.22' );
2249 * Produce a "user is blocked" page.
2250 * @deprecated since 1.18
2252 function blockedPage() {
2253 throw new UserBlockedError( $this->getUser()->mBlock
);
2257 * Prepare this object to display an error page; disable caching and
2258 * indexing, clear the current text and redirect, set the page's title
2259 * and optionally an custom HTML title (content of the "<title>" tag).
2261 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2262 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2263 * optional, if not passed the "<title>" attribute will be
2264 * based on $pageTitle
2266 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2267 $this->setPageTitle( $pageTitle );
2268 if ( $htmlTitle !== false ) {
2269 $this->setHTMLTitle( $htmlTitle );
2271 $this->setRobotPolicy( 'noindex,nofollow' );
2272 $this->setArticleRelated( false );
2273 $this->enableClientCache( false );
2274 $this->mRedirect
= '';
2275 $this->clearSubtitle();
2280 * Output a standard error page
2282 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2283 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2284 * showErrorPage( 'titlemsg', $messageObject );
2285 * showErrorPage( $titleMessageObject, $messageObject );
2287 * @param string|Message $title Message key (string) for page title, or a Message object
2288 * @param string|Message $msg Message key (string) for page text, or a Message object
2289 * @param array $params Message parameters; ignored if $msg is a Message object
2291 public function showErrorPage( $title, $msg, $params = array() ) {
2292 if ( !$title instanceof Message
) {
2293 $title = $this->msg( $title );
2296 $this->prepareErrorPage( $title );
2298 if ( $msg instanceof Message
) {
2299 if ( $params !== array() ) {
2300 trigger_error( 'Argument ignored: $params. The message parameters argument '
2301 . 'is discarded when the $msg argument is a Message object instead of '
2302 . 'a string.', E_USER_NOTICE
);
2304 $this->addHTML( $msg->parseAsBlock() );
2306 $this->addWikiMsgArray( $msg, $params );
2309 $this->returnToMain();
2313 * Output a standard permission error page
2315 * @param array $errors Error message keys
2316 * @param string $action Action that was denied or null if unknown
2318 public function showPermissionsErrorPage( array $errors, $action = null ) {
2319 // For some action (read, edit, create and upload), display a "login to do this action"
2320 // error if all of the following conditions are met:
2321 // 1. the user is not logged in
2322 // 2. the only error is insufficient permissions (i.e. no block or something else)
2323 // 3. the error can be avoided simply by logging in
2324 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2325 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2326 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2327 && ( User
::groupHasPermission( 'user', $action )
2328 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2330 $displayReturnto = null;
2332 # Due to bug 32276, if a user does not have read permissions,
2333 # $this->getTitle() will just give Special:Badtitle, which is
2334 # not especially useful as a returnto parameter. Use the title
2335 # from the request instead, if there was one.
2336 $request = $this->getRequest();
2337 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2338 if ( $action == 'edit' ) {
2339 $msg = 'whitelistedittext';
2340 $displayReturnto = $returnto;
2341 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2342 $msg = 'nocreatetext';
2343 } elseif ( $action == 'upload' ) {
2344 $msg = 'uploadnologintext';
2346 $msg = 'loginreqpagetext';
2347 $displayReturnto = Title
::newMainPage();
2353 $query['returnto'] = $returnto->getPrefixedText();
2355 if ( !$request->wasPosted() ) {
2356 $returntoquery = $request->getValues();
2357 unset( $returntoquery['title'] );
2358 unset( $returntoquery['returnto'] );
2359 unset( $returntoquery['returntoquery'] );
2360 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2363 $loginLink = Linker
::linkKnown(
2364 SpecialPage
::getTitleFor( 'Userlogin' ),
2365 $this->msg( 'loginreqlink' )->escaped(),
2370 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2371 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2373 # Don't return to a page the user can't read otherwise
2374 # we'll end up in a pointless loop
2375 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2376 $this->returnToMain( null, $displayReturnto );
2379 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2380 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2385 * Display an error page indicating that a given version of MediaWiki is
2386 * required to use it
2388 * @param mixed $version The version of MediaWiki needed to use the page
2390 public function versionRequired( $version ) {
2391 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2393 $this->addWikiMsg( 'versionrequiredtext', $version );
2394 $this->returnToMain();
2398 * Display an error page noting that a given permission bit is required.
2399 * @deprecated since 1.18, just throw the exception directly
2400 * @param string $permission Key required
2401 * @throws PermissionsError
2403 public function permissionRequired( $permission ) {
2404 throw new PermissionsError( $permission );
2408 * Produce the stock "please login to use the wiki" page
2410 * @deprecated since 1.19; throw the exception directly
2412 public function loginToUse() {
2413 throw new PermissionsError( 'read' );
2417 * Format a list of error messages
2419 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2420 * @param string $action Action that was denied or null if unknown
2421 * @return string The wikitext error-messages, formatted into a list.
2423 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2424 if ( $action == null ) {
2425 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2427 $action_desc = $this->msg( "action-$action" )->plain();
2429 'permissionserrorstext-withaction',
2432 )->plain() . "\n\n";
2435 if ( count( $errors ) > 1 ) {
2436 $text .= '<ul class="permissions-errors">' . "\n";
2438 foreach ( $errors as $error ) {
2440 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2445 $text .= "<div class=\"permissions-errors\">\n" .
2446 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2454 * Display a page stating that the Wiki is in read-only mode.
2455 * Should only be called after wfReadOnly() has returned true.
2457 * Historically, this function was used to show the source of the page that the user
2458 * was trying to edit and _also_ permissions error messages. The relevant code was
2459 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2461 * @deprecated since 1.25; throw the exception directly
2462 * @throws ReadOnlyError
2464 public function readOnlyPage() {
2465 if ( func_num_args() > 0 ) {
2466 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2469 throw new ReadOnlyError
;
2473 * Turn off regular page output and return an error response
2474 * for when rate limiting has triggered.
2476 * @deprecated since 1.25; throw the exception directly
2478 public function rateLimited() {
2479 wfDeprecated( __METHOD__
, '1.25' );
2480 throw new ThrottledError
;
2484 * Show a warning about slave lag
2486 * If the lag is higher than $wgSlaveLagCritical seconds,
2487 * then the warning is a bit more obvious. If the lag is
2488 * lower than $wgSlaveLagWarning, then no warning is shown.
2490 * @param int $lag Slave lag
2492 public function showLagWarning( $lag ) {
2493 $config = $this->getConfig();
2494 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2495 $message = $lag < $config->get( 'SlaveLagCritical' )
2498 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2499 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2503 public function showFatalError( $message ) {
2504 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2506 $this->addHTML( $message );
2509 public function showUnexpectedValueError( $name, $val ) {
2510 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2513 public function showFileCopyError( $old, $new ) {
2514 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2517 public function showFileRenameError( $old, $new ) {
2518 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2521 public function showFileDeleteError( $name ) {
2522 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2525 public function showFileNotFoundError( $name ) {
2526 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2530 * Add a "return to" link pointing to a specified title
2532 * @param Title $title Title to link
2533 * @param array $query Query string parameters
2534 * @param string $text Text of the link (input is not escaped)
2535 * @param array $options Options array to pass to Linker
2537 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2538 $link = $this->msg( 'returnto' )->rawParams(
2539 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2540 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2544 * Add a "return to" link pointing to a specified title,
2545 * or the title indicated in the request, or else the main page
2547 * @param mixed $unused
2548 * @param Title|string $returnto Title or String to return to
2549 * @param string $returntoquery Query string for the return to link
2551 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2552 if ( $returnto == null ) {
2553 $returnto = $this->getRequest()->getText( 'returnto' );
2556 if ( $returntoquery == null ) {
2557 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2560 if ( $returnto === '' ) {
2561 $returnto = Title
::newMainPage();
2564 if ( is_object( $returnto ) ) {
2565 $titleObj = $returnto;
2567 $titleObj = Title
::newFromText( $returnto );
2569 if ( !is_object( $titleObj ) ) {
2570 $titleObj = Title
::newMainPage();
2573 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2577 * @param Skin $sk The given Skin
2578 * @param bool $includeStyle Unused
2579 * @return string The doctype, opening "<html>", and head element.
2581 public function headElement( Skin
$sk, $includeStyle = true ) {
2584 $section = new ProfileSection( __METHOD__
);
2586 $userdir = $this->getLanguage()->getDir();
2587 $sitedir = $wgContLang->getDir();
2589 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2591 if ( $this->getHTMLTitle() == '' ) {
2592 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2595 $openHead = Html
::openElement( 'head' );
2597 # Don't bother with the newline if $head == ''
2598 $ret .= "$openHead\n";
2601 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2602 // Add <meta charset="UTF-8">
2603 // This should be before <title> since it defines the charset used by
2604 // text including the text inside <title>.
2605 // The spec recommends defining XHTML5's charset using the XML declaration
2607 // Our XML declaration is output by Html::htmlHeader.
2608 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2609 // http://www.whatwg.org/html/semantics.html#charset
2610 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2613 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2615 foreach ( $this->getHeadLinksArray() as $item ) {
2616 $ret .= $item . "\n";
2619 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2620 $ret .= $this->buildCssLinks();
2622 $ret .= $this->getHeadScripts() . "\n";
2624 foreach ( $this->mHeadItems
as $item ) {
2625 $ret .= $item . "\n";
2628 $closeHead = Html
::closeElement( 'head' );
2630 $ret .= "$closeHead\n";
2633 $bodyClasses = array();
2634 $bodyClasses[] = 'mediawiki';
2636 # Classes for LTR/RTL directionality support
2637 $bodyClasses[] = $userdir;
2638 $bodyClasses[] = "sitedir-$sitedir";
2640 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2641 # A <body> class is probably not the best way to do this . . .
2642 $bodyClasses[] = 'capitalize-all-nouns';
2645 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2646 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2648 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2650 $bodyAttrs = array();
2651 // While the implode() is not strictly needed, it's used for backwards compatibility
2652 // (this used to be built as a string and hooks likely still expect that).
2653 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2655 // Allow skins and extensions to add body attributes they need
2656 $sk->addToBodyAttributes( $this, $bodyAttrs );
2657 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2659 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2665 * Get a ResourceLoader object associated with this OutputPage
2667 * @return ResourceLoader
2669 public function getResourceLoader() {
2670 if ( is_null( $this->mResourceLoader
) ) {
2671 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2673 return $this->mResourceLoader
;
2678 * @param array|string $modules One or more module names
2679 * @param string $only ResourceLoaderModule TYPE_ class constant
2680 * @param bool $useESI
2681 * @param array $extraQuery Array with extra query parameters to add to each
2682 * request. array( param => value ).
2683 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2684 * call rather than a "<script src='...'>" tag.
2685 * @return string The html "<script>", "<link>" and "<style>" tags
2687 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2688 array $extraQuery = array(), $loadCall = false
2690 $modules = (array)$modules;
2694 'states' => array(),
2697 if ( !count( $modules ) ) {
2701 if ( count( $modules ) > 1 ) {
2702 // Remove duplicate module requests
2703 $modules = array_unique( $modules );
2704 // Sort module names so requests are more uniform
2707 if ( ResourceLoader
::inDebugMode() ) {
2708 // Recursively call us for every item
2709 foreach ( $modules as $name ) {
2710 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2711 $links['html'] .= $link['html'];
2712 $links['states'] +
= $link['states'];
2718 if ( !is_null( $this->mTarget
) ) {
2719 $extraQuery['target'] = $this->mTarget
;
2722 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2723 $sortedModules = array();
2724 $resourceLoader = $this->getResourceLoader();
2725 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2726 foreach ( $modules as $name ) {
2727 $module = $resourceLoader->getModule( $name );
2728 # Check that we're allowed to include this module on this page
2730 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2731 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2732 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2733 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2734 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2735 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2736 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2741 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2744 foreach ( $sortedModules as $source => $groups ) {
2745 foreach ( $groups as $group => $grpModules ) {
2746 // Special handling for user-specific groups
2748 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2749 $user = $this->getUser()->getName();
2752 // Create a fake request based on the one we are about to make so modules return
2753 // correct timestamp and emptiness data
2754 $query = ResourceLoader
::makeLoaderQuery(
2755 array(), // modules; not determined yet
2756 $this->getLanguage()->getCode(),
2757 $this->getSkin()->getSkinName(),
2759 null, // version; not determined yet
2760 ResourceLoader
::inDebugMode(),
2761 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2762 $this->isPrintable(),
2763 $this->getRequest()->getBool( 'handheld' ),
2766 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2768 // Extract modules that know they're empty and see if we have one or more
2771 foreach ( $grpModules as $key => $module ) {
2772 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2773 // If we're only getting the styles, we don't need to do anything for empty modules.
2774 if ( $module->isKnownEmpty( $context ) ) {
2775 unset( $grpModules[$key] );
2776 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2777 $links['states'][$key] = 'ready';
2781 $isRaw |
= $module->isRaw();
2784 // If there are no non-empty modules, skip this group
2785 if ( count( $grpModules ) === 0 ) {
2789 // Inline private modules. These can't be loaded through load.php for security
2790 // reasons, see bug 34907. Note that these modules should be loaded from
2791 // getHeadScripts() before the first loader call. Otherwise other modules can't
2792 // properly use them as dependencies (bug 30914)
2793 if ( $group === 'private' ) {
2794 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2795 $links['html'] .= Html
::inlineStyle(
2796 $resourceLoader->makeModuleResponse( $context, $grpModules )
2799 $links['html'] .= Html
::inlineScript(
2800 ResourceLoader
::makeLoaderConditionalScript(
2801 $resourceLoader->makeModuleResponse( $context, $grpModules )
2805 $links['html'] .= "\n";
2809 // Special handling for the user group; because users might change their stuff
2810 // on-wiki like user pages, or user preferences; we need to find the highest
2811 // timestamp of these user-changeable modules so we can ensure cache misses on change
2812 // This should NOT be done for the site group (bug 27564) because anons get that too
2813 // and we shouldn't be putting timestamps in Squid-cached HTML
2815 if ( $group === 'user' ) {
2816 // Get the maximum timestamp
2818 foreach ( $grpModules as $module ) {
2819 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2821 // Add a version parameter so cache will break when things change
2822 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2825 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2826 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2827 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2829 if ( $useESI && $resourceLoaderUseESI ) {
2830 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2831 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2832 $link = Html
::inlineStyle( $esi );
2834 $link = Html
::inlineScript( $esi );
2837 // Automatically select style/script elements
2838 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2839 $link = Html
::linkedStyle( $url );
2840 } elseif ( $loadCall ) {
2841 $link = Html
::inlineScript(
2842 ResourceLoader
::makeLoaderConditionalScript(
2843 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2847 $link = Html
::linkedScript( $url );
2848 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2849 // Wrap only=script requests in a conditional as browsers not supported
2850 // by the startup module would unconditionally execute this module.
2851 // Otherwise users will get "ReferenceError: mw is undefined" or
2852 // "jQuery is undefined" from e.g. a "site" module.
2853 $link = Html
::inlineScript(
2854 ResourceLoader
::makeLoaderConditionalScript(
2855 Xml
::encodeJsCall( 'document.write', array( $link ) )
2860 // For modules requested directly in the html via <link> or <script>,
2861 // tell mw.loader they are being loading to prevent duplicate requests.
2862 foreach ( $grpModules as $key => $module ) {
2863 // Don't output state=loading for the startup module..
2864 if ( $key !== 'startup' ) {
2865 $links['states'][$key] = 'loading';
2871 if ( $group == 'noscript' ) {
2872 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2874 $links['html'] .= $link . "\n";
2883 * Build html output from an array of links from makeResourceLoaderLink.
2884 * @param array $links
2885 * @return string HTML
2887 protected static function getHtmlFromLoaderLinks( array $links ) {
2890 foreach ( $links as $link ) {
2891 if ( !is_array( $link ) ) {
2894 $html .= $link['html'];
2895 $states +
= $link['states'];
2899 if ( count( $states ) ) {
2900 $html = Html
::inlineScript(
2901 ResourceLoader
::makeLoaderConditionalScript(
2902 ResourceLoader
::makeLoaderStateScript( $states )
2911 * JS stuff to put in the "<head>". This is the startup module, config
2912 * vars and modules marked with position 'top'
2914 * @return string HTML fragment
2916 function getHeadScripts() {
2917 // Startup - this will immediately load jquery and mediawiki modules
2919 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2921 // Load config before anything else
2922 $links[] = Html
::inlineScript(
2923 ResourceLoader
::makeLoaderConditionalScript(
2924 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2928 // Load embeddable private modules before any loader links
2929 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2930 // in mw.loader.implement() calls and deferred until mw.user is available
2931 $embedScripts = array( 'user.options', 'user.tokens' );
2932 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2934 // Scripts and messages "only" requests marked for top inclusion
2935 // Messages should go first
2936 $links[] = $this->makeResourceLoaderLink(
2937 $this->getModuleMessages( true, 'top' ),
2938 ResourceLoaderModule
::TYPE_MESSAGES
2940 $links[] = $this->makeResourceLoaderLink(
2941 $this->getModuleScripts( true, 'top' ),
2942 ResourceLoaderModule
::TYPE_SCRIPTS
2945 // Modules requests - let the client calculate dependencies and batch requests as it likes
2946 // Only load modules that have marked themselves for loading at the top
2947 $modules = $this->getModules( true, 'top' );
2949 $links[] = Html
::inlineScript(
2950 ResourceLoader
::makeLoaderConditionalScript(
2951 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2956 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2957 $links[] = $this->getScriptsForBottomQueue( true );
2960 return self
::getHtmlFromLoaderLinks( $links );
2964 * JS stuff to put at the 'bottom', which can either be the bottom of the
2965 * "<body>" or the bottom of the "<head>" depending on
2966 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2967 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2970 * @param bool $inHead If true, this HTML goes into the "<head>",
2971 * if false it goes into the "<body>".
2974 function getScriptsForBottomQueue( $inHead ) {
2975 // Scripts and messages "only" requests marked for bottom inclusion
2976 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2977 // Messages should go first
2979 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2980 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2981 /* $loadCall = */ $inHead
2983 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2984 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2985 /* $loadCall = */ $inHead
2988 // Modules requests - let the client calculate dependencies and batch requests as it likes
2989 // Only load modules that have marked themselves for loading at the bottom
2990 $modules = $this->getModules( true, 'bottom' );
2992 $links[] = Html
::inlineScript(
2993 ResourceLoader
::makeLoaderConditionalScript(
2994 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3000 $links[] = "\n" . $this->mScripts
;
3002 // Add site JS if enabled
3003 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3004 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3007 // Add user JS if enabled
3008 if ( $this->getConfig()->get( 'AllowUserJs' )
3009 && $this->getUser()->isLoggedIn()
3010 && $this->getTitle()
3011 && $this->getTitle()->isJsSubpage()
3012 && $this->userCanPreview()
3014 # XXX: additional security check/prompt?
3015 // We're on a preview of a JS subpage
3016 // Exclude this page from the user module in case it's in there (bug 26283)
3017 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3018 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3020 // Load the previewed JS
3021 $links[] = Html
::inlineScript( "\n"
3022 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3024 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3025 // asynchronously and may arrive *after* the inline script here. So the previewed code
3026 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3028 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3029 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3030 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3034 // Group JS is only enabled if site JS is enabled.
3035 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3036 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3039 return self
::getHtmlFromLoaderLinks( $links );
3043 * JS stuff to put at the bottom of the "<body>"
3046 function getBottomScripts() {
3047 // Optimise jQuery ready event cross-browser.
3048 // This also enforces $.isReady to be true at </body> which fixes the
3049 // mw.loader bug in Firefox with using document.write between </body>
3050 // and the DOMContentReady event (bug 47457).
3051 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3053 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3054 $html .= $this->getScriptsForBottomQueue( false );
3061 * Get the javascript config vars to include on this page
3063 * @return array Array of javascript config vars
3066 public function getJsConfigVars() {
3067 return $this->mJsConfigVars
;
3071 * Add one or more variables to be set in mw.config in JavaScript
3073 * @param string|array $keys Key or array of key/value pairs
3074 * @param mixed $value [optional] Value of the configuration variable
3076 public function addJsConfigVars( $keys, $value = null ) {
3077 if ( is_array( $keys ) ) {
3078 foreach ( $keys as $key => $value ) {
3079 $this->mJsConfigVars
[$key] = $value;
3084 $this->mJsConfigVars
[$keys] = $value;
3088 * Get an array containing the variables to be set in mw.config in JavaScript.
3090 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3091 * - in other words, page-independent/site-wide variables (without state).
3092 * You will only be adding bloat to the html page and causing page caches to
3093 * have to be purged on configuration changes.
3096 private function getJSVars() {
3101 $canonicalSpecialPageName = false; # bug 21115
3103 $title = $this->getTitle();
3104 $ns = $title->getNamespace();
3105 $canonicalNamespace = MWNamespace
::exists( $ns )
3106 ? MWNamespace
::getCanonicalName( $ns )
3107 : $title->getNsText();
3109 $sk = $this->getSkin();
3110 // Get the relevant title so that AJAX features can use the correct page name
3111 // when making API requests from certain special pages (bug 34972).
3112 $relevantTitle = $sk->getRelevantTitle();
3113 $relevantUser = $sk->getRelevantUser();
3115 if ( $ns == NS_SPECIAL
) {
3116 list( $canonicalSpecialPageName, /*...*/ ) =
3117 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3118 } elseif ( $this->canUseWikiPage() ) {
3119 $wikiPage = $this->getWikiPage();
3120 $curRevisionId = $wikiPage->getLatest();
3121 $articleId = $wikiPage->getId();
3124 $lang = $title->getPageLanguage();
3126 // Pre-process information
3127 $separatorTransTable = $lang->separatorTransformTable();
3128 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3129 $compactSeparatorTransTable = array(
3130 implode( "\t", array_keys( $separatorTransTable ) ),
3131 implode( "\t", $separatorTransTable ),
3133 $digitTransTable = $lang->digitTransformTable();
3134 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3135 $compactDigitTransTable = array(
3136 implode( "\t", array_keys( $digitTransTable ) ),
3137 implode( "\t", $digitTransTable ),
3140 $user = $this->getUser();
3143 'wgCanonicalNamespace' => $canonicalNamespace,
3144 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3145 'wgNamespaceNumber' => $title->getNamespace(),
3146 'wgPageName' => $title->getPrefixedDBkey(),
3147 'wgTitle' => $title->getText(),
3148 'wgCurRevisionId' => $curRevisionId,
3149 'wgRevisionId' => (int)$this->getRevisionId(),
3150 'wgArticleId' => $articleId,
3151 'wgIsArticle' => $this->isArticle(),
3152 'wgIsRedirect' => $title->isRedirect(),
3153 'wgAction' => Action
::getActionName( $this->getContext() ),
3154 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3155 'wgUserGroups' => $user->getEffectiveGroups(),
3156 'wgCategories' => $this->getCategories(),
3157 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3158 'wgPageContentLanguage' => $lang->getCode(),
3159 'wgPageContentModel' => $title->getContentModel(),
3160 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3161 'wgDigitTransformTable' => $compactDigitTransTable,
3162 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3163 'wgMonthNames' => $lang->getMonthNamesArray(),
3164 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3165 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3166 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3169 if ( $user->isLoggedIn() ) {
3170 $vars['wgUserId'] = $user->getId();
3171 $vars['wgUserEditCount'] = $user->getEditCount();
3172 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3173 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3174 // Get the revision ID of the oldest new message on the user's talk
3175 // page. This can be used for constructing new message alerts on
3177 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3180 if ( $wgContLang->hasVariants() ) {
3181 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3183 // Same test as SkinTemplate
3184 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3185 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3187 foreach ( $title->getRestrictionTypes() as $type ) {
3188 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3191 if ( $title->isMainPage() ) {
3192 $vars['wgIsMainPage'] = true;
3195 if ( $this->mRedirectedFrom
) {
3196 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3199 if ( $relevantUser ) {
3200 $vars['wgRelevantUserName'] = $relevantUser->getName();
3203 // Allow extensions to add their custom variables to the mw.config map.
3204 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3205 // page-dependant but site-wide (without state).
3206 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3207 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3209 // Merge in variables from addJsConfigVars last
3210 return array_merge( $vars, $this->getJsConfigVars() );
3214 * To make it harder for someone to slip a user a fake
3215 * user-JavaScript or user-CSS preview, a random token
3216 * is associated with the login session. If it's not
3217 * passed back with the preview request, we won't render
3222 public function userCanPreview() {
3223 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3224 ||
!$this->getRequest()->wasPosted()
3225 ||
!$this->getUser()->matchEditToken(
3226 $this->getRequest()->getVal( 'wpEditToken' ) )
3230 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3234 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3238 * @return array Array in format "link name or number => 'link html'".
3240 public function getHeadLinksArray() {
3244 $config = $this->getConfig();
3246 $canonicalUrl = $this->mCanonicalUrl
;
3248 $tags['meta-generator'] = Html
::element( 'meta', array(
3249 'name' => 'generator',
3250 'content' => "MediaWiki $wgVersion",
3253 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3254 if ( $p !== 'index,follow' ) {
3255 // http://www.robotstxt.org/wc/meta-user.html
3256 // Only show if it's different from the default robots policy
3257 $tags['meta-robots'] = Html
::element( 'meta', array(
3263 foreach ( $this->mMetatags
as $tag ) {
3264 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3266 $tag[0] = substr( $tag[0], 5 );
3270 $tagName = "meta-{$tag[0]}";
3271 if ( isset( $tags[$tagName] ) ) {
3272 $tagName .= $tag[1];
3274 $tags[$tagName] = Html
::element( 'meta',
3277 'content' => $tag[1]
3282 foreach ( $this->mLinktags
as $tag ) {
3283 $tags[] = Html
::element( 'link', $tag );
3286 # Universal edit button
3287 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3288 $user = $this->getUser();
3289 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3290 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3291 // Original UniversalEditButton
3292 $msg = $this->msg( 'edit' )->text();
3293 $tags['universal-edit-button'] = Html
::element( 'link', array(
3294 'rel' => 'alternate',
3295 'type' => 'application/x-wiki',
3297 'href' => $this->getTitle()->getEditURL(),
3299 // Alternate edit link
3300 $tags['alternative-edit'] = Html
::element( 'link', array(
3303 'href' => $this->getTitle()->getEditURL(),
3308 # Generally the order of the favicon and apple-touch-icon links
3309 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3310 # uses whichever one appears later in the HTML source. Make sure
3311 # apple-touch-icon is specified first to avoid this.
3312 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3313 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3314 'rel' => 'apple-touch-icon',
3315 'href' => $config->get( 'AppleTouchIcon' )
3319 if ( $config->get( 'Favicon' ) !== false ) {
3320 $tags['favicon'] = Html
::element( 'link', array(
3321 'rel' => 'shortcut icon',
3322 'href' => $config->get( 'Favicon' )
3326 # OpenSearch description link
3327 $tags['opensearch'] = Html
::element( 'link', array(
3329 'type' => 'application/opensearchdescription+xml',
3330 'href' => wfScript( 'opensearch_desc' ),
3331 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3334 if ( $config->get( 'EnableAPI' ) ) {
3335 # Real Simple Discovery link, provides auto-discovery information
3336 # for the MediaWiki API (and potentially additional custom API
3337 # support such as WordPress or Twitter-compatible APIs for a
3338 # blogging extension, etc)
3339 $tags['rsd'] = Html
::element( 'link', array(
3341 'type' => 'application/rsd+xml',
3342 // Output a protocol-relative URL here if $wgServer is protocol-relative
3343 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3344 'href' => wfExpandUrl( wfAppendQuery(
3346 array( 'action' => 'rsd' ) ),
3353 if ( !$config->get( 'DisableLangConversion' ) ) {
3354 $lang = $this->getTitle()->getPageLanguage();
3355 if ( $lang->hasVariants() ) {
3356 $variants = $lang->getVariants();
3357 foreach ( $variants as $_v ) {
3358 $tags["variant-$_v"] = Html
::element( 'link', array(
3359 'rel' => 'alternate',
3360 'hreflang' => wfBCP47( $_v ),
3361 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3365 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3366 $tags["variant-x-default"] = Html
::element( 'link', array(
3367 'rel' => 'alternate',
3368 'hreflang' => 'x-default',
3369 'href' => $this->getTitle()->getLocalURL() ) );
3374 if ( $config->get( 'RightsPage' ) ) {
3375 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3378 $copyright = $copy->getLocalURL();
3382 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3383 $copyright = $config->get( 'RightsUrl' );
3387 $tags['copyright'] = Html
::element( 'link', array(
3388 'rel' => 'copyright',
3389 'href' => $copyright )
3394 if ( $config->get( 'Feed' ) ) {
3395 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3396 # Use the page name for the title. In principle, this could
3397 # lead to issues with having the same name for different feeds
3398 # corresponding to the same page, but we can't avoid that at
3401 $tags[] = $this->feedLink(
3404 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3405 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3409 # Recent changes feed should appear on every page (except recentchanges,
3410 # that would be redundant). Put it after the per-page feed to avoid
3411 # changing existing behavior. It's still available, probably via a
3412 # menu in your browser. Some sites might have a different feed they'd
3413 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3414 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3415 # If so, use it instead.
3416 $sitename = $config->get( 'Sitename' );
3417 if ( $config->get( 'OverrideSiteFeed' ) ) {
3418 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3419 // Note, this->feedLink escapes the url.
3420 $tags[] = $this->feedLink(
3423 $this->msg( "site-{$type}-feed", $sitename )->text()
3426 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3427 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3428 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3429 $tags[] = $this->feedLink(
3431 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3432 # For grep: 'site-rss-feed', 'site-atom-feed'
3433 $this->msg( "site-{$format}-feed", $sitename )->text()
3440 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3441 if ( $canonicalUrl !== false ) {
3442 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3444 $reqUrl = $this->getRequest()->getRequestURL();
3445 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3448 if ( $canonicalUrl !== false ) {
3449 $tags[] = Html
::element( 'link', array(
3450 'rel' => 'canonical',
3451 'href' => $canonicalUrl
3459 * @return string HTML tag links to be put in the header.
3460 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3461 * OutputPage::getHeadLinksArray directly.
3463 public function getHeadLinks() {
3464 wfDeprecated( __METHOD__
, '1.24' );
3465 return implode( "\n", $this->getHeadLinksArray() );
3469 * Generate a "<link rel/>" for a feed.
3471 * @param string $type Feed type
3472 * @param string $url URL to the feed
3473 * @param string $text Value of the "title" attribute
3474 * @return string HTML fragment
3476 private function feedLink( $type, $url, $text ) {
3477 return Html
::element( 'link', array(
3478 'rel' => 'alternate',
3479 'type' => "application/$type+xml",
3486 * Add a local or specified stylesheet, with the given media options.
3487 * Meant primarily for internal use...
3489 * @param string $style URL to the file
3490 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3491 * @param string $condition For IE conditional comments, specifying an IE version
3492 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3494 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3496 // Even though we expect the media type to be lowercase, but here we
3497 // force it to lowercase to be safe.
3499 $options['media'] = $media;
3502 $options['condition'] = $condition;
3505 $options['dir'] = $dir;
3507 $this->styles
[$style] = $options;
3511 * Adds inline CSS styles
3512 * @param mixed $style_css Inline CSS
3513 * @param string $flip Set to 'flip' to flip the CSS if needed
3515 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3516 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3517 # If wanted, and the interface is right-to-left, flip the CSS
3518 $style_css = CSSJanus
::transform( $style_css, true, false );
3520 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3524 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3525 * These will be applied to various media & IE conditionals.
3529 public function buildCssLinks() {
3532 $this->getSkin()->setupSkinUserCss( $this );
3534 // Add ResourceLoader styles
3535 // Split the styles into these groups
3540 'private' => array(),
3541 'noscript' => array()
3544 $otherTags = ''; // Tags to append after the normal <link> tags
3545 $resourceLoader = $this->getResourceLoader();
3547 $moduleStyles = $this->getModuleStyles();
3549 // Per-site custom styles
3550 $moduleStyles[] = 'site';
3551 $moduleStyles[] = 'noscript';
3552 $moduleStyles[] = 'user.groups';
3554 // Per-user custom styles
3555 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3556 && $this->userCanPreview()
3558 // We're on a preview of a CSS subpage
3559 // Exclude this page from the user module in case it's in there (bug 26283)
3560 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3561 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3563 $otherTags .= $link['html'];
3565 // Load the previewed CSS
3566 // If needed, Janus it first. This is user-supplied CSS, so it's
3567 // assumed to be right for the content language directionality.
3568 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3569 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3570 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3572 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3574 // Load the user styles normally
3575 $moduleStyles[] = 'user';
3578 // Per-user preference styles
3579 $moduleStyles[] = 'user.cssprefs';
3581 foreach ( $moduleStyles as $name ) {
3582 $module = $resourceLoader->getModule( $name );
3586 $group = $module->getGroup();
3587 // Modules in groups different than the ones listed on top (see $styles assignment)
3588 // will be placed in the "other" group
3589 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3592 // We want site, private and user styles to override dynamically added
3593 // styles from modules, but we want dynamically added styles to override
3594 // statically added styles from other modules. So the order has to be
3595 // other, dynamic, site, private, user. Add statically added styles for
3597 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3598 // Add normal styles added through addStyle()/addInlineStyle() here
3599 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3600 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3601 // We use a <meta> tag with a made-up name for this because that's valid HTML
3602 $links[] = Html
::element(
3604 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3607 // Add site, private and user styles
3608 // 'private' at present only contains user.options, so put that before 'user'
3609 // Any future private modules will likely have a similar user-specific character
3610 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3611 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3612 ResourceLoaderModule
::TYPE_STYLES
3616 // Add stuff in $otherTags (previewed user CSS if applicable)
3617 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3623 public function buildCssLinksArray() {
3626 // Add any extension CSS
3627 foreach ( $this->mExtStyles
as $url ) {
3628 $this->addStyle( $url );
3630 $this->mExtStyles
= array();
3632 foreach ( $this->styles
as $file => $options ) {
3633 $link = $this->styleLink( $file, $options );
3635 $links[$file] = $link;
3642 * Generate \<link\> tags for stylesheets
3644 * @param string $style URL to the file
3645 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3646 * @return string HTML fragment
3648 protected function styleLink( $style, array $options ) {
3649 if ( isset( $options['dir'] ) ) {
3650 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3655 if ( isset( $options['media'] ) ) {
3656 $media = self
::transformCssMedia( $options['media'] );
3657 if ( is_null( $media ) ) {
3664 if ( substr( $style, 0, 1 ) == '/' ||
3665 substr( $style, 0, 5 ) == 'http:' ||
3666 substr( $style, 0, 6 ) == 'https:' ) {
3669 $config = $this->getConfig();
3670 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3673 $link = Html
::linkedStyle( $url, $media );
3675 if ( isset( $options['condition'] ) ) {
3676 $condition = htmlspecialchars( $options['condition'] );
3677 $link = "<!--[if $condition]>$link<![endif]-->";
3683 * Transform "media" attribute based on request parameters
3685 * @param string $media Current value of the "media" attribute
3686 * @return string Modified value of the "media" attribute, or null to skip
3689 public static function transformCssMedia( $media ) {
3692 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3693 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3695 // Switch in on-screen display for media testing
3697 'printable' => 'print',
3698 'handheld' => 'handheld',
3700 foreach ( $switches as $switch => $targetMedia ) {
3701 if ( $wgRequest->getBool( $switch ) ) {
3702 if ( $media == $targetMedia ) {
3704 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3705 // This regex will not attempt to understand a comma-separated media_query_list
3707 // Example supported values for $media:
3708 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3709 // Example NOT supported value for $media:
3710 // '3d-glasses, screen, print and resolution > 90dpi'
3712 // If it's a print request, we never want any kind of screen stylesheets
3713 // If it's a handheld request (currently the only other choice with a switch),
3714 // we don't want simple 'screen' but we might want screen queries that
3715 // have a max-width or something, so we'll pass all others on and let the
3716 // client do the query.
3717 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3728 * Add a wikitext-formatted message to the output.
3729 * This is equivalent to:
3731 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3733 public function addWikiMsg( /*...*/ ) {
3734 $args = func_get_args();
3735 $name = array_shift( $args );
3736 $this->addWikiMsgArray( $name, $args );
3740 * Add a wikitext-formatted message to the output.
3741 * Like addWikiMsg() except the parameters are taken as an array
3742 * instead of a variable argument list.
3744 * @param string $name
3745 * @param array $args
3747 public function addWikiMsgArray( $name, $args ) {
3748 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3752 * This function takes a number of message/argument specifications, wraps them in
3753 * some overall structure, and then parses the result and adds it to the output.
3755 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3756 * on. The subsequent arguments may either be strings, in which case they are the
3757 * message names, or arrays, in which case the first element is the message name,
3758 * and subsequent elements are the parameters to that message.
3760 * Don't use this for messages that are not in users interface language.
3764 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3768 * $wgOut->addWikiText( "<div class='error'>\n"
3769 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3771 * The newline after opening div is needed in some wikitext. See bug 19226.
3773 * @param string $wrap
3775 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3776 $msgSpecs = func_get_args();
3777 array_shift( $msgSpecs );
3778 $msgSpecs = array_values( $msgSpecs );
3780 foreach ( $msgSpecs as $n => $spec ) {
3781 if ( is_array( $spec ) ) {
3783 $name = array_shift( $args );
3784 if ( isset( $args['options'] ) ) {
3785 unset( $args['options'] );
3787 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3795 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3797 $this->addWikiText( $s );
3801 * Include jQuery core. Use this to avoid loading it multiple times
3802 * before we get a usable script loader.
3804 * @param array $modules List of jQuery modules which should be loaded
3805 * @return array The list of modules which were not loaded.
3807 * @deprecated since 1.17
3809 public function includeJQuery( array $modules = array() ) {
3814 * Enables/disables TOC, doesn't override __NOTOC__
3818 public function enableTOC( $flag = true ) {
3819 $this->mEnableTOC
= $flag;
3826 public function isTOCEnabled() {
3827 return $this->mEnableTOC
;
3831 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3835 public function enableSectionEditLinks( $flag = true ) {
3836 $this->mEnableSectionEditLinks
= $flag;
3843 public function sectionEditLinksEnabled() {
3844 return $this->mEnableSectionEditLinks
;