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 /// Should be private. Used with addMeta() which adds "<meta>"
40 var $mMetatags = array();
42 /// "<meta keywords='stuff'>" most of the time the first 10 links to an article
43 var $mKeywords = array();
45 var $mLinktags = array();
46 var $mCanonicalUrl = false;
48 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
49 var $mExtStyles = array();
51 /// Should be private - has getter and setter. Contains the HTML title
54 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
58 * Holds the debug lines that will be output as comments in page source if
59 * $wgDebugComments is enabled. See also $wgShowDebug.
60 * @deprecated since 1.20; use MWDebug class instead.
62 public $mDebugtext = '';
64 /// Should be private. Stores contents of "<title>" tag
67 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
68 var $mIsarticle = false;
71 * Should be private. Has get/set methods properly documented.
72 * Stores "article flag" toggle.
74 var $mIsArticleRelated = true;
77 * Should be private. We have to set isPrintable(). Some pages should
78 * never be printed (ex: redirections).
80 var $mPrintable = false;
83 * Should be private. We have set/get/append methods.
85 * Contains the page subtitle. Special pages usually have some links here.
86 * Don't confuse with site subtitle added by skins.
88 private $mSubtitle = array();
94 * mLastModified and mEtag are used for sending cache control.
95 * The whole caching system should probably be moved into its own class.
97 var $mLastModified = '';
100 * Should be private. No getter but used in sendCacheControl();
101 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
102 * as a unique identifier for the content. It is later used by the client
103 * to compare its cached version with the server version. Client sends
104 * headers If-Match and If-None-Match containing its locally cached ETAG value.
106 * To get more information, you will have to look at HTTP/1.1 protocol which
107 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
111 var $mCategoryLinks = array();
112 var $mCategories = array();
114 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
115 var $mLanguageLinks = array();
118 * Should be private. Used for JavaScript (pre resource loader)
119 * We should split js / css.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contains either a link to a stylesheet or inline css.
126 * Inline CSS styles. Use addInlineStyle() sparingly
128 var $mInlineStyles = '';
134 * Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 var $mPageLinkTitle = '';
139 /// Array of elements in "<head>". Parser might add its own headers!
140 var $mHeadItems = array();
142 // @todo FIXME: Next variables probably comes from the resource loader
143 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
144 var $mResourceLoader;
145 var $mJsConfigVars = array();
147 /** @todo FIXME: Is this still used ?*/
148 var $mInlineMsg = array();
150 var $mTemplateIds = array();
151 var $mImageTimeKeys = array();
153 var $mRedirectCode = '';
155 var $mFeedLinksAppendQuery = null;
157 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
158 # @see ResourceLoaderModule::$origin
159 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
160 protected $mAllowedModules = array(
161 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
165 * @EasterEgg I just love the name for this self documenting variable.
168 var $mDoNothing = false;
171 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
174 * lazy initialised, use parserOptions()
177 protected $mParserOptions = null;
180 * Handles the atom / rss links.
181 * We probably only support atom in 2011.
182 * Looks like a private variable.
183 * @see $wgAdvertisedFeedTypes
185 var $mFeedLinks = array();
187 // Gwicke work on squid caching? Roughly from 2003.
188 var $mEnableClientCache = true;
191 * Flag if output should only contain the body of the article.
194 var $mArticleBodyOnly = false;
196 var $mNewSectionLink = false;
197 var $mHideNewSectionLink = false;
200 * Comes from the parser. This was probably made to load CSS/JS only
201 * if we had "<gallery>". Used directly in CategoryPage.php
202 * Looks like resource loader can replace this.
204 var $mNoGallery = false;
206 // should be private.
207 var $mPageTitleActionText = '';
208 var $mParseWarnings = array();
210 // Cache stuff. Looks like mEnableClientCache
211 var $mSquidMaxage = 0;
214 var $mPreventClickjacking = true;
216 /// should be private. To include the variable {{REVISIONID}}
217 var $mRevisionId = null;
218 private $mRevisionTimestamp = null;
220 var $mFileVersion = null;
223 * An array of stylesheet filenames (relative from skins path), with options
224 * for CSS media, IE conditions, and RTL/LTR direction.
225 * For internal use; add settings in the skin via $this->addStyle()
227 * Style again! This seems like a code duplication since we already have
228 * mStyles. This is what makes OpenSource amazing.
230 var $styles = array();
233 * Whether jQuery is already handled.
235 protected $mJQueryDone = false;
237 private $mIndexPolicy = 'index';
238 private $mFollowPolicy = 'follow';
239 private $mVaryHeader = array(
240 'Accept-Encoding' => array( 'list-contains=gzip' ),
244 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
249 private $mRedirectedFrom = null;
252 * Additional key => value data
254 private $mProperties = array();
257 * Constructor for OutputPage. This should not be called directly.
258 * Instead a new RequestContext should be created and it will implicitly create
259 * a OutputPage tied to that context.
261 function __construct( IContextSource
$context = null ) {
262 if ( $context === null ) {
263 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
264 wfDeprecated( __METHOD__
, '1.18' );
266 $this->setContext( $context );
271 * Redirect to $url rather than displaying the normal page
273 * @param string $url URL
274 * @param string $responsecode HTTP status code
276 public function redirect( $url, $responsecode = '302' ) {
277 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
278 $this->mRedirect
= str_replace( "\n", '', $url );
279 $this->mRedirectCode
= $responsecode;
283 * Get the URL to redirect to, or an empty string if not redirect URL set
287 public function getRedirect() {
288 return $this->mRedirect
;
292 * Set the HTTP status code to send with the output.
294 * @param $statusCode Integer
296 public function setStatusCode( $statusCode ) {
297 $this->mStatusCode
= $statusCode;
301 * Add a new "<meta>" tag
302 * To add an http-equiv meta tag, precede the name with "http:"
304 * @param string $name tag name
305 * @param string $val tag value
307 function addMeta( $name, $val ) {
308 array_push( $this->mMetatags
, array( $name, $val ) );
312 * Add a keyword or a list of keywords in the page header
314 * @param string $text or array of strings
316 function addKeyword( $text ) {
317 if( is_array( $text ) ) {
318 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
320 array_push( $this->mKeywords
, $text );
325 * Add a new \<link\> tag to the page header.
327 * Note: use setCanonicalUrl() for rel=canonical.
329 * @param array $linkarr associative array of attributes.
331 function addLink( $linkarr ) {
332 array_push( $this->mLinktags
, $linkarr );
336 * Add a new \<link\> with "rel" attribute set to "meta"
338 * @param array $linkarr associative array mapping attribute names to their
339 * values, both keys and values will be escaped, and the
340 * "rel" attribute will be automatically added
342 function addMetadataLink( $linkarr ) {
343 $linkarr['rel'] = $this->getMetadataAttribute();
344 $this->addLink( $linkarr );
348 * Set the URL to be used for the <link rel=canonical>. This should be used
349 * in preference to addLink(), to avoid duplicate link tags.
351 function setCanonicalUrl( $url ) {
352 $this->mCanonicalUrl
= $url;
356 * Get the value of the "rel" attribute for metadata links
360 public function getMetadataAttribute() {
361 # note: buggy CC software only reads first "meta" link
362 static $haveMeta = false;
364 return 'alternate meta';
372 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
374 * @param string $script raw HTML
376 function addScript( $script ) {
377 $this->mScripts
.= $script . "\n";
381 * Register and add a stylesheet from an extension directory.
383 * @param string $url path to sheet. Provide either a full url (beginning
384 * with 'http', etc) or a relative path from the document root
385 * (beginning with '/'). Otherwise it behaves identically to
386 * addStyle() and draws from the /skins folder.
388 public function addExtensionStyle( $url ) {
389 array_push( $this->mExtStyles
, $url );
393 * Get all styles added by extensions
397 function getExtStyle() {
398 return $this->mExtStyles
;
402 * Add a JavaScript file out of skins/common, or a given relative path.
404 * @param string $file filename in skins/common or complete on-server path
406 * @param string $version style version of the file. Defaults to $wgStyleVersion
408 public function addScriptFile( $file, $version = null ) {
409 global $wgStylePath, $wgStyleVersion;
410 // See if $file parameter is an absolute URL or begins with a slash
411 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
414 $path = "{$wgStylePath}/common/{$file}";
416 if ( is_null( $version ) )
417 $version = $wgStyleVersion;
418 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
422 * Add a self-contained script tag with the given contents
424 * @param string $script JavaScript text, no "<script>" tags
426 public function addInlineScript( $script ) {
427 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
431 * Get all registered JS and CSS tags for the header.
435 function getScript() {
436 return $this->mScripts
. $this->getHeadItems();
440 * Filter an array of modules to remove insufficiently trustworthy members, and modules
441 * which are no longer registered (eg a page is cached before an extension is disabled)
442 * @param $modules Array
443 * @param string $position if not null, only return modules with this position
444 * @param $type string
447 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
) {
448 $resourceLoader = $this->getResourceLoader();
449 $filteredModules = array();
450 foreach( $modules as $val ) {
451 $module = $resourceLoader->getModule( $val );
452 if( $module instanceof ResourceLoaderModule
453 && $module->getOrigin() <= $this->getAllowedModules( $type )
454 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
456 $filteredModules[] = $val;
459 return $filteredModules;
463 * Get the list of modules to include on this page
465 * @param bool $filter whether to filter out insufficiently trustworthy modules
466 * @param string $position if not null, only return modules with this position
467 * @param $param string
468 * @return Array of module names
470 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
471 $modules = array_values( array_unique( $this->$param ) );
473 ?
$this->filterModules( $modules, $position )
478 * Add one or more modules recognized by the resource loader. Modules added
479 * through this function will be loaded by the resource loader when the
482 * @param $modules Mixed: module name (string) or array of module names
484 public function addModules( $modules ) {
485 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
489 * Get the list of module JS to include on this page
494 * @return array of module names
496 public function getModuleScripts( $filter = false, $position = null ) {
497 return $this->getModules( $filter, $position, 'mModuleScripts' );
501 * Add only JS of one or more modules recognized by the resource loader. Module
502 * scripts added through this function will be loaded by the resource loader when
505 * @param $modules Mixed: module name (string) or array of module names
507 public function addModuleScripts( $modules ) {
508 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
512 * Get the list of module CSS to include on this page
517 * @return Array of module names
519 public function getModuleStyles( $filter = false, $position = null ) {
520 return $this->getModules( $filter, $position, 'mModuleStyles' );
524 * Add only CSS of one or more modules recognized by the resource loader.
526 * Module styles added through this function will be added using standard link CSS
527 * tags, rather than as a combined Javascript and CSS package. Thus, they will
528 * load when JavaScript is disabled (unless CSS also happens to be disabled).
530 * @param $modules Mixed: module name (string) or array of module names
532 public function addModuleStyles( $modules ) {
533 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
537 * Get the list of module messages to include on this page
542 * @return Array of module names
544 public function getModuleMessages( $filter = false, $position = null ) {
545 return $this->getModules( $filter, $position, 'mModuleMessages' );
549 * Add only messages of one or more modules recognized by the resource loader.
550 * Module messages added through this function will be loaded by the resource
551 * loader when the page loads.
553 * @param $modules Mixed: module name (string) or array of module names
555 public function addModuleMessages( $modules ) {
556 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
560 * Get an array of head items
564 function getHeadItemsArray() {
565 return $this->mHeadItems
;
569 * Get all header items in a string
573 function getHeadItems() {
575 foreach ( $this->mHeadItems
as $item ) {
582 * Add or replace an header item to the output
584 * @param string $name item name
585 * @param string $value raw HTML
587 public function addHeadItem( $name, $value ) {
588 $this->mHeadItems
[$name] = $value;
592 * Check if the header item $name is already set
594 * @param string $name item name
597 public function hasHeadItem( $name ) {
598 return isset( $this->mHeadItems
[$name] );
602 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
604 * @param string $tag value of "ETag" header
606 function setETag( $tag ) {
611 * Set whether the output should only contain the body of the article,
612 * without any skin, sidebar, etc.
613 * Used e.g. when calling with "action=render".
615 * @param $only Boolean: whether to output only the body of the article
617 public function setArticleBodyOnly( $only ) {
618 $this->mArticleBodyOnly
= $only;
622 * Return whether the output will contain only the body of the article
626 public function getArticleBodyOnly() {
627 return $this->mArticleBodyOnly
;
631 * Set an additional output property
634 * @param string $name
635 * @param mixed $value
637 public function setProperty( $name, $value ) {
638 $this->mProperties
[$name] = $value;
642 * Get an additional output property
646 * @return mixed: Property value or null if not found
648 public function getProperty( $name ) {
649 if ( isset( $this->mProperties
[$name] ) ) {
650 return $this->mProperties
[$name];
657 * checkLastModified tells the client to use the client-cached page if
658 * possible. If successful, the OutputPage is disabled so that
659 * any future call to OutputPage->output() have no effect.
661 * Side effect: sets mLastModified for Last-Modified header
663 * @param $timestamp string
665 * @return Boolean: true iff cache-ok headers was sent.
667 public function checkLastModified( $timestamp ) {
668 global $wgCachePages, $wgCacheEpoch;
670 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
671 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
674 if( !$wgCachePages ) {
675 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
678 if( $this->getUser()->getOption( 'nocache' ) ) {
679 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
683 $timestamp = wfTimestamp( TS_MW
, $timestamp );
684 $modifiedTimes = array(
685 'page' => $timestamp,
686 'user' => $this->getUser()->getTouched(),
687 'epoch' => $wgCacheEpoch
689 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
691 $maxModified = max( $modifiedTimes );
692 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
694 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
695 if ( $clientHeader === false ) {
696 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
700 # IE sends sizes after the date like this:
701 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
702 # this breaks strtotime().
703 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
705 wfSuppressWarnings(); // E_STRICT system time bitching
706 $clientHeaderTime = strtotime( $clientHeader );
708 if ( !$clientHeaderTime ) {
709 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
712 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
716 foreach ( $modifiedTimes as $name => $value ) {
717 if ( $info !== '' ) {
720 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
723 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
724 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
725 wfDebug( __METHOD__
. ": effective Last-Modified: " .
726 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
727 if( $clientHeaderTime < $maxModified ) {
728 wfDebug( __METHOD__
. ": STALE, $info\n", false );
733 # Give a 304 response code and disable body output
734 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
735 ini_set( 'zlib.output_compression', 0 );
736 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
737 $this->sendCacheControl();
740 // Don't output a compressed blob when using ob_gzhandler;
741 // it's technically against HTTP spec and seems to confuse
742 // Firefox when the response gets split over two packets.
743 wfClearOutputBuffers();
749 * Override the last modified timestamp
751 * @param string $timestamp new timestamp, in a format readable by
754 public function setLastModified( $timestamp ) {
755 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
759 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
761 * @param string $policy the literal string to output as the contents of
762 * the meta tag. Will be parsed according to the spec and output in
766 public function setRobotPolicy( $policy ) {
767 $policy = Article
::formatRobotPolicy( $policy );
769 if( isset( $policy['index'] ) ) {
770 $this->setIndexPolicy( $policy['index'] );
772 if( isset( $policy['follow'] ) ) {
773 $this->setFollowPolicy( $policy['follow'] );
778 * Set the index policy for the page, but leave the follow policy un-
781 * @param string $policy Either 'index' or 'noindex'.
784 public function setIndexPolicy( $policy ) {
785 $policy = trim( $policy );
786 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
787 $this->mIndexPolicy
= $policy;
792 * Set the follow policy for the page, but leave the index policy un-
795 * @param string $policy either 'follow' or 'nofollow'.
798 public function setFollowPolicy( $policy ) {
799 $policy = trim( $policy );
800 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
801 $this->mFollowPolicy
= $policy;
806 * Set the new value of the "action text", this will be added to the
807 * "HTML title", separated from it with " - ".
809 * @param string $text new value of the "action text"
811 public function setPageTitleActionText( $text ) {
812 $this->mPageTitleActionText
= $text;
816 * Get the value of the "action text"
820 public function getPageTitleActionText() {
821 if ( isset( $this->mPageTitleActionText
) ) {
822 return $this->mPageTitleActionText
;
828 * "HTML title" means the contents of "<title>".
829 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
831 * @param $name string
833 public function setHTMLTitle( $name ) {
834 if ( $name instanceof Message
) {
835 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
837 $this->mHTMLtitle
= $name;
842 * Return the "HTML title", i.e. the content of the "<title>" tag.
846 public function getHTMLTitle() {
847 return $this->mHTMLtitle
;
851 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
855 public function setRedirectedFrom( $t ) {
856 $this->mRedirectedFrom
= $t;
860 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
861 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
862 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
863 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
865 * @param $name string|Message
867 public function setPageTitle( $name ) {
868 if ( $name instanceof Message
) {
869 $name = $name->setContext( $this->getContext() )->text();
872 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
873 # but leave "<i>foobar</i>" alone
874 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
875 $this->mPagetitle
= $nameWithTags;
877 # change "<i>foo&bar</i>" to "foo&bar"
878 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
882 * Return the "page title", i.e. the content of the \<h1\> tag.
886 public function getPageTitle() {
887 return $this->mPagetitle
;
891 * Set the Title object to use
893 * @param $t Title object
895 public function setTitle( Title
$t ) {
896 $this->getContext()->setTitle( $t );
900 * Replace the subtitle with $str
902 * @param string|Message $str new value of the subtitle. String should be safe HTML.
904 public function setSubtitle( $str ) {
905 $this->clearSubtitle();
906 $this->addSubtitle( $str );
910 * Add $str to the subtitle
912 * @deprecated in 1.19; use addSubtitle() instead
913 * @param string|Message $str to add to the subtitle
915 public function appendSubtitle( $str ) {
916 $this->addSubtitle( $str );
920 * Add $str to the subtitle
922 * @param string|Message $str to add to the subtitle. String should be safe HTML.
924 public function addSubtitle( $str ) {
925 if ( $str instanceof Message
) {
926 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
928 $this->mSubtitle
[] = $str;
933 * Add a subtitle containing a backlink to a page
935 * @param $title Title to link to
937 public function addBacklinkSubtitle( Title
$title ) {
939 if ( $title->isRedirect() ) {
940 $query['redirect'] = 'no';
942 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
946 * Clear the subtitles
948 public function clearSubtitle() {
949 $this->mSubtitle
= array();
957 public function getSubtitle() {
958 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
962 * Set the page as printable, i.e. it'll be displayed with with all
963 * print styles included
965 public function setPrintable() {
966 $this->mPrintable
= true;
970 * Return whether the page is "printable"
974 public function isPrintable() {
975 return $this->mPrintable
;
979 * Disable output completely, i.e. calling output() will have no effect
981 public function disable() {
982 $this->mDoNothing
= true;
986 * Return whether the output will be completely disabled
990 public function isDisabled() {
991 return $this->mDoNothing
;
995 * Show an "add new section" link?
999 public function showNewSectionLink() {
1000 return $this->mNewSectionLink
;
1004 * Forcibly hide the new section link?
1008 public function forceHideNewSectionLink() {
1009 return $this->mHideNewSectionLink
;
1013 * Add or remove feed links in the page header
1014 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1015 * for the new version
1016 * @see addFeedLink()
1018 * @param $show Boolean: true: add default feeds, false: remove all feeds
1020 public function setSyndicated( $show = true ) {
1022 $this->setFeedAppendQuery( false );
1024 $this->mFeedLinks
= array();
1029 * Add default feeds to the page header
1030 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1031 * for the new version
1032 * @see addFeedLink()
1034 * @param string $val query to append to feed links or false to output
1037 public function setFeedAppendQuery( $val ) {
1038 global $wgAdvertisedFeedTypes;
1040 $this->mFeedLinks
= array();
1042 foreach ( $wgAdvertisedFeedTypes as $type ) {
1043 $query = "feed=$type";
1044 if ( is_string( $val ) ) {
1045 $query .= '&' . $val;
1047 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1052 * Add a feed link to the page header
1054 * @param string $format feed type, should be a key of $wgFeedClasses
1055 * @param string $href URL
1057 public function addFeedLink( $format, $href ) {
1058 global $wgAdvertisedFeedTypes;
1060 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1061 $this->mFeedLinks
[$format] = $href;
1066 * Should we output feed links for this page?
1069 public function isSyndicated() {
1070 return count( $this->mFeedLinks
) > 0;
1074 * Return URLs for each supported syndication format for this page.
1075 * @return array associating format keys with URLs
1077 public function getSyndicationLinks() {
1078 return $this->mFeedLinks
;
1082 * Will currently always return null
1086 public function getFeedAppendQuery() {
1087 return $this->mFeedLinksAppendQuery
;
1091 * Set whether the displayed content is related to the source of the
1092 * corresponding article on the wiki
1093 * Setting true will cause the change "article related" toggle to true
1097 public function setArticleFlag( $v ) {
1098 $this->mIsarticle
= $v;
1100 $this->mIsArticleRelated
= $v;
1105 * Return whether the content displayed page is related to the source of
1106 * the corresponding article on the wiki
1110 public function isArticle() {
1111 return $this->mIsarticle
;
1115 * Set whether this page is related an article on the wiki
1116 * Setting false will cause the change of "article flag" toggle to false
1120 public function setArticleRelated( $v ) {
1121 $this->mIsArticleRelated
= $v;
1123 $this->mIsarticle
= false;
1128 * Return whether this page is related an article on the wiki
1132 public function isArticleRelated() {
1133 return $this->mIsArticleRelated
;
1137 * Add new language links
1139 * @param array $newLinkArray Associative array mapping language code to the page
1142 public function addLanguageLinks( $newLinkArray ) {
1143 $this->mLanguageLinks +
= $newLinkArray;
1147 * Reset the language links and add new language links
1149 * @param array $newLinkArray Associative array mapping language code to the page
1152 public function setLanguageLinks( $newLinkArray ) {
1153 $this->mLanguageLinks
= $newLinkArray;
1157 * Get the list of language links
1159 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1161 public function getLanguageLinks() {
1162 return $this->mLanguageLinks
;
1166 * Add an array of categories, with names in the keys
1168 * @param array $categories mapping category name => sort key
1170 public function addCategoryLinks( $categories ) {
1173 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1177 # Add the links to a LinkBatch
1178 $arr = array( NS_CATEGORY
=> $categories );
1179 $lb = new LinkBatch
;
1180 $lb->setArray( $arr );
1182 # Fetch existence plus the hiddencat property
1183 $dbr = wfGetDB( DB_SLAVE
);
1184 $res = $dbr->select( array( 'page', 'page_props' ),
1185 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1186 $lb->constructSet( 'page', $dbr ),
1189 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1192 # Add the results to the link cache
1193 $lb->addResultToCache( LinkCache
::singleton(), $res );
1195 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1196 $categories = array_combine(
1197 array_keys( $categories ),
1198 array_fill( 0, count( $categories ), 'normal' )
1201 # Mark hidden categories
1202 foreach ( $res as $row ) {
1203 if ( isset( $row->pp_value
) ) {
1204 $categories[$row->page_title
] = 'hidden';
1208 # Add the remaining categories to the skin
1209 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1210 foreach ( $categories as $category => $type ) {
1211 $origcategory = $category;
1212 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1213 $wgContLang->findVariantLink( $category, $title, true );
1214 if ( $category != $origcategory ) {
1215 if ( array_key_exists( $category, $categories ) ) {
1219 $text = $wgContLang->convertHtml( $title->getText() );
1220 $this->mCategories
[] = $title->getText();
1221 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1227 * Reset the category links (but not the category list) and add $categories
1229 * @param array $categories mapping category name => sort key
1231 public function setCategoryLinks( $categories ) {
1232 $this->mCategoryLinks
= array();
1233 $this->addCategoryLinks( $categories );
1237 * Get the list of category links, in a 2-D array with the following format:
1238 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1239 * hidden categories) and $link a HTML fragment with a link to the category
1244 public function getCategoryLinks() {
1245 return $this->mCategoryLinks
;
1249 * Get the list of category names this page belongs to
1251 * @return Array of strings
1253 public function getCategories() {
1254 return $this->mCategories
;
1258 * Do not allow scripts which can be modified by wiki users to load on this page;
1259 * only allow scripts bundled with, or generated by, the software.
1261 public function disallowUserJs() {
1262 $this->reduceAllowedModules(
1263 ResourceLoaderModule
::TYPE_SCRIPTS
,
1264 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1269 * Return whether user JavaScript is allowed for this page
1270 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1271 * trustworthiness is identified and enforced automagically.
1272 * Will be removed in 1.20.
1275 public function isUserJsAllowed() {
1276 wfDeprecated( __METHOD__
, '1.18' );
1277 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1281 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1282 * @see ResourceLoaderModule::$origin
1283 * @param string $type ResourceLoaderModule TYPE_ constant
1284 * @return Int ResourceLoaderModule ORIGIN_ class constant
1286 public function getAllowedModules( $type ) {
1287 if( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1288 return min( array_values( $this->mAllowedModules
) );
1290 return isset( $this->mAllowedModules
[$type] )
1291 ?
$this->mAllowedModules
[$type]
1292 : ResourceLoaderModule
::ORIGIN_ALL
;
1297 * Set the highest level of CSS/JS untrustworthiness allowed
1298 * @param $type String ResourceLoaderModule TYPE_ constant
1299 * @param $level Int ResourceLoaderModule class constant
1301 public function setAllowedModules( $type, $level ) {
1302 $this->mAllowedModules
[$type] = $level;
1306 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1307 * @param $type String
1308 * @param $level Int ResourceLoaderModule class constant
1310 public function reduceAllowedModules( $type, $level ) {
1311 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1315 * Prepend $text to the body HTML
1317 * @param string $text HTML
1319 public function prependHTML( $text ) {
1320 $this->mBodytext
= $text . $this->mBodytext
;
1324 * Append $text to the body HTML
1326 * @param string $text HTML
1328 public function addHTML( $text ) {
1329 $this->mBodytext
.= $text;
1333 * Shortcut for adding an Html::element via addHTML.
1337 * @param $element string
1338 * @param $attribs array
1339 * @param $contents string
1341 public function addElement( $element, $attribs = array(), $contents = '' ) {
1342 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1346 * Clear the body HTML
1348 public function clearHTML() {
1349 $this->mBodytext
= '';
1355 * @return String: HTML
1357 public function getHTML() {
1358 return $this->mBodytext
;
1362 * Get/set the ParserOptions object to use for wikitext parsing
1364 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1365 * current ParserOption object
1366 * @return ParserOptions object
1368 public function parserOptions( $options = null ) {
1369 if ( !$this->mParserOptions
) {
1370 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1371 $this->mParserOptions
->setEditSection( false );
1373 return wfSetVar( $this->mParserOptions
, $options );
1377 * Set the revision ID which will be seen by the wiki text parser
1378 * for things such as embedded {{REVISIONID}} variable use.
1380 * @param $revid Mixed: an positive integer, or null
1381 * @return Mixed: previous value
1383 public function setRevisionId( $revid ) {
1384 $val = is_null( $revid ) ?
null : intval( $revid );
1385 return wfSetVar( $this->mRevisionId
, $val );
1389 * Get the displayed revision ID
1393 public function getRevisionId() {
1394 return $this->mRevisionId
;
1398 * Set the timestamp of the revision which will be displayed. This is used
1399 * to avoid a extra DB call in Skin::lastModified().
1401 * @param $timestamp Mixed: string, or null
1402 * @return Mixed: previous value
1404 public function setRevisionTimestamp( $timestamp) {
1405 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1409 * Get the timestamp of displayed revision.
1410 * This will be null if not filled by setRevisionTimestamp().
1412 * @return String or null
1414 public function getRevisionTimestamp() {
1415 return $this->mRevisionTimestamp
;
1419 * Set the displayed file version
1421 * @param $file File|bool
1422 * @return Mixed: previous value
1424 public function setFileVersion( $file ) {
1426 if ( $file instanceof File
&& $file->exists() ) {
1427 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1429 return wfSetVar( $this->mFileVersion
, $val, true );
1433 * Get the displayed file version
1435 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1437 public function getFileVersion() {
1438 return $this->mFileVersion
;
1442 * Get the templates used on this page
1444 * @return Array (namespace => dbKey => revId)
1447 public function getTemplateIds() {
1448 return $this->mTemplateIds
;
1452 * Get the files used on this page
1454 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1457 public function getFileSearchOptions() {
1458 return $this->mImageTimeKeys
;
1462 * Convert wikitext to HTML and add it to the buffer
1463 * Default assumes that the current page title will be used.
1465 * @param $text String
1466 * @param $linestart Boolean: is this the start of a line?
1467 * @param $interface Boolean: is this text in the user interface language?
1469 public function addWikiText( $text, $linestart = true, $interface = true ) {
1470 $title = $this->getTitle(); // Work around E_STRICT
1472 throw new MWException( 'Title is null' );
1474 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1478 * Add wikitext with a custom Title object
1480 * @param string $text wikitext
1481 * @param $title Title object
1482 * @param $linestart Boolean: is this the start of a line?
1484 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1485 $this->addWikiTextTitle( $text, $title, $linestart );
1489 * Add wikitext with a custom Title object and tidy enabled.
1491 * @param string $text wikitext
1492 * @param $title Title object
1493 * @param $linestart Boolean: is this the start of a line?
1495 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1496 $this->addWikiTextTitle( $text, $title, $linestart, true );
1500 * Add wikitext with tidy enabled
1502 * @param string $text wikitext
1503 * @param $linestart Boolean: is this the start of a line?
1505 public function addWikiTextTidy( $text, $linestart = true ) {
1506 $title = $this->getTitle();
1507 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1511 * Add wikitext with a custom Title object
1513 * @param string $text wikitext
1514 * @param $title Title object
1515 * @param $linestart Boolean: is this the start of a line?
1516 * @param $tidy Boolean: whether to use tidy
1517 * @param $interface Boolean: whether it is an interface message
1518 * (for example disables conversion)
1520 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1523 wfProfileIn( __METHOD__
);
1525 $popts = $this->parserOptions();
1526 $oldTidy = $popts->setTidy( $tidy );
1527 $popts->setInterfaceMessage( (bool) $interface );
1529 $parserOutput = $wgParser->parse(
1530 $text, $title, $popts,
1531 $linestart, true, $this->mRevisionId
1534 $popts->setTidy( $oldTidy );
1536 $this->addParserOutput( $parserOutput );
1538 wfProfileOut( __METHOD__
);
1542 * Add a ParserOutput object, but without Html
1544 * @param $parserOutput ParserOutput object
1546 public function addParserOutputNoText( &$parserOutput ) {
1547 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1548 $this->addCategoryLinks( $parserOutput->getCategories() );
1549 $this->mNewSectionLink
= $parserOutput->getNewSection();
1550 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1552 $this->mParseWarnings
= $parserOutput->getWarnings();
1553 if ( !$parserOutput->isCacheable() ) {
1554 $this->enableClientCache( false );
1556 $this->mNoGallery
= $parserOutput->getNoGallery();
1557 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1558 $this->addModules( $parserOutput->getModules() );
1559 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1560 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1561 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1563 // Template versioning...
1564 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1565 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1566 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1568 $this->mTemplateIds
[$ns] = $dbks;
1571 // File versioning...
1572 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1573 $this->mImageTimeKeys
[$dbk] = $data;
1576 // Hooks registered in the object
1577 global $wgParserOutputHooks;
1578 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1579 list( $hookName, $data ) = $hookInfo;
1580 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1581 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1585 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1589 * Add a ParserOutput object
1591 * @param $parserOutput ParserOutput
1593 function addParserOutput( &$parserOutput ) {
1594 $this->addParserOutputNoText( $parserOutput );
1595 $text = $parserOutput->getText();
1596 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1597 $this->addHTML( $text );
1601 * Add the output of a QuickTemplate to the output buffer
1603 * @param $template QuickTemplate
1605 public function addTemplate( &$template ) {
1607 $template->execute();
1608 $this->addHTML( ob_get_contents() );
1613 * Parse wikitext and return the HTML.
1615 * @param $text String
1616 * @param $linestart Boolean: is this the start of a line?
1617 * @param $interface Boolean: use interface language ($wgLang instead of
1618 * $wgContLang) while parsing language sensitive magic
1619 * words like GRAMMAR and PLURAL. This also disables
1620 * LanguageConverter.
1621 * @param $language Language object: target language object, will override
1623 * @throws MWException
1624 * @return String: HTML
1626 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1629 if( is_null( $this->getTitle() ) ) {
1630 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1633 $popts = $this->parserOptions();
1635 $popts->setInterfaceMessage( true );
1637 if ( $language !== null ) {
1638 $oldLang = $popts->setTargetLanguage( $language );
1641 $parserOutput = $wgParser->parse(
1642 $text, $this->getTitle(), $popts,
1643 $linestart, true, $this->mRevisionId
1647 $popts->setInterfaceMessage( false );
1649 if ( $language !== null ) {
1650 $popts->setTargetLanguage( $oldLang );
1653 return $parserOutput->getText();
1657 * Parse wikitext, strip paragraphs, and return the HTML.
1659 * @param $text String
1660 * @param $linestart Boolean: is this the start of a line?
1661 * @param $interface Boolean: use interface language ($wgLang instead of
1662 * $wgContLang) while parsing language sensitive magic
1663 * words like GRAMMAR and PLURAL
1664 * @return String: HTML
1666 public function parseInline( $text, $linestart = true, $interface = false ) {
1667 $parsed = $this->parse( $text, $linestart, $interface );
1670 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1678 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1680 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1682 public function setSquidMaxage( $maxage ) {
1683 $this->mSquidMaxage
= $maxage;
1687 * Use enableClientCache(false) to force it to send nocache headers
1689 * @param $state bool
1693 public function enableClientCache( $state ) {
1694 return wfSetVar( $this->mEnableClientCache
, $state );
1698 * Get the list of cookies that will influence on the cache
1702 function getCacheVaryCookies() {
1703 global $wgCookiePrefix, $wgCacheVaryCookies;
1705 if ( $cookies === null ) {
1706 $cookies = array_merge(
1708 "{$wgCookiePrefix}Token",
1709 "{$wgCookiePrefix}LoggedOut",
1714 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1720 * Check if the request has a cache-varying cookie header
1721 * If it does, it's very important that we don't allow public caching
1725 function haveCacheVaryCookies() {
1726 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1727 if ( $cookieHeader === false ) {
1730 $cvCookies = $this->getCacheVaryCookies();
1731 foreach ( $cvCookies as $cookieName ) {
1732 # Check for a simple string match, like the way squid does it
1733 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1734 wfDebug( __METHOD__
. ": found $cookieName\n" );
1738 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1743 * Add an HTTP header that will influence on the cache
1745 * @param string $header header name
1746 * @param $option Array|null
1747 * @todo FIXME: Document the $option parameter; it appears to be for
1748 * X-Vary-Options but what format is acceptable?
1750 public function addVaryHeader( $header, $option = null ) {
1751 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1752 $this->mVaryHeader
[$header] = (array)$option;
1753 } elseif( is_array( $option ) ) {
1754 if( is_array( $this->mVaryHeader
[$header] ) ) {
1755 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1757 $this->mVaryHeader
[$header] = $option;
1760 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1764 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1765 * such as Accept-Encoding or Cookie
1769 public function getVaryHeader() {
1770 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1774 * Get a complete X-Vary-Options header
1778 public function getXVO() {
1779 $cvCookies = $this->getCacheVaryCookies();
1781 $cookiesOption = array();
1782 foreach ( $cvCookies as $cookieName ) {
1783 $cookiesOption[] = 'string-contains=' . $cookieName;
1785 $this->addVaryHeader( 'Cookie', $cookiesOption );
1788 foreach( $this->mVaryHeader
as $header => $option ) {
1789 $newheader = $header;
1790 if ( is_array( $option ) && count( $option ) > 0 ) {
1791 $newheader .= ';' . implode( ';', $option );
1793 $headers[] = $newheader;
1795 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1801 * bug 21672: Add Accept-Language to Vary and XVO headers
1802 * if there's no 'variant' parameter existed in GET.
1805 * /w/index.php?title=Main_page should always be served; but
1806 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1808 function addAcceptLanguage() {
1809 $lang = $this->getTitle()->getPageLanguage();
1810 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1811 $variants = $lang->getVariants();
1812 $aloption = array();
1813 foreach ( $variants as $variant ) {
1814 if( $variant === $lang->getCode() ) {
1817 $aloption[] = 'string-contains=' . $variant;
1819 // IE and some other browsers use BCP 47 standards in
1820 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1821 // We should handle these too.
1822 $variantBCP47 = wfBCP47( $variant );
1823 if ( $variantBCP47 !== $variant ) {
1824 $aloption[] = 'string-contains=' . $variantBCP47;
1828 $this->addVaryHeader( 'Accept-Language', $aloption );
1833 * Set a flag which will cause an X-Frame-Options header appropriate for
1834 * edit pages to be sent. The header value is controlled by
1835 * $wgEditPageFrameOptions.
1837 * This is the default for special pages. If you display a CSRF-protected
1838 * form on an ordinary view page, then you need to call this function.
1840 * @param $enable bool
1842 public function preventClickjacking( $enable = true ) {
1843 $this->mPreventClickjacking
= $enable;
1847 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1848 * This can be called from pages which do not contain any CSRF-protected
1851 public function allowClickjacking() {
1852 $this->mPreventClickjacking
= false;
1856 * Get the X-Frame-Options header value (without the name part), or false
1857 * if there isn't one. This is used by Skin to determine whether to enable
1858 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1862 public function getFrameOptions() {
1863 global $wgBreakFrames, $wgEditPageFrameOptions;
1864 if ( $wgBreakFrames ) {
1866 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1867 return $wgEditPageFrameOptions;
1873 * Send cache control HTTP headers
1875 public function sendCacheControl() {
1876 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1878 $response = $this->getRequest()->response();
1879 if ( $wgUseETag && $this->mETag
) {
1880 $response->header( "ETag: $this->mETag" );
1883 $this->addVaryHeader( 'Cookie' );
1884 $this->addAcceptLanguage();
1886 # don't serve compressed data to clients who can't handle it
1887 # maintain different caches for logged-in users and non-logged in ones
1888 $response->header( $this->getVaryHeader() );
1891 # Add an X-Vary-Options header for Squid with Wikimedia patches
1892 $response->header( $this->getXVO() );
1895 if( $this->mEnableClientCache
) {
1897 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1898 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1902 # We'll purge the proxy cache explicitly, but require end user agents
1903 # to revalidate against the proxy on each visit.
1904 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1905 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1906 # start with a shorter timeout for initial testing
1907 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1908 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
1909 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1911 # We'll purge the proxy cache for anons explicitly, but require end user agents
1912 # to revalidate against the proxy on each visit.
1913 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1914 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1915 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1916 # start with a shorter timeout for initial testing
1917 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1918 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0' );
1921 # We do want clients to cache if they can, but they *must* check for updates
1922 # on revisiting the page.
1923 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1924 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1925 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1927 if( $this->mLastModified
) {
1928 $response->header( "Last-Modified: {$this->mLastModified}" );
1931 wfDebug( __METHOD__
. ": no caching **\n", false );
1933 # In general, the absence of a last modified header should be enough to prevent
1934 # the client from using its cache. We send a few other things just to make sure.
1935 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1936 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1937 $response->header( 'Pragma: no-cache' );
1942 * Get the message associated with the HTTP response code $code
1944 * @param $code Integer: status code
1945 * @return String or null: message or null if $code is not in the list of
1948 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1950 public static function getStatusMessage( $code ) {
1951 wfDeprecated( __METHOD__
, '1.18' );
1952 return HttpStatus
::getMessage( $code );
1956 * Finally, all the text has been munged and accumulated into
1957 * the object, let's actually output it:
1959 public function output() {
1960 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1962 if( $this->mDoNothing
) {
1966 wfProfileIn( __METHOD__
);
1968 $response = $this->getRequest()->response();
1970 if ( $this->mRedirect
!= '' ) {
1971 # Standards require redirect URLs to be absolute
1972 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1974 $redirect = $this->mRedirect
;
1975 $code = $this->mRedirectCode
;
1977 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1978 if( $code == '301' ||
$code == '303' ) {
1979 if( !$wgDebugRedirects ) {
1980 $message = HttpStatus
::getMessage( $code );
1981 $response->header( "HTTP/1.1 $code $message" );
1983 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1985 if ( $wgVaryOnXFP ) {
1986 $this->addVaryHeader( 'X-Forwarded-Proto' );
1988 $this->sendCacheControl();
1990 $response->header( "Content-Type: text/html; charset=utf-8" );
1991 if( $wgDebugRedirects ) {
1992 $url = htmlspecialchars( $redirect );
1993 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1994 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1995 print "</body>\n</html>\n";
1997 $response->header( 'Location: ' . $redirect );
2001 wfProfileOut( __METHOD__
);
2003 } elseif ( $this->mStatusCode
) {
2004 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2006 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2010 # Buffer output; final headers may depend on later processing
2013 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2014 $response->header( 'Content-language: ' . $wgLanguageCode );
2016 // Prevent framing, if requested
2017 $frameOptions = $this->getFrameOptions();
2018 if ( $frameOptions ) {
2019 $response->header( "X-Frame-Options: $frameOptions" );
2022 if ( $this->mArticleBodyOnly
) {
2023 $this->out( $this->mBodytext
);
2025 $this->addDefaultModules();
2027 $sk = $this->getSkin();
2029 // Hook that allows last minute changes to the output page, e.g.
2030 // adding of CSS or Javascript by extensions.
2031 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2033 wfProfileIn( 'Output-skin' );
2035 wfProfileOut( 'Output-skin' );
2038 // This hook allows last minute changes to final overall output by modifying output buffer
2039 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2041 $this->sendCacheControl();
2045 wfProfileOut( __METHOD__
);
2049 * Actually output something with print().
2051 * @param string $ins the string to output
2053 public function out( $ins ) {
2058 * Produce a "user is blocked" page.
2059 * @deprecated since 1.18
2061 function blockedPage() {
2062 throw new UserBlockedError( $this->getUser()->mBlock
);
2066 * Prepare this object to display an error page; disable caching and
2067 * indexing, clear the current text and redirect, set the page's title
2068 * and optionally an custom HTML title (content of the "<title>" tag).
2070 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2071 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2072 * optional, if not passed the "<title>" attribute will be
2073 * based on $pageTitle
2075 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2076 $this->setPageTitle( $pageTitle );
2077 if ( $htmlTitle !== false ) {
2078 $this->setHTMLTitle( $htmlTitle );
2080 $this->setRobotPolicy( 'noindex,nofollow' );
2081 $this->setArticleRelated( false );
2082 $this->enableClientCache( false );
2083 $this->mRedirect
= '';
2084 $this->clearSubtitle();
2089 * Output a standard error page
2091 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2092 * showErrorPage( 'titlemsg', $messageObject );
2093 * showErrorPage( $titleMessageObj, $messageObject );
2095 * @param $title Mixed: message key (string) for page title, or a Message object
2096 * @param $msg Mixed: message key (string) for page text, or a Message object
2097 * @param array $params message parameters; ignored if $msg is a Message object
2099 public function showErrorPage( $title, $msg, $params = array() ) {
2100 if( !$title instanceof Message
) {
2101 $title = $this->msg( $title );
2104 $this->prepareErrorPage( $title );
2106 if ( $msg instanceof Message
) {
2107 $this->addHTML( $msg->parseAsBlock() );
2109 $this->addWikiMsgArray( $msg, $params );
2112 $this->returnToMain();
2116 * Output a standard permission error page
2118 * @param array $errors error message keys
2119 * @param string $action action that was denied or null if unknown
2121 public function showPermissionsErrorPage( $errors, $action = null ) {
2122 // For some action (read, edit, create and upload), display a "login to do this action"
2123 // error if all of the following conditions are met:
2124 // 1. the user is not logged in
2125 // 2. the only error is insufficient permissions (i.e. no block or something else)
2126 // 3. the error can be avoided simply by logging in
2127 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2128 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2129 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2130 && ( User
::groupHasPermission( 'user', $action )
2131 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2133 $displayReturnto = null;
2135 # Due to bug 32276, if a user does not have read permissions,
2136 # $this->getTitle() will just give Special:Badtitle, which is
2137 # not especially useful as a returnto parameter. Use the title
2138 # from the request instead, if there was one.
2139 $request = $this->getRequest();
2140 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2141 if ( $action == 'edit' ) {
2142 $msg = 'whitelistedittext';
2143 $displayReturnto = $returnto;
2144 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2145 $msg = 'nocreatetext';
2146 } elseif ( $action == 'upload' ) {
2147 $msg = 'uploadnologintext';
2149 $msg = 'loginreqpagetext';
2150 $displayReturnto = Title
::newMainPage();
2156 $query['returnto'] = $returnto->getPrefixedText();
2158 if ( !$request->wasPosted() ) {
2159 $returntoquery = $request->getValues();
2160 unset( $returntoquery['title'] );
2161 unset( $returntoquery['returnto'] );
2162 unset( $returntoquery['returntoquery'] );
2163 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2166 $loginLink = Linker
::linkKnown(
2167 SpecialPage
::getTitleFor( 'Userlogin' ),
2168 $this->msg( 'loginreqlink' )->escaped(),
2173 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2174 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2176 # Don't return to a page the user can't read otherwise
2177 # we'll end up in a pointless loop
2178 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2179 $this->returnToMain( null, $displayReturnto );
2182 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2183 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2188 * Display an error page indicating that a given version of MediaWiki is
2189 * required to use it
2191 * @param $version Mixed: the version of MediaWiki needed to use the page
2193 public function versionRequired( $version ) {
2194 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2196 $this->addWikiMsg( 'versionrequiredtext', $version );
2197 $this->returnToMain();
2201 * Display an error page noting that a given permission bit is required.
2202 * @deprecated since 1.18, just throw the exception directly
2203 * @param string $permission key required
2204 * @throws PermissionsError
2206 public function permissionRequired( $permission ) {
2207 throw new PermissionsError( $permission );
2211 * Produce the stock "please login to use the wiki" page
2213 * @deprecated in 1.19; throw the exception directly
2215 public function loginToUse() {
2216 throw new PermissionsError( 'read' );
2220 * Format a list of error messages
2222 * @param array $errors of arrays returned by Title::getUserPermissionsErrors
2223 * @param string $action action that was denied or null if unknown
2224 * @return String: the wikitext error-messages, formatted into a list.
2226 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2227 if ( $action == null ) {
2228 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2230 $action_desc = $this->msg( "action-$action" )->plain();
2232 'permissionserrorstext-withaction',
2235 )->plain() . "\n\n";
2238 if ( count( $errors ) > 1 ) {
2239 $text .= '<ul class="permissions-errors">' . "\n";
2241 foreach( $errors as $error ) {
2243 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2248 $text .= "<div class=\"permissions-errors\">\n" .
2249 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2257 * Display a page stating that the Wiki is in read-only mode,
2258 * and optionally show the source of the page that the user
2259 * was trying to edit. Should only be called (for this
2260 * purpose) after wfReadOnly() has returned true.
2262 * For historical reasons, this function is _also_ used to
2263 * show the error message when a user tries to edit a page
2264 * they are not allowed to edit. (Unless it's because they're
2265 * blocked, then we show blockedPage() instead.) In this
2266 * case, the second parameter should be set to true and a list
2267 * of reasons supplied as the third parameter.
2269 * @todo Needs to be split into multiple functions.
2271 * @param $source String: source code to show (or null).
2272 * @param $protected Boolean: is this a permissions error?
2273 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2274 * @param $action String: action that was denied or null if unknown
2275 * @throws ReadOnlyError
2277 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2278 $this->setRobotPolicy( 'noindex,nofollow' );
2279 $this->setArticleRelated( false );
2281 // If no reason is given, just supply a default "I can't let you do
2282 // that, Dave" message. Should only occur if called by legacy code.
2283 if ( $protected && empty( $reasons ) ) {
2284 $reasons[] = array( 'badaccess-group0' );
2287 if ( !empty( $reasons ) ) {
2288 // Permissions error
2290 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2291 $this->addBacklinkSubtitle( $this->getTitle() );
2293 $this->setPageTitle( $this->msg( 'badaccess' ) );
2295 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2297 // Wiki is read only
2298 throw new ReadOnlyError
;
2301 // Show source, if supplied
2302 if( is_string( $source ) ) {
2303 $this->addWikiMsg( 'viewsourcetext' );
2305 $pageLang = $this->getTitle()->getPageLanguage();
2307 'id' => 'wpTextbox1',
2308 'name' => 'wpTextbox1',
2309 'cols' => $this->getUser()->getOption( 'cols' ),
2310 'rows' => $this->getUser()->getOption( 'rows' ),
2311 'readonly' => 'readonly',
2312 'lang' => $pageLang->getHtmlCode(),
2313 'dir' => $pageLang->getDir(),
2315 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2317 // Show templates used by this article
2318 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2319 $this->addHTML( "<div class='templatesUsed'>
2325 # If the title doesn't exist, it's fairly pointless to print a return
2326 # link to it. After all, you just tried editing it and couldn't, so
2327 # what's there to do there?
2328 if( $this->getTitle()->exists() ) {
2329 $this->returnToMain( null, $this->getTitle() );
2334 * Turn off regular page output and return an error response
2335 * for when rate limiting has triggered.
2337 public function rateLimited() {
2338 throw new ThrottledError
;
2342 * Show a warning about slave lag
2344 * If the lag is higher than $wgSlaveLagCritical seconds,
2345 * then the warning is a bit more obvious. If the lag is
2346 * lower than $wgSlaveLagWarning, then no warning is shown.
2348 * @param $lag Integer: slave lag
2350 public function showLagWarning( $lag ) {
2351 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2352 if( $lag >= $wgSlaveLagWarning ) {
2353 $message = $lag < $wgSlaveLagCritical
2356 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2357 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2361 public function showFatalError( $message ) {
2362 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2364 $this->addHTML( $message );
2367 public function showUnexpectedValueError( $name, $val ) {
2368 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2371 public function showFileCopyError( $old, $new ) {
2372 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2375 public function showFileRenameError( $old, $new ) {
2376 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2379 public function showFileDeleteError( $name ) {
2380 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2383 public function showFileNotFoundError( $name ) {
2384 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2388 * Add a "return to" link pointing to a specified title
2390 * @param $title Title to link
2391 * @param array $query query string parameters
2392 * @param string $text text of the link (input is not escaped)
2393 * @param $options Options array to pass to Linker
2395 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2396 if( in_array( 'http', $options ) ) {
2397 $proto = PROTO_HTTP
;
2398 } elseif( in_array( 'https', $options ) ) {
2399 $proto = PROTO_HTTPS
;
2401 $proto = PROTO_RELATIVE
;
2404 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2405 $link = $this->msg( 'returnto' )->rawParams(
2406 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2407 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2411 * Add a "return to" link pointing to a specified title,
2412 * or the title indicated in the request, or else the main page
2415 * @param $returnto Title or String to return to
2416 * @param string $returntoquery query string for the return to link
2418 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2419 if ( $returnto == null ) {
2420 $returnto = $this->getRequest()->getText( 'returnto' );
2423 if ( $returntoquery == null ) {
2424 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2427 if ( $returnto === '' ) {
2428 $returnto = Title
::newMainPage();
2431 if ( is_object( $returnto ) ) {
2432 $titleObj = $returnto;
2434 $titleObj = Title
::newFromText( $returnto );
2436 if ( !is_object( $titleObj ) ) {
2437 $titleObj = Title
::newMainPage();
2440 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2444 * @param $sk Skin The given Skin
2445 * @param $includeStyle Boolean: unused
2446 * @return String: The doctype, opening "<html>", and head element.
2448 public function headElement( Skin
$sk, $includeStyle = true ) {
2451 $userdir = $this->getLanguage()->getDir();
2452 $sitedir = $wgContLang->getDir();
2454 if ( $sk->commonPrintStylesheet() ) {
2455 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2458 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2460 if ( $this->getHTMLTitle() == '' ) {
2461 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2464 $openHead = Html
::openElement( 'head' );
2466 # Don't bother with the newline if $head == ''
2467 $ret .= "$openHead\n";
2470 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2472 $ret .= implode( "\n", array(
2473 $this->getHeadLinks( null, true ),
2474 $this->buildCssLinks(),
2475 $this->getHeadScripts(),
2476 $this->getHeadItems()
2479 $closeHead = Html
::closeElement( 'head' );
2481 $ret .= "$closeHead\n";
2484 $bodyAttrs = array();
2486 # Classes for LTR/RTL directionality support
2487 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2489 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2490 # A <body> class is probably not the best way to do this . . .
2491 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2493 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2494 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2495 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2497 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2498 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2500 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2506 * Add the default ResourceLoader modules to this object
2508 private function addDefaultModules() {
2509 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2510 $wgAjaxWatch, $wgResponsiveImages;
2512 // Add base resources
2513 $this->addModules( array(
2515 'mediawiki.page.startup',
2516 'mediawiki.page.ready',
2518 if ( $wgIncludeLegacyJavaScript ) {
2519 $this->addModules( 'mediawiki.legacy.wikibits' );
2522 if ( $wgPreloadJavaScriptMwUtil ) {
2523 $this->addModules( 'mediawiki.util' );
2526 MWDebug
::addModules( $this );
2528 // Add various resources if required
2530 $this->addModules( 'mediawiki.legacy.ajax' );
2532 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2534 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2535 $this->addModules( 'mediawiki.page.watch.ajax' );
2538 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2539 $this->addModules( 'mediawiki.searchSuggest' );
2543 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2544 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2547 # Crazy edit-on-double-click stuff
2548 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2549 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2552 // Support for high-density display images
2553 if ( $wgResponsiveImages ) {
2554 $this->addModules( 'mediawiki.hidpi' );
2559 * Get a ResourceLoader object associated with this OutputPage
2561 * @return ResourceLoader
2563 public function getResourceLoader() {
2564 if ( is_null( $this->mResourceLoader
) ) {
2565 $this->mResourceLoader
= new ResourceLoader();
2567 return $this->mResourceLoader
;
2572 * @param $modules Array/string with the module name(s)
2573 * @param string $only ResourceLoaderModule TYPE_ class constant
2574 * @param $useESI boolean
2575 * @param array $extraQuery with extra query parameters to add to each request. array( param => value )
2576 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2577 * @return string html "<script>" and "<style>" tags
2579 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2580 global $wgResourceLoaderUseESI;
2582 $modules = (array) $modules;
2584 if ( !count( $modules ) ) {
2588 if ( count( $modules ) > 1 ) {
2589 // Remove duplicate module requests
2590 $modules = array_unique( $modules );
2591 // Sort module names so requests are more uniform
2594 if ( ResourceLoader
::inDebugMode() ) {
2595 // Recursively call us for every item
2597 foreach ( $modules as $name ) {
2598 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2604 // Create keyed-by-group list of module objects from modules list
2606 $resourceLoader = $this->getResourceLoader();
2607 foreach ( $modules as $name ) {
2608 $module = $resourceLoader->getModule( $name );
2609 # Check that we're allowed to include this module on this page
2611 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2612 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2613 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2614 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2620 $group = $module->getGroup();
2621 if ( !isset( $groups[$group] ) ) {
2622 $groups[$group] = array();
2624 $groups[$group][$name] = $module;
2628 foreach ( $groups as $group => $grpModules ) {
2629 // Special handling for user-specific groups
2631 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2632 $user = $this->getUser()->getName();
2635 // Create a fake request based on the one we are about to make so modules return
2636 // correct timestamp and emptiness data
2637 $query = ResourceLoader
::makeLoaderQuery(
2638 array(), // modules; not determined yet
2639 $this->getLanguage()->getCode(),
2640 $this->getSkin()->getSkinName(),
2642 null, // version; not determined yet
2643 ResourceLoader
::inDebugMode(),
2644 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2645 $this->isPrintable(),
2646 $this->getRequest()->getBool( 'handheld' ),
2649 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2650 // Extract modules that know they're empty
2651 $emptyModules = array ();
2652 foreach ( $grpModules as $key => $module ) {
2653 if ( $module->isKnownEmpty( $context ) ) {
2654 $emptyModules[$key] = 'ready';
2655 unset( $grpModules[$key] );
2658 // Inline empty modules: since they're empty, just mark them as 'ready'
2659 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2660 // If we're only getting the styles, we don't need to do anything for empty modules.
2661 $links .= Html
::inlineScript(
2663 ResourceLoader
::makeLoaderConditionalScript(
2665 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2672 // If there are no modules left, skip this group
2673 if ( count( $grpModules ) === 0 ) {
2677 // Inline private modules. These can't be loaded through load.php for security
2678 // reasons, see bug 34907. Note that these modules should be loaded from
2679 // getHeadScripts() before the first loader call. Otherwise other modules can't
2680 // properly use them as dependencies (bug 30914)
2681 if ( $group === 'private' ) {
2682 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2683 $links .= Html
::inlineStyle(
2684 $resourceLoader->makeModuleResponse( $context, $grpModules )
2687 $links .= Html
::inlineScript(
2688 ResourceLoader
::makeLoaderConditionalScript(
2689 $resourceLoader->makeModuleResponse( $context, $grpModules )
2696 // Special handling for the user group; because users might change their stuff
2697 // on-wiki like user pages, or user preferences; we need to find the highest
2698 // timestamp of these user-changeable modules so we can ensure cache misses on change
2699 // This should NOT be done for the site group (bug 27564) because anons get that too
2700 // and we shouldn't be putting timestamps in Squid-cached HTML
2702 if ( $group === 'user' ) {
2703 // Get the maximum timestamp
2705 foreach ( $grpModules as $module ) {
2706 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2708 // Add a version parameter so cache will break when things change
2709 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2712 $url = ResourceLoader
::makeLoaderURL(
2713 array_keys( $grpModules ),
2714 $this->getLanguage()->getCode(),
2715 $this->getSkin()->getSkinName(),
2718 ResourceLoader
::inDebugMode(),
2719 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2720 $this->isPrintable(),
2721 $this->getRequest()->getBool( 'handheld' ),
2724 if ( $useESI && $wgResourceLoaderUseESI ) {
2725 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2726 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2727 $link = Html
::inlineStyle( $esi );
2729 $link = Html
::inlineScript( $esi );
2732 // Automatically select style/script elements
2733 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2734 $link = Html
::linkedStyle( $url );
2735 } else if ( $loadCall ) {
2736 $link = Html
::inlineScript(
2737 ResourceLoader
::makeLoaderConditionalScript(
2738 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2742 $link = Html
::linkedScript( $url );
2746 if( $group == 'noscript' ) {
2747 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2749 $links .= $link . "\n";
2756 * JS stuff to put in the "<head>". This is the startup module, config
2757 * vars and modules marked with position 'top'
2759 * @return String: HTML fragment
2761 function getHeadScripts() {
2762 global $wgResourceLoaderExperimentalAsyncLoading;
2764 // Startup - this will immediately load jquery and mediawiki modules
2765 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2767 // Load config before anything else
2768 $scripts .= Html
::inlineScript(
2769 ResourceLoader
::makeLoaderConditionalScript(
2770 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2774 // Load embeddable private modules before any loader links
2775 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2776 // in mw.loader.implement() calls and deferred until mw.user is available
2777 $embedScripts = array( 'user.options', 'user.tokens' );
2778 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2780 // Script and Messages "only" requests marked for top inclusion
2781 // Messages should go first
2782 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2783 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2785 // Modules requests - let the client calculate dependencies and batch requests as it likes
2786 // Only load modules that have marked themselves for loading at the top
2787 $modules = $this->getModules( true, 'top' );
2789 $scripts .= Html
::inlineScript(
2790 ResourceLoader
::makeLoaderConditionalScript(
2791 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2796 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2797 $scripts .= $this->getScriptsForBottomQueue( true );
2804 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2805 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2806 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2807 * user preferences, site JS and user JS
2809 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2812 function getScriptsForBottomQueue( $inHead ) {
2813 global $wgUseSiteJs, $wgAllowUserJs;
2815 // Script and Messages "only" requests marked for bottom inclusion
2816 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2817 // Messages should go first
2818 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2819 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2820 /* $loadCall = */ $inHead
2822 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2823 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2824 /* $loadCall = */ $inHead
2827 // Modules requests - let the client calculate dependencies and batch requests as it likes
2828 // Only load modules that have marked themselves for loading at the bottom
2829 $modules = $this->getModules( true, 'bottom' );
2831 $scripts .= Html
::inlineScript(
2832 ResourceLoader
::makeLoaderConditionalScript(
2833 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2839 $scripts .= "\n" . $this->mScripts
;
2841 $defaultModules = array();
2843 // Add site JS if enabled
2844 if ( $wgUseSiteJs ) {
2845 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2846 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2848 $defaultModules['site'] = 'loading';
2850 // The wiki is configured to not allow a site module.
2851 $defaultModules['site'] = 'missing';
2854 // Add user JS if enabled
2855 if ( $wgAllowUserJs ) {
2856 if ( $this->getUser()->isLoggedIn() ) {
2857 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2858 # XXX: additional security check/prompt?
2859 // We're on a preview of a JS subpage
2860 // Exclude this page from the user module in case it's in there (bug 26283)
2861 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2862 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2864 // Load the previewed JS
2865 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2866 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2867 // asynchronously and may arrive *after* the inline script here. So the previewed code
2868 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2870 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2871 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2872 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2875 $defaultModules['user'] = 'loading';
2877 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2878 // blocking default gadgets that might depend on it. Although arguably default-enabled
2879 // gadgets should not depend on the user module, it's harmless and less error-prone to
2880 // handle this case.
2881 $defaultModules['user'] = 'ready';
2885 $defaultModules['user'] = 'missing';
2888 // Group JS is only enabled if site JS is enabled.
2889 if ( $wgUseSiteJs ) {
2890 if ( $this->getUser()->isLoggedIn() ) {
2891 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2892 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2894 $defaultModules['user.groups'] = 'loading';
2896 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2897 // avoid blocking gadgets that might depend upon the module.
2898 $defaultModules['user.groups'] = 'ready';
2901 // Site (and group JS) disabled
2902 $defaultModules['user.groups'] = 'missing';
2907 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2908 foreach ( $defaultModules as $m => $state ) {
2909 if ( $state == 'loading' ) {
2910 unset( $defaultModules[$m] );
2914 if ( count( $defaultModules ) > 0 ) {
2915 $loaderInit = Html
::inlineScript(
2916 ResourceLoader
::makeLoaderConditionalScript(
2917 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2921 return $loaderInit . $scripts;
2925 * JS stuff to put at the bottom of the "<body>"
2928 function getBottomScripts() {
2929 global $wgResourceLoaderExperimentalAsyncLoading;
2930 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2931 return $this->getScriptsForBottomQueue( false );
2938 * Add one or more variables to be set in mw.config in JavaScript.
2940 * @param $keys {String|Array} Key or array of key/value pairs.
2941 * @param $value {Mixed} [optional] Value of the configuration variable.
2943 public function addJsConfigVars( $keys, $value = null ) {
2944 if ( is_array( $keys ) ) {
2945 foreach ( $keys as $key => $value ) {
2946 $this->mJsConfigVars
[$key] = $value;
2951 $this->mJsConfigVars
[$keys] = $value;
2955 * Get an array containing the variables to be set in mw.config in JavaScript.
2957 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2958 * This is only public until that function is removed. You have been warned.
2960 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2961 * - in other words, page-independent/site-wide variables (without state).
2962 * You will only be adding bloat to the html page and causing page caches to
2963 * have to be purged on configuration changes.
2966 public function getJSVars() {
2971 $canonicalName = false; # bug 21115
2973 $title = $this->getTitle();
2974 $ns = $title->getNamespace();
2975 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2977 // Get the relevant title so that AJAX features can use the correct page name
2978 // when making API requests from certain special pages (bug 34972).
2979 $relevantTitle = $this->getSkin()->getRelevantTitle();
2981 if ( $ns == NS_SPECIAL
) {
2982 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2983 } elseif ( $this->canUseWikiPage() ) {
2984 $wikiPage = $this->getWikiPage();
2985 $latestRevID = $wikiPage->getLatest();
2986 $pageID = $wikiPage->getId();
2989 $lang = $title->getPageLanguage();
2991 // Pre-process information
2992 $separatorTransTable = $lang->separatorTransformTable();
2993 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2994 $compactSeparatorTransTable = array(
2995 implode( "\t", array_keys( $separatorTransTable ) ),
2996 implode( "\t", $separatorTransTable ),
2998 $digitTransTable = $lang->digitTransformTable();
2999 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3000 $compactDigitTransTable = array(
3001 implode( "\t", array_keys( $digitTransTable ) ),
3002 implode( "\t", $digitTransTable ),
3005 $user = $this->getUser();
3008 'wgCanonicalNamespace' => $nsname,
3009 'wgCanonicalSpecialPageName' => $canonicalName,
3010 'wgNamespaceNumber' => $title->getNamespace(),
3011 'wgPageName' => $title->getPrefixedDBkey(),
3012 'wgTitle' => $title->getText(),
3013 'wgCurRevisionId' => $latestRevID,
3014 'wgArticleId' => $pageID,
3015 'wgIsArticle' => $this->isArticle(),
3016 'wgAction' => Action
::getActionName( $this->getContext() ),
3017 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3018 'wgUserGroups' => $user->getEffectiveGroups(),
3019 'wgCategories' => $this->getCategories(),
3020 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3021 'wgPageContentLanguage' => $lang->getCode(),
3022 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3023 'wgDigitTransformTable' => $compactDigitTransTable,
3024 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3025 'wgMonthNames' => $lang->getMonthNamesArray(),
3026 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3027 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3029 if ( $user->isLoggedIn() ) {
3030 $vars['wgUserId'] = $user->getId();
3031 $vars['wgUserEditCount'] = $user->getEditCount();
3032 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3033 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3035 if ( $wgContLang->hasVariants() ) {
3036 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3038 foreach ( $title->getRestrictionTypes() as $type ) {
3039 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3041 if ( $title->isMainPage() ) {
3042 $vars['wgIsMainPage'] = true;
3044 if ( $this->mRedirectedFrom
) {
3045 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3048 // Allow extensions to add their custom variables to the mw.config map.
3049 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3050 // page-dependant but site-wide (without state).
3051 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3052 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3054 // Merge in variables from addJsConfigVars last
3055 return array_merge( $vars, $this->mJsConfigVars
);
3059 * To make it harder for someone to slip a user a fake
3060 * user-JavaScript or user-CSS preview, a random token
3061 * is associated with the login session. If it's not
3062 * passed back with the preview request, we won't render
3067 public function userCanPreview() {
3068 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3069 ||
!$this->getRequest()->wasPosted()
3070 ||
!$this->getUser()->matchEditToken(
3071 $this->getRequest()->getVal( 'wpEditToken' ) )
3075 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3079 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3083 * @param bool $addContentType Whether "<meta>" specifying content type should be returned
3085 * @return array in format "link name or number => 'link html'".
3087 public function getHeadLinksArray( $addContentType = false ) {
3088 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3089 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3090 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3091 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3092 $wgRightsPage, $wgRightsUrl;
3096 $canonicalUrl = $this->mCanonicalUrl
;
3098 if ( $addContentType ) {
3100 # More succinct than <meta http-equiv=Content-Type>, has the
3102 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3104 $tags['meta-content-type'] = Html
::element( 'meta', array(
3105 'http-equiv' => 'Content-Type',
3106 'content' => "$wgMimeType; charset=UTF-8"
3108 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3109 'http-equiv' => 'Content-Style-Type',
3110 'content' => 'text/css'
3115 $tags['meta-generator'] = Html
::element( 'meta', array(
3116 'name' => 'generator',
3117 'content' => "MediaWiki $wgVersion",
3120 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3121 if( $p !== 'index,follow' ) {
3122 // http://www.robotstxt.org/wc/meta-user.html
3123 // Only show if it's different from the default robots policy
3124 $tags['meta-robots'] = Html
::element( 'meta', array(
3130 if ( count( $this->mKeywords
) > 0 ) {
3132 "/<.*?" . ">/" => '',
3135 $tags['meta-keywords'] = Html
::element( 'meta', array(
3136 'name' => 'keywords',
3137 'content' => preg_replace(
3138 array_keys( $strip ),
3139 array_values( $strip ),
3140 implode( ',', $this->mKeywords
)
3145 foreach ( $this->mMetatags
as $tag ) {
3146 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3148 $tag[0] = substr( $tag[0], 5 );
3152 $tagName = "meta-{$tag[0]}";
3153 if ( isset( $tags[$tagName] ) ) {
3154 $tagName .= $tag[1];
3156 $tags[$tagName] = Html
::element( 'meta',
3159 'content' => $tag[1]
3164 foreach ( $this->mLinktags
as $tag ) {
3165 $tags[] = Html
::element( 'link', $tag );
3168 # Universal edit button
3169 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3170 $user = $this->getUser();
3171 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3172 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3173 // Original UniversalEditButton
3174 $msg = $this->msg( 'edit' )->text();
3175 $tags['universal-edit-button'] = Html
::element( 'link', array(
3176 'rel' => 'alternate',
3177 'type' => 'application/x-wiki',
3179 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3181 // Alternate edit link
3182 $tags['alternative-edit'] = Html
::element( 'link', array(
3185 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3190 # Generally the order of the favicon and apple-touch-icon links
3191 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3192 # uses whichever one appears later in the HTML source. Make sure
3193 # apple-touch-icon is specified first to avoid this.
3194 if ( $wgAppleTouchIcon !== false ) {
3195 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3198 if ( $wgFavicon !== false ) {
3199 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3202 # OpenSearch description link
3203 $tags['opensearch'] = Html
::element( 'link', array(
3205 'type' => 'application/opensearchdescription+xml',
3206 'href' => wfScript( 'opensearch_desc' ),
3207 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3210 if ( $wgEnableAPI ) {
3211 # Real Simple Discovery link, provides auto-discovery information
3212 # for the MediaWiki API (and potentially additional custom API
3213 # support such as WordPress or Twitter-compatible APIs for a
3214 # blogging extension, etc)
3215 $tags['rsd'] = Html
::element( 'link', array(
3217 'type' => 'application/rsd+xml',
3218 // Output a protocol-relative URL here if $wgServer is protocol-relative
3219 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3220 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3225 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3226 $lang = $this->getTitle()->getPageLanguage();
3227 if ( $lang->hasVariants() ) {
3229 $urlvar = $lang->getURLVariant();
3232 $variants = $lang->getVariants();
3233 foreach ( $variants as $_v ) {
3234 $tags["variant-$_v"] = Html
::element( 'link', array(
3235 'rel' => 'alternate',
3237 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3241 $canonicalUrl = $this->getTitle()->getLocalURL();
3248 if ( $wgRightsPage ) {
3249 $copy = Title
::newFromText( $wgRightsPage );
3252 $copyright = $copy->getLocalURL();
3256 if ( !$copyright && $wgRightsUrl ) {
3257 $copyright = $wgRightsUrl;
3261 $tags['copyright'] = Html
::element( 'link', array(
3262 'rel' => 'copyright',
3263 'href' => $copyright )
3269 foreach( $this->getSyndicationLinks() as $format => $link ) {
3270 # Use the page name for the title. In principle, this could
3271 # lead to issues with having the same name for different feeds
3272 # corresponding to the same page, but we can't avoid that at
3275 $tags[] = $this->feedLink(
3278 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3279 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3283 # Recent changes feed should appear on every page (except recentchanges,
3284 # that would be redundant). Put it after the per-page feed to avoid
3285 # changing existing behavior. It's still available, probably via a
3286 # menu in your browser. Some sites might have a different feed they'd
3287 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3288 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3289 # If so, use it instead.
3290 if ( $wgOverrideSiteFeed ) {
3291 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3292 // Note, this->feedLink escapes the url.
3293 $tags[] = $this->feedLink(
3296 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3299 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3300 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3301 foreach ( $wgAdvertisedFeedTypes as $format ) {
3302 $tags[] = $this->feedLink(
3304 $rctitle->getLocalURL( "feed={$format}" ),
3305 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3312 global $wgEnableCanonicalServerLink;
3313 if ( $wgEnableCanonicalServerLink ) {
3314 if ( $canonicalUrl !== false ) {
3315 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3317 $reqUrl = $this->getRequest()->getRequestURL();
3318 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3321 if ( $canonicalUrl !== false ) {
3322 $tags[] = Html
::element( 'link', array(
3323 'rel' => 'canonical',
3324 'href' => $canonicalUrl
3333 * @param bool $addContentType Whether "<meta>" specifying content type should be returned
3335 * @return string HTML tag links to be put in the header.
3337 public function getHeadLinks( $unused = null, $addContentType = false ) {
3338 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3342 * Generate a "<link rel/>" for a feed.
3344 * @param string $type feed type
3345 * @param string $url URL to the feed
3346 * @param string $text value of the "title" attribute
3347 * @return String: HTML fragment
3349 private function feedLink( $type, $url, $text ) {
3350 return Html
::element( 'link', array(
3351 'rel' => 'alternate',
3352 'type' => "application/$type+xml",
3359 * Add a local or specified stylesheet, with the given media options.
3360 * Meant primarily for internal use...
3362 * @param string $style URL to the file
3363 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3364 * @param string $condition for IE conditional comments, specifying an IE version
3365 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3367 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3369 // Even though we expect the media type to be lowercase, but here we
3370 // force it to lowercase to be safe.
3372 $options['media'] = $media;
3375 $options['condition'] = $condition;
3378 $options['dir'] = $dir;
3380 $this->styles
[$style] = $options;
3384 * Adds inline CSS styles
3385 * @param $style_css Mixed: inline CSS
3386 * @param string $flip Set to 'flip' to flip the CSS if needed
3388 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3389 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3390 # If wanted, and the interface is right-to-left, flip the CSS
3391 $style_css = CSSJanus
::transform( $style_css, true, false );
3393 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3397 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3398 * These will be applied to various media & IE conditionals.
3402 public function buildCssLinks() {
3403 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3405 $this->getSkin()->setupSkinUserCss( $this );
3407 // Add ResourceLoader styles
3408 // Split the styles into four groups
3409 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3410 $otherTags = ''; // Tags to append after the normal <link> tags
3411 $resourceLoader = $this->getResourceLoader();
3413 $moduleStyles = $this->getModuleStyles();
3415 // Per-site custom styles
3416 if ( $wgUseSiteCss ) {
3417 $moduleStyles[] = 'site';
3418 $moduleStyles[] = 'noscript';
3419 if( $this->getUser()->isLoggedIn() ) {
3420 $moduleStyles[] = 'user.groups';
3424 // Per-user custom styles
3425 if ( $wgAllowUserCss ) {
3426 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3427 // We're on a preview of a CSS subpage
3428 // Exclude this page from the user module in case it's in there (bug 26283)
3429 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3430 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3433 // Load the previewed CSS
3434 // If needed, Janus it first. This is user-supplied CSS, so it's
3435 // assumed to be right for the content language directionality.
3436 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3437 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3438 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3440 $otherTags .= Html
::inlineStyle( $previewedCSS );
3442 // Load the user styles normally
3443 $moduleStyles[] = 'user';
3447 // Per-user preference styles
3448 if ( $wgAllowUserCssPrefs ) {
3449 $moduleStyles[] = 'user.cssprefs';
3452 foreach ( $moduleStyles as $name ) {
3453 $module = $resourceLoader->getModule( $name );
3457 $group = $module->getGroup();
3458 // Modules in groups named "other" or anything different than "user", "site" or "private"
3459 // will be placed in the "other" group
3460 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3463 // We want site, private and user styles to override dynamically added styles from modules, but we want
3464 // dynamically added styles to override statically added styles from other modules. So the order
3465 // has to be other, dynamic, site, private, user
3466 // Add statically added styles for other modules
3467 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3468 // Add normal styles added through addStyle()/addInlineStyle() here
3469 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3470 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3471 // We use a <meta> tag with a made-up name for this because that's valid HTML
3472 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3474 // Add site, private and user styles
3475 // 'private' at present only contains user.options, so put that before 'user'
3476 // Any future private modules will likely have a similar user-specific character
3477 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3478 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3479 ResourceLoaderModule
::TYPE_STYLES
3483 // Add stuff in $otherTags (previewed user CSS if applicable)
3491 public function buildCssLinksArray() {
3494 // Add any extension CSS
3495 foreach ( $this->mExtStyles
as $url ) {
3496 $this->addStyle( $url );
3498 $this->mExtStyles
= array();
3500 foreach( $this->styles
as $file => $options ) {
3501 $link = $this->styleLink( $file, $options );
3503 $links[$file] = $link;
3510 * Generate \<link\> tags for stylesheets
3512 * @param string $style URL to the file
3513 * @param array $options option, can contain 'condition', 'dir', 'media'
3515 * @return String: HTML fragment
3517 protected function styleLink( $style, $options ) {
3518 if( isset( $options['dir'] ) ) {
3519 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3524 if( isset( $options['media'] ) ) {
3525 $media = self
::transformCssMedia( $options['media'] );
3526 if( is_null( $media ) ) {
3533 if( substr( $style, 0, 1 ) == '/' ||
3534 substr( $style, 0, 5 ) == 'http:' ||
3535 substr( $style, 0, 6 ) == 'https:' ) {
3538 global $wgStylePath, $wgStyleVersion;
3539 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3542 $link = Html
::linkedStyle( $url, $media );
3544 if( isset( $options['condition'] ) ) {
3545 $condition = htmlspecialchars( $options['condition'] );
3546 $link = "<!--[if $condition]>$link<![endif]-->";
3552 * Transform "media" attribute based on request parameters
3554 * @param string $media current value of the "media" attribute
3555 * @return String: modified value of the "media" attribute, or null to skip
3558 public static function transformCssMedia( $media ) {
3559 global $wgRequest, $wgHandheldForIPhone;
3561 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3562 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3564 // Switch in on-screen display for media testing
3566 'printable' => 'print',
3567 'handheld' => 'handheld',
3569 foreach( $switches as $switch => $targetMedia ) {
3570 if( $wgRequest->getBool( $switch ) ) {
3571 if( $media == $targetMedia ) {
3573 } elseif( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3574 // This regex will not attempt to understand a comma-separated media_query_list
3576 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3577 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3579 // If it's a print request, we never want any kind of screen stylesheets
3580 // If it's a handheld request (currently the only other choice with a switch),
3581 // we don't want simple 'screen' but we might want screen queries that
3582 // have a max-width or something, so we'll pass all others on and let the
3583 // client do the query.
3584 if( $targetMedia == 'print' ||
$media == 'screen' ) {
3591 // Expand longer media queries as iPhone doesn't grok 'handheld'
3592 if( $wgHandheldForIPhone ) {
3593 $mediaAliases = array(
3594 'screen' => 'screen and (min-device-width: 481px)',
3595 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3598 if( isset( $mediaAliases[$media] ) ) {
3599 $media = $mediaAliases[$media];
3607 * Add a wikitext-formatted message to the output.
3608 * This is equivalent to:
3610 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3612 public function addWikiMsg( /*...*/ ) {
3613 $args = func_get_args();
3614 $name = array_shift( $args );
3615 $this->addWikiMsgArray( $name, $args );
3619 * Add a wikitext-formatted message to the output.
3620 * Like addWikiMsg() except the parameters are taken as an array
3621 * instead of a variable argument list.
3623 * @param $name string
3624 * @param $args array
3626 public function addWikiMsgArray( $name, $args ) {
3627 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3631 * This function takes a number of message/argument specifications, wraps them in
3632 * some overall structure, and then parses the result and adds it to the output.
3634 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3635 * on. The subsequent arguments may either be strings, in which case they are the
3636 * message names, or arrays, in which case the first element is the message name,
3637 * and subsequent elements are the parameters to that message.
3639 * Don't use this for messages that are not in users interface language.
3643 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3647 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3649 * The newline after opening div is needed in some wikitext. See bug 19226.
3651 * @param $wrap string
3653 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3654 $msgSpecs = func_get_args();
3655 array_shift( $msgSpecs );
3656 $msgSpecs = array_values( $msgSpecs );
3658 foreach ( $msgSpecs as $n => $spec ) {
3659 if ( is_array( $spec ) ) {
3661 $name = array_shift( $args );
3662 if ( isset( $args['options'] ) ) {
3663 unset( $args['options'] );
3665 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3673 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3675 $this->addWikiText( $s );
3679 * Include jQuery core. Use this to avoid loading it multiple times
3680 * before we get a usable script loader.
3682 * @param array $modules list of jQuery modules which should be loaded
3683 * @return Array: the list of modules which were not loaded.
3685 * @deprecated since 1.17
3687 public function includeJQuery( $modules = array() ) {