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() sparsingly
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 * Constructor for OutputPage. This should not be called directly.
253 * Instead a new RequestContext should be created and it will implicitly create
254 * a OutputPage tied to that context.
256 function __construct( IContextSource
$context = null ) {
257 if ( $context === null ) {
258 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
259 wfDeprecated( __METHOD__
, '1.18' );
261 $this->setContext( $context );
266 * Redirect to $url rather than displaying the normal page
268 * @param $url String: URL
269 * @param $responsecode String: HTTP status code
271 public function redirect( $url, $responsecode = '302' ) {
272 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
273 $this->mRedirect
= str_replace( "\n", '', $url );
274 $this->mRedirectCode
= $responsecode;
278 * Get the URL to redirect to, or an empty string if not redirect URL set
282 public function getRedirect() {
283 return $this->mRedirect
;
287 * Set the HTTP status code to send with the output.
289 * @param $statusCode Integer
291 public function setStatusCode( $statusCode ) {
292 $this->mStatusCode
= $statusCode;
296 * Add a new "<meta>" tag
297 * To add an http-equiv meta tag, precede the name with "http:"
299 * @param $name String tag name
300 * @param $val String tag value
302 function addMeta( $name, $val ) {
303 array_push( $this->mMetatags
, array( $name, $val ) );
307 * Add a keyword or a list of keywords in the page header
309 * @param $text String or array of strings
311 function addKeyword( $text ) {
312 if( is_array( $text ) ) {
313 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
315 array_push( $this->mKeywords
, $text );
320 * Add a new \<link\> tag to the page header.
322 * Note: use setCanonicalUrl() for rel=canonical.
324 * @param $linkarr Array: associative array of attributes.
326 function addLink( $linkarr ) {
327 array_push( $this->mLinktags
, $linkarr );
331 * Add a new \<link\> with "rel" attribute set to "meta"
333 * @param $linkarr Array: associative array mapping attribute names to their
334 * values, both keys and values will be escaped, and the
335 * "rel" attribute will be automatically added
337 function addMetadataLink( $linkarr ) {
338 $linkarr['rel'] = $this->getMetadataAttribute();
339 $this->addLink( $linkarr );
343 * Set the URL to be used for the <link rel=canonical>. This should be used
344 * in preference to addLink(), to avoid duplicate link tags.
346 function setCanonicalUrl( $url ) {
347 $this->mCanonicalUrl
= $url;
351 * Get the value of the "rel" attribute for metadata links
355 public function getMetadataAttribute() {
356 # note: buggy CC software only reads first "meta" link
357 static $haveMeta = false;
359 return 'alternate meta';
367 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
369 * @param $script String: raw HTML
371 function addScript( $script ) {
372 $this->mScripts
.= $script . "\n";
376 * Register and add a stylesheet from an extension directory.
378 * @param $url String path to sheet. Provide either a full url (beginning
379 * with 'http', etc) or a relative path from the document root
380 * (beginning with '/'). Otherwise it behaves identically to
381 * addStyle() and draws from the /skins folder.
383 public function addExtensionStyle( $url ) {
384 array_push( $this->mExtStyles
, $url );
388 * Get all styles added by extensions
392 function getExtStyle() {
393 return $this->mExtStyles
;
397 * Add a JavaScript file out of skins/common, or a given relative path.
399 * @param $file String: filename in skins/common or complete on-server path
401 * @param $version String: style version of the file. Defaults to $wgStyleVersion
403 public function addScriptFile( $file, $version = null ) {
404 global $wgStylePath, $wgStyleVersion;
405 // See if $file parameter is an absolute URL or begins with a slash
406 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
409 $path = "{$wgStylePath}/common/{$file}";
411 if ( is_null( $version ) )
412 $version = $wgStyleVersion;
413 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
417 * Add a self-contained script tag with the given contents
419 * @param $script String: JavaScript text, no "<script>" tags
421 public function addInlineScript( $script ) {
422 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
426 * Get all registered JS and CSS tags for the header.
430 function getScript() {
431 return $this->mScripts
. $this->getHeadItems();
435 * Filter an array of modules to remove insufficiently trustworthy members, and modules
436 * which are no longer registered (eg a page is cached before an extension is disabled)
437 * @param $modules Array
438 * @param $position String if not null, only return modules with this position
439 * @param $type string
442 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
) {
443 $resourceLoader = $this->getResourceLoader();
444 $filteredModules = array();
445 foreach( $modules as $val ){
446 $module = $resourceLoader->getModule( $val );
447 if( $module instanceof ResourceLoaderModule
448 && $module->getOrigin() <= $this->getAllowedModules( $type )
449 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
451 $filteredModules[] = $val;
454 return $filteredModules;
458 * Get the list of modules to include on this page
460 * @param $filter Bool whether to filter out insufficiently trustworthy modules
461 * @param $position String if not null, only return modules with this position
462 * @param $param string
463 * @return Array of module names
465 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
466 $modules = array_values( array_unique( $this->$param ) );
468 ?
$this->filterModules( $modules, $position )
473 * Add one or more modules recognized by the resource loader. Modules added
474 * through this function will be loaded by the resource loader when the
477 * @param $modules Mixed: module name (string) or array of module names
479 public function addModules( $modules ) {
480 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
484 * Get the list of module JS to include on this page
489 * @return array of module names
491 public function getModuleScripts( $filter = false, $position = null ) {
492 return $this->getModules( $filter, $position, 'mModuleScripts' );
496 * Add only JS of one or more modules recognized by the resource loader. Module
497 * scripts added through this function will be loaded by the resource loader when
500 * @param $modules Mixed: module name (string) or array of module names
502 public function addModuleScripts( $modules ) {
503 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
507 * Get the list of module CSS to include on this page
512 * @return Array of module names
514 public function getModuleStyles( $filter = false, $position = null ) {
515 return $this->getModules( $filter, $position, 'mModuleStyles' );
519 * Add only CSS of one or more modules recognized by the resource loader. Module
520 * styles added through this function will be loaded by the resource loader when
523 * @param $modules Mixed: module name (string) or array of module names
525 public function addModuleStyles( $modules ) {
526 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
530 * Get the list of module messages to include on this page
535 * @return Array of module names
537 public function getModuleMessages( $filter = false, $position = null ) {
538 return $this->getModules( $filter, $position, 'mModuleMessages' );
542 * Add only messages of one or more modules recognized by the resource loader.
543 * Module messages added through this function will be loaded by the resource
544 * loader when the page loads.
546 * @param $modules Mixed: module name (string) or array of module names
548 public function addModuleMessages( $modules ) {
549 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
553 * Get an array of head items
557 function getHeadItemsArray() {
558 return $this->mHeadItems
;
562 * Get all header items in a string
566 function getHeadItems() {
568 foreach ( $this->mHeadItems
as $item ) {
575 * Add or replace an header item to the output
577 * @param $name String: item name
578 * @param $value String: raw HTML
580 public function addHeadItem( $name, $value ) {
581 $this->mHeadItems
[$name] = $value;
585 * Check if the header item $name is already set
587 * @param $name String: item name
590 public function hasHeadItem( $name ) {
591 return isset( $this->mHeadItems
[$name] );
595 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
597 * @param $tag String: value of "ETag" header
599 function setETag( $tag ) {
604 * Set whether the output should only contain the body of the article,
605 * without any skin, sidebar, etc.
606 * Used e.g. when calling with "action=render".
608 * @param $only Boolean: whether to output only the body of the article
610 public function setArticleBodyOnly( $only ) {
611 $this->mArticleBodyOnly
= $only;
615 * Return whether the output will contain only the body of the article
619 public function getArticleBodyOnly() {
620 return $this->mArticleBodyOnly
;
624 * checkLastModified tells the client to use the client-cached page if
625 * possible. If successful, the OutputPage is disabled so that
626 * any future call to OutputPage->output() have no effect.
628 * Side effect: sets mLastModified for Last-Modified header
630 * @param $timestamp string
632 * @return Boolean: true iff cache-ok headers was sent.
634 public function checkLastModified( $timestamp ) {
635 global $wgCachePages, $wgCacheEpoch;
637 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
638 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
641 if( !$wgCachePages ) {
642 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
645 if( $this->getUser()->getOption( 'nocache' ) ) {
646 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
650 $timestamp = wfTimestamp( TS_MW
, $timestamp );
651 $modifiedTimes = array(
652 'page' => $timestamp,
653 'user' => $this->getUser()->getTouched(),
654 'epoch' => $wgCacheEpoch
656 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
658 $maxModified = max( $modifiedTimes );
659 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
661 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
662 if ( $clientHeader === false ) {
663 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
667 # IE sends sizes after the date like this:
668 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
669 # this breaks strtotime().
670 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
672 wfSuppressWarnings(); // E_STRICT system time bitching
673 $clientHeaderTime = strtotime( $clientHeader );
675 if ( !$clientHeaderTime ) {
676 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
679 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
683 foreach ( $modifiedTimes as $name => $value ) {
684 if ( $info !== '' ) {
687 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
690 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
691 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
692 wfDebug( __METHOD__
. ": effective Last-Modified: " .
693 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
694 if( $clientHeaderTime < $maxModified ) {
695 wfDebug( __METHOD__
. ": STALE, $info\n", false );
700 # Give a 304 response code and disable body output
701 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
702 ini_set( 'zlib.output_compression', 0 );
703 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
704 $this->sendCacheControl();
707 // Don't output a compressed blob when using ob_gzhandler;
708 // it's technically against HTTP spec and seems to confuse
709 // Firefox when the response gets split over two packets.
710 wfClearOutputBuffers();
716 * Override the last modified timestamp
718 * @param $timestamp String: new timestamp, in a format readable by
721 public function setLastModified( $timestamp ) {
722 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
726 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
728 * @param $policy String: the literal string to output as the contents of
729 * the meta tag. Will be parsed according to the spec and output in
733 public function setRobotPolicy( $policy ) {
734 $policy = Article
::formatRobotPolicy( $policy );
736 if( isset( $policy['index'] ) ) {
737 $this->setIndexPolicy( $policy['index'] );
739 if( isset( $policy['follow'] ) ) {
740 $this->setFollowPolicy( $policy['follow'] );
745 * Set the index policy for the page, but leave the follow policy un-
748 * @param $policy string Either 'index' or 'noindex'.
751 public function setIndexPolicy( $policy ) {
752 $policy = trim( $policy );
753 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
754 $this->mIndexPolicy
= $policy;
759 * Set the follow policy for the page, but leave the index policy un-
762 * @param $policy String: either 'follow' or 'nofollow'.
765 public function setFollowPolicy( $policy ) {
766 $policy = trim( $policy );
767 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
768 $this->mFollowPolicy
= $policy;
773 * Set the new value of the "action text", this will be added to the
774 * "HTML title", separated from it with " - ".
776 * @param $text String: new value of the "action text"
778 public function setPageTitleActionText( $text ) {
779 $this->mPageTitleActionText
= $text;
783 * Get the value of the "action text"
787 public function getPageTitleActionText() {
788 if ( isset( $this->mPageTitleActionText
) ) {
789 return $this->mPageTitleActionText
;
795 * "HTML title" means the contents of "<title>".
796 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
798 * @param $name string
800 public function setHTMLTitle( $name ) {
801 if ( $name instanceof Message
) {
802 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
804 $this->mHTMLtitle
= $name;
809 * Return the "HTML title", i.e. the content of the "<title>" tag.
813 public function getHTMLTitle() {
814 return $this->mHTMLtitle
;
818 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
822 public function setRedirectedFrom( $t ) {
823 $this->mRedirectedFrom
= $t;
827 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
828 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
829 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
830 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
832 * @param $name string|Message
834 public function setPageTitle( $name ) {
835 if ( $name instanceof Message
) {
836 $name = $name->setContext( $this->getContext() )->text();
839 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
840 # but leave "<i>foobar</i>" alone
841 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
842 $this->mPagetitle
= $nameWithTags;
844 # change "<i>foo&bar</i>" to "foo&bar"
845 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
849 * Return the "page title", i.e. the content of the \<h1\> tag.
853 public function getPageTitle() {
854 return $this->mPagetitle
;
858 * Set the Title object to use
860 * @param $t Title object
862 public function setTitle( Title
$t ) {
863 $this->getContext()->setTitle( $t );
867 * Replace the subtile with $str
869 * @param $str String|Message: new value of the subtitle. String should be safe HTML.
871 public function setSubtitle( $str ) {
872 $this->clearSubtitle();
873 $this->addSubtitle( $str );
877 * Add $str to the subtitle
879 * @deprecated in 1.19; use addSubtitle() instead
880 * @param $str String|Message to add to the subtitle
882 public function appendSubtitle( $str ) {
883 $this->addSubtitle( $str );
887 * Add $str to the subtitle
889 * @param $str String|Message to add to the subtitle. String should be safe HTML.
891 public function addSubtitle( $str ) {
892 if ( $str instanceof Message
) {
893 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
895 $this->mSubtitle
[] = $str;
900 * Add a subtitle containing a backlink to a page
902 * @param $title Title to link to
904 public function addBacklinkSubtitle( Title
$title ) {
906 if ( $title->isRedirect() ) {
907 $query['redirect'] = 'no';
909 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
913 * Clear the subtitles
915 public function clearSubtitle() {
916 $this->mSubtitle
= array();
924 public function getSubtitle() {
925 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
929 * Set the page as printable, i.e. it'll be displayed with with all
930 * print styles included
932 public function setPrintable() {
933 $this->mPrintable
= true;
937 * Return whether the page is "printable"
941 public function isPrintable() {
942 return $this->mPrintable
;
946 * Disable output completely, i.e. calling output() will have no effect
948 public function disable() {
949 $this->mDoNothing
= true;
953 * Return whether the output will be completely disabled
957 public function isDisabled() {
958 return $this->mDoNothing
;
962 * Show an "add new section" link?
966 public function showNewSectionLink() {
967 return $this->mNewSectionLink
;
971 * Forcibly hide the new section link?
975 public function forceHideNewSectionLink() {
976 return $this->mHideNewSectionLink
;
980 * Add or remove feed links in the page header
981 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
982 * for the new version
985 * @param $show Boolean: true: add default feeds, false: remove all feeds
987 public function setSyndicated( $show = true ) {
989 $this->setFeedAppendQuery( false );
991 $this->mFeedLinks
= array();
996 * Add default feeds to the page header
997 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
998 * for the new version
1001 * @param $val String: query to append to feed links or false to output
1004 public function setFeedAppendQuery( $val ) {
1005 global $wgAdvertisedFeedTypes;
1007 $this->mFeedLinks
= array();
1009 foreach ( $wgAdvertisedFeedTypes as $type ) {
1010 $query = "feed=$type";
1011 if ( is_string( $val ) ) {
1012 $query .= '&' . $val;
1014 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1019 * Add a feed link to the page header
1021 * @param $format String: feed type, should be a key of $wgFeedClasses
1022 * @param $href String: URL
1024 public function addFeedLink( $format, $href ) {
1025 global $wgAdvertisedFeedTypes;
1027 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1028 $this->mFeedLinks
[$format] = $href;
1033 * Should we output feed links for this page?
1036 public function isSyndicated() {
1037 return count( $this->mFeedLinks
) > 0;
1041 * Return URLs for each supported syndication format for this page.
1042 * @return array associating format keys with URLs
1044 public function getSyndicationLinks() {
1045 return $this->mFeedLinks
;
1049 * Will currently always return null
1053 public function getFeedAppendQuery() {
1054 return $this->mFeedLinksAppendQuery
;
1058 * Set whether the displayed content is related to the source of the
1059 * corresponding article on the wiki
1060 * Setting true will cause the change "article related" toggle to true
1064 public function setArticleFlag( $v ) {
1065 $this->mIsarticle
= $v;
1067 $this->mIsArticleRelated
= $v;
1072 * Return whether the content displayed page is related to the source of
1073 * the corresponding article on the wiki
1077 public function isArticle() {
1078 return $this->mIsarticle
;
1082 * Set whether this page is related an article on the wiki
1083 * Setting false will cause the change of "article flag" toggle to false
1087 public function setArticleRelated( $v ) {
1088 $this->mIsArticleRelated
= $v;
1090 $this->mIsarticle
= false;
1095 * Return whether this page is related an article on the wiki
1099 public function isArticleRelated() {
1100 return $this->mIsArticleRelated
;
1104 * Add new language links
1106 * @param $newLinkArray array Associative array mapping language code to the page
1109 public function addLanguageLinks( $newLinkArray ) {
1110 $this->mLanguageLinks +
= $newLinkArray;
1114 * Reset the language links and add new language links
1116 * @param $newLinkArray array Associative array mapping language code to the page
1119 public function setLanguageLinks( $newLinkArray ) {
1120 $this->mLanguageLinks
= $newLinkArray;
1124 * Get the list of language links
1126 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1128 public function getLanguageLinks() {
1129 return $this->mLanguageLinks
;
1133 * Add an array of categories, with names in the keys
1135 * @param $categories Array mapping category name => sort key
1137 public function addCategoryLinks( $categories ) {
1140 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1144 # Add the links to a LinkBatch
1145 $arr = array( NS_CATEGORY
=> $categories );
1146 $lb = new LinkBatch
;
1147 $lb->setArray( $arr );
1149 # Fetch existence plus the hiddencat property
1150 $dbr = wfGetDB( DB_SLAVE
);
1151 $res = $dbr->select( array( 'page', 'page_props' ),
1152 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1153 $lb->constructSet( 'page', $dbr ),
1156 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1159 # Add the results to the link cache
1160 $lb->addResultToCache( LinkCache
::singleton(), $res );
1162 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1163 $categories = array_combine(
1164 array_keys( $categories ),
1165 array_fill( 0, count( $categories ), 'normal' )
1168 # Mark hidden categories
1169 foreach ( $res as $row ) {
1170 if ( isset( $row->pp_value
) ) {
1171 $categories[$row->page_title
] = 'hidden';
1175 # Add the remaining categories to the skin
1176 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1177 foreach ( $categories as $category => $type ) {
1178 $origcategory = $category;
1179 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1180 $wgContLang->findVariantLink( $category, $title, true );
1181 if ( $category != $origcategory ) {
1182 if ( array_key_exists( $category, $categories ) ) {
1186 $text = $wgContLang->convertHtml( $title->getText() );
1187 $this->mCategories
[] = $title->getText();
1188 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1194 * Reset the category links (but not the category list) and add $categories
1196 * @param $categories Array mapping category name => sort key
1198 public function setCategoryLinks( $categories ) {
1199 $this->mCategoryLinks
= array();
1200 $this->addCategoryLinks( $categories );
1204 * Get the list of category links, in a 2-D array with the following format:
1205 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1206 * hidden categories) and $link a HTML fragment with a link to the category
1211 public function getCategoryLinks() {
1212 return $this->mCategoryLinks
;
1216 * Get the list of category names this page belongs to
1218 * @return Array of strings
1220 public function getCategories() {
1221 return $this->mCategories
;
1225 * Do not allow scripts which can be modified by wiki users to load on this page;
1226 * only allow scripts bundled with, or generated by, the software.
1228 public function disallowUserJs() {
1229 $this->reduceAllowedModules(
1230 ResourceLoaderModule
::TYPE_SCRIPTS
,
1231 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1236 * Return whether user JavaScript is allowed for this page
1237 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1238 * trustworthiness is identified and enforced automagically.
1239 * Will be removed in 1.20.
1242 public function isUserJsAllowed() {
1243 wfDeprecated( __METHOD__
, '1.18' );
1244 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1248 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1249 * @see ResourceLoaderModule::$origin
1250 * @param $type String ResourceLoaderModule TYPE_ constant
1251 * @return Int ResourceLoaderModule ORIGIN_ class constant
1253 public function getAllowedModules( $type ) {
1254 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1255 return min( array_values( $this->mAllowedModules
) );
1257 return isset( $this->mAllowedModules
[$type] )
1258 ?
$this->mAllowedModules
[$type]
1259 : ResourceLoaderModule
::ORIGIN_ALL
;
1264 * Set the highest level of CSS/JS untrustworthiness allowed
1265 * @param $type String ResourceLoaderModule TYPE_ constant
1266 * @param $level Int ResourceLoaderModule class constant
1268 public function setAllowedModules( $type, $level ) {
1269 $this->mAllowedModules
[$type] = $level;
1273 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1274 * @param $type String
1275 * @param $level Int ResourceLoaderModule class constant
1277 public function reduceAllowedModules( $type, $level ) {
1278 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1282 * Prepend $text to the body HTML
1284 * @param $text String: HTML
1286 public function prependHTML( $text ) {
1287 $this->mBodytext
= $text . $this->mBodytext
;
1291 * Append $text to the body HTML
1293 * @param $text String: HTML
1295 public function addHTML( $text ) {
1296 $this->mBodytext
.= $text;
1300 * Shortcut for adding an Html::element via addHTML.
1304 * @param $element string
1305 * @param $attribs array
1306 * @param $contents string
1308 public function addElement( $element, $attribs = array(), $contents = '' ) {
1309 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1313 * Clear the body HTML
1315 public function clearHTML() {
1316 $this->mBodytext
= '';
1322 * @return String: HTML
1324 public function getHTML() {
1325 return $this->mBodytext
;
1329 * Get/set the ParserOptions object to use for wikitext parsing
1331 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1332 * current ParserOption object
1333 * @return ParserOptions object
1335 public function parserOptions( $options = null ) {
1336 if ( !$this->mParserOptions
) {
1337 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1338 $this->mParserOptions
->setEditSection( false );
1340 return wfSetVar( $this->mParserOptions
, $options );
1344 * Set the revision ID which will be seen by the wiki text parser
1345 * for things such as embedded {{REVISIONID}} variable use.
1347 * @param $revid Mixed: an positive integer, or null
1348 * @return Mixed: previous value
1350 public function setRevisionId( $revid ) {
1351 $val = is_null( $revid ) ?
null : intval( $revid );
1352 return wfSetVar( $this->mRevisionId
, $val );
1356 * Get the displayed revision ID
1360 public function getRevisionId() {
1361 return $this->mRevisionId
;
1365 * Set the timestamp of the revision which will be displayed. This is used
1366 * to avoid a extra DB call in Skin::lastModified().
1368 * @param $timestamp Mixed: string, or null
1369 * @return Mixed: previous value
1371 public function setRevisionTimestamp( $timestamp) {
1372 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1376 * Get the timestamp of displayed revision.
1377 * This will be null if not filled by setRevisionTimestamp().
1379 * @return String or null
1381 public function getRevisionTimestamp() {
1382 return $this->mRevisionTimestamp
;
1386 * Set the displayed file version
1388 * @param $file File|bool
1389 * @return Mixed: previous value
1391 public function setFileVersion( $file ) {
1393 if ( $file instanceof File
&& $file->exists() ) {
1394 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1396 return wfSetVar( $this->mFileVersion
, $val, true );
1400 * Get the displayed file version
1402 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1404 public function getFileVersion() {
1405 return $this->mFileVersion
;
1409 * Get the templates used on this page
1411 * @return Array (namespace => dbKey => revId)
1414 public function getTemplateIds() {
1415 return $this->mTemplateIds
;
1419 * Get the files used on this page
1421 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1424 public function getFileSearchOptions() {
1425 return $this->mImageTimeKeys
;
1429 * Convert wikitext to HTML and add it to the buffer
1430 * Default assumes that the current page title will be used.
1432 * @param $text String
1433 * @param $linestart Boolean: is this the start of a line?
1434 * @param $interface Boolean: is this text in the user interface language?
1436 public function addWikiText( $text, $linestart = true, $interface = true ) {
1437 $title = $this->getTitle(); // Work arround E_STRICT
1438 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1442 * Add wikitext with a custom Title object
1444 * @param $text String: wikitext
1445 * @param $title Title object
1446 * @param $linestart Boolean: is this the start of a line?
1448 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1449 $this->addWikiTextTitle( $text, $title, $linestart );
1453 * Add wikitext with a custom Title object and tidy enabled.
1455 * @param $text String: wikitext
1456 * @param $title Title object
1457 * @param $linestart Boolean: is this the start of a line?
1459 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1460 $this->addWikiTextTitle( $text, $title, $linestart, true );
1464 * Add wikitext with tidy enabled
1466 * @param $text String: wikitext
1467 * @param $linestart Boolean: is this the start of a line?
1469 public function addWikiTextTidy( $text, $linestart = true ) {
1470 $title = $this->getTitle();
1471 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1475 * Add wikitext with a custom Title object
1477 * @param $text String: wikitext
1478 * @param $title Title object
1479 * @param $linestart Boolean: is this the start of a line?
1480 * @param $tidy Boolean: whether to use tidy
1481 * @param $interface Boolean: whether it is an interface message
1482 * (for example disables conversion)
1484 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1487 wfProfileIn( __METHOD__
);
1489 $popts = $this->parserOptions();
1490 $oldTidy = $popts->setTidy( $tidy );
1491 $popts->setInterfaceMessage( (bool) $interface );
1493 $parserOutput = $wgParser->parse(
1494 $text, $title, $popts,
1495 $linestart, true, $this->mRevisionId
1498 $popts->setTidy( $oldTidy );
1500 $this->addParserOutput( $parserOutput );
1502 wfProfileOut( __METHOD__
);
1506 * Add a ParserOutput object, but without Html
1508 * @param $parserOutput ParserOutput object
1510 public function addParserOutputNoText( &$parserOutput ) {
1511 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1512 $this->addCategoryLinks( $parserOutput->getCategories() );
1513 $this->mNewSectionLink
= $parserOutput->getNewSection();
1514 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1516 $this->mParseWarnings
= $parserOutput->getWarnings();
1517 if ( !$parserOutput->isCacheable() ) {
1518 $this->enableClientCache( false );
1520 $this->mNoGallery
= $parserOutput->getNoGallery();
1521 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1522 $this->addModules( $parserOutput->getModules() );
1523 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1524 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1525 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1527 // Template versioning...
1528 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1529 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1530 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1532 $this->mTemplateIds
[$ns] = $dbks;
1535 // File versioning...
1536 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1537 $this->mImageTimeKeys
[$dbk] = $data;
1540 // Hooks registered in the object
1541 global $wgParserOutputHooks;
1542 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1543 list( $hookName, $data ) = $hookInfo;
1544 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1545 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1549 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1553 * Add a ParserOutput object
1555 * @param $parserOutput ParserOutput
1557 function addParserOutput( &$parserOutput ) {
1558 $this->addParserOutputNoText( $parserOutput );
1559 $text = $parserOutput->getText();
1560 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1561 $this->addHTML( $text );
1566 * Add the output of a QuickTemplate to the output buffer
1568 * @param $template QuickTemplate
1570 public function addTemplate( &$template ) {
1572 $template->execute();
1573 $this->addHTML( ob_get_contents() );
1578 * Parse wikitext and return the HTML.
1580 * @param $text String
1581 * @param $linestart Boolean: is this the start of a line?
1582 * @param $interface Boolean: use interface language ($wgLang instead of
1583 * $wgContLang) while parsing language sensitive magic
1584 * words like GRAMMAR and PLURAL. This also disables
1585 * LanguageConverter.
1586 * @param $language Language object: target language object, will override
1588 * @throws MWException
1589 * @return String: HTML
1591 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1594 if( is_null( $this->getTitle() ) ) {
1595 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1598 $popts = $this->parserOptions();
1600 $popts->setInterfaceMessage( true );
1602 if ( $language !== null ) {
1603 $oldLang = $popts->setTargetLanguage( $language );
1606 $parserOutput = $wgParser->parse(
1607 $text, $this->getTitle(), $popts,
1608 $linestart, true, $this->mRevisionId
1612 $popts->setInterfaceMessage( false );
1614 if ( $language !== null ) {
1615 $popts->setTargetLanguage( $oldLang );
1618 return $parserOutput->getText();
1622 * Parse wikitext, strip paragraphs, and return the HTML.
1624 * @param $text String
1625 * @param $linestart Boolean: is this the start of a line?
1626 * @param $interface Boolean: use interface language ($wgLang instead of
1627 * $wgContLang) while parsing language sensitive magic
1628 * words like GRAMMAR and PLURAL
1629 * @return String: HTML
1631 public function parseInline( $text, $linestart = true, $interface = false ) {
1632 $parsed = $this->parse( $text, $linestart, $interface );
1635 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1643 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1645 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1647 public function setSquidMaxage( $maxage ) {
1648 $this->mSquidMaxage
= $maxage;
1652 * Use enableClientCache(false) to force it to send nocache headers
1654 * @param $state bool
1658 public function enableClientCache( $state ) {
1659 return wfSetVar( $this->mEnableClientCache
, $state );
1663 * Get the list of cookies that will influence on the cache
1667 function getCacheVaryCookies() {
1668 global $wgCookiePrefix, $wgCacheVaryCookies;
1670 if ( $cookies === null ) {
1671 $cookies = array_merge(
1673 "{$wgCookiePrefix}Token",
1674 "{$wgCookiePrefix}LoggedOut",
1679 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1685 * Check if the request has a cache-varying cookie header
1686 * If it does, it's very important that we don't allow public caching
1690 function haveCacheVaryCookies() {
1691 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1692 if ( $cookieHeader === false ) {
1695 $cvCookies = $this->getCacheVaryCookies();
1696 foreach ( $cvCookies as $cookieName ) {
1697 # Check for a simple string match, like the way squid does it
1698 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1699 wfDebug( __METHOD__
. ": found $cookieName\n" );
1703 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1708 * Add an HTTP header that will influence on the cache
1710 * @param $header String: header name
1711 * @param $option Array|null
1712 * @todo FIXME: Document the $option parameter; it appears to be for
1713 * X-Vary-Options but what format is acceptable?
1715 public function addVaryHeader( $header, $option = null ) {
1716 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1717 $this->mVaryHeader
[$header] = (array)$option;
1718 } elseif( is_array( $option ) ) {
1719 if( is_array( $this->mVaryHeader
[$header] ) ) {
1720 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1722 $this->mVaryHeader
[$header] = $option;
1725 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1729 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1730 * such as Accept-Encoding or Cookie
1734 public function getVaryHeader() {
1735 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1739 * Get a complete X-Vary-Options header
1743 public function getXVO() {
1744 $cvCookies = $this->getCacheVaryCookies();
1746 $cookiesOption = array();
1747 foreach ( $cvCookies as $cookieName ) {
1748 $cookiesOption[] = 'string-contains=' . $cookieName;
1750 $this->addVaryHeader( 'Cookie', $cookiesOption );
1753 foreach( $this->mVaryHeader
as $header => $option ) {
1754 $newheader = $header;
1755 if ( is_array( $option ) && count( $option ) > 0 ) {
1756 $newheader .= ';' . implode( ';', $option );
1758 $headers[] = $newheader;
1760 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1766 * bug 21672: Add Accept-Language to Vary and XVO headers
1767 * if there's no 'variant' parameter existed in GET.
1770 * /w/index.php?title=Main_page should always be served; but
1771 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1773 function addAcceptLanguage() {
1774 $lang = $this->getTitle()->getPageLanguage();
1775 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1776 $variants = $lang->getVariants();
1777 $aloption = array();
1778 foreach ( $variants as $variant ) {
1779 if( $variant === $lang->getCode() ) {
1782 $aloption[] = 'string-contains=' . $variant;
1784 // IE and some other browsers use BCP 47 standards in
1785 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1786 // We should handle these too.
1787 $variantBCP47 = wfBCP47( $variant );
1788 if ( $variantBCP47 !== $variant ) {
1789 $aloption[] = 'string-contains=' . $variantBCP47;
1793 $this->addVaryHeader( 'Accept-Language', $aloption );
1798 * Set a flag which will cause an X-Frame-Options header appropriate for
1799 * edit pages to be sent. The header value is controlled by
1800 * $wgEditPageFrameOptions.
1802 * This is the default for special pages. If you display a CSRF-protected
1803 * form on an ordinary view page, then you need to call this function.
1805 * @param $enable bool
1807 public function preventClickjacking( $enable = true ) {
1808 $this->mPreventClickjacking
= $enable;
1812 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1813 * This can be called from pages which do not contain any CSRF-protected
1816 public function allowClickjacking() {
1817 $this->mPreventClickjacking
= false;
1821 * Get the X-Frame-Options header value (without the name part), or false
1822 * if there isn't one. This is used by Skin to determine whether to enable
1823 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1827 public function getFrameOptions() {
1828 global $wgBreakFrames, $wgEditPageFrameOptions;
1829 if ( $wgBreakFrames ) {
1831 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1832 return $wgEditPageFrameOptions;
1838 * Send cache control HTTP headers
1840 public function sendCacheControl() {
1841 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1843 $response = $this->getRequest()->response();
1844 if ( $wgUseETag && $this->mETag
) {
1845 $response->header( "ETag: $this->mETag" );
1848 $this->addVaryHeader( 'Cookie' );
1849 $this->addAcceptLanguage();
1851 # don't serve compressed data to clients who can't handle it
1852 # maintain different caches for logged-in users and non-logged in ones
1853 $response->header( $this->getVaryHeader() );
1856 # Add an X-Vary-Options header for Squid with Wikimedia patches
1857 $response->header( $this->getXVO() );
1860 if( $this->mEnableClientCache
) {
1862 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1863 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1867 # We'll purge the proxy cache explicitly, but require end user agents
1868 # to revalidate against the proxy on each visit.
1869 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1870 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1871 # start with a shorter timeout for initial testing
1872 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1873 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1874 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1876 # We'll purge the proxy cache for anons explicitly, but require end user agents
1877 # to revalidate against the proxy on each visit.
1878 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1879 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1880 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1881 # start with a shorter timeout for initial testing
1882 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1883 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1886 # We do want clients to cache if they can, but they *must* check for updates
1887 # on revisiting the page.
1888 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1889 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1890 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1892 if($this->mLastModified
) {
1893 $response->header( "Last-Modified: {$this->mLastModified}" );
1896 wfDebug( __METHOD__
. ": no caching **\n", false );
1898 # In general, the absence of a last modified header should be enough to prevent
1899 # the client from using its cache. We send a few other things just to make sure.
1900 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1901 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1902 $response->header( 'Pragma: no-cache' );
1907 * Get the message associed with the HTTP response code $code
1909 * @param $code Integer: status code
1910 * @return String or null: message or null if $code is not in the list of
1913 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1915 public static function getStatusMessage( $code ) {
1916 wfDeprecated( __METHOD__
, '1.18' );
1917 return HttpStatus
::getMessage( $code );
1921 * Finally, all the text has been munged and accumulated into
1922 * the object, let's actually output it:
1924 public function output() {
1925 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1927 if( $this->mDoNothing
) {
1931 wfProfileIn( __METHOD__
);
1933 $response = $this->getRequest()->response();
1935 if ( $this->mRedirect
!= '' ) {
1936 # Standards require redirect URLs to be absolute
1937 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1939 $redirect = $this->mRedirect
;
1940 $code = $this->mRedirectCode
;
1942 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1943 if( $code == '301' ||
$code == '303' ) {
1944 if( !$wgDebugRedirects ) {
1945 $message = HttpStatus
::getMessage( $code );
1946 $response->header( "HTTP/1.1 $code $message" );
1948 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1950 if ( $wgVaryOnXFP ) {
1951 $this->addVaryHeader( 'X-Forwarded-Proto' );
1953 $this->sendCacheControl();
1955 $response->header( "Content-Type: text/html; charset=utf-8" );
1956 if( $wgDebugRedirects ) {
1957 $url = htmlspecialchars( $redirect );
1958 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1959 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1960 print "</body>\n</html>\n";
1962 $response->header( 'Location: ' . $redirect );
1966 wfProfileOut( __METHOD__
);
1968 } elseif ( $this->mStatusCode
) {
1969 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1971 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1975 # Buffer output; final headers may depend on later processing
1978 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1979 $response->header( 'Content-language: ' . $wgLanguageCode );
1981 // Prevent framing, if requested
1982 $frameOptions = $this->getFrameOptions();
1983 if ( $frameOptions ) {
1984 $response->header( "X-Frame-Options: $frameOptions" );
1987 if ( $this->mArticleBodyOnly
) {
1988 $this->out( $this->mBodytext
);
1990 $this->addDefaultModules();
1992 $sk = $this->getSkin();
1994 // Hook that allows last minute changes to the output page, e.g.
1995 // adding of CSS or Javascript by extensions.
1996 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1998 wfProfileIn( 'Output-skin' );
2000 wfProfileOut( 'Output-skin' );
2003 // This hook allows last minute changes to final overall output by modifying output buffer
2004 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2006 $this->sendCacheControl();
2010 wfProfileOut( __METHOD__
);
2014 * Actually output something with print().
2016 * @param $ins String: the string to output
2018 public function out( $ins ) {
2023 * Produce a "user is blocked" page.
2024 * @deprecated since 1.18
2026 function blockedPage() {
2027 throw new UserBlockedError( $this->getUser()->mBlock
);
2031 * Prepare this object to display an error page; disable caching and
2032 * indexing, clear the current text and redirect, set the page's title
2033 * and optionally an custom HTML title (content of the "<title>" tag).
2035 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2036 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2037 * optional, if not passed the "<title>" attribute will be
2038 * based on $pageTitle
2040 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2041 $this->setPageTitle( $pageTitle );
2042 if ( $htmlTitle !== false ) {
2043 $this->setHTMLTitle( $htmlTitle );
2045 $this->setRobotPolicy( 'noindex,nofollow' );
2046 $this->setArticleRelated( false );
2047 $this->enableClientCache( false );
2048 $this->mRedirect
= '';
2049 $this->clearSubtitle();
2054 * Output a standard error page
2056 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2057 * showErrorPage( 'titlemsg', $messageObject );
2058 * showErrorPage( $titleMessageObj, $messageObject );
2060 * @param $title Mixed: message key (string) for page title, or a Message object
2061 * @param $msg Mixed: message key (string) for page text, or a Message object
2062 * @param $params Array: message parameters; ignored if $msg is a Message object
2064 public function showErrorPage( $title, $msg, $params = array() ) {
2065 if( !$title instanceof Message
) {
2066 $title = $this->msg( $title );
2069 $this->prepareErrorPage( $title );
2071 if ( $msg instanceof Message
){
2072 $this->addHTML( $msg->parseAsBlock() );
2074 $this->addWikiMsgArray( $msg, $params );
2077 $this->returnToMain();
2081 * Output a standard permission error page
2083 * @param $errors Array: error message keys
2084 * @param $action String: action that was denied or null if unknown
2086 public function showPermissionsErrorPage( $errors, $action = null ) {
2087 // For some action (read, edit, create and upload), display a "login to do this action"
2088 // error if all of the following conditions are met:
2089 // 1. the user is not logged in
2090 // 2. the only error is insufficient permissions (i.e. no block or something else)
2091 // 3. the error can be avoided simply by logging in
2092 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2093 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2094 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2095 && ( User
::groupHasPermission( 'user', $action )
2096 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2098 $displayReturnto = null;
2100 # Due to bug 32276, if a user does not have read permissions,
2101 # $this->getTitle() will just give Special:Badtitle, which is
2102 # not especially useful as a returnto parameter. Use the title
2103 # from the request instead, if there was one.
2104 $request = $this->getRequest();
2105 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2106 if ( $action == 'edit' ) {
2107 $msg = 'whitelistedittext';
2108 $displayReturnto = $returnto;
2109 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2110 $msg = 'nocreatetext';
2111 } elseif ( $action == 'upload' ) {
2112 $msg = 'uploadnologintext';
2114 $msg = 'loginreqpagetext';
2115 $displayReturnto = Title
::newMainPage();
2121 $query['returnto'] = $returnto->getPrefixedText();
2123 if ( !$request->wasPosted() ) {
2124 $returntoquery = $request->getValues();
2125 unset( $returntoquery['title'] );
2126 unset( $returntoquery['returnto'] );
2127 unset( $returntoquery['returntoquery'] );
2128 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2131 $loginLink = Linker
::linkKnown(
2132 SpecialPage
::getTitleFor( 'Userlogin' ),
2133 $this->msg( 'loginreqlink' )->escaped(),
2138 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2139 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2141 # Don't return to a page the user can't read otherwise
2142 # we'll end up in a pointless loop
2143 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2144 $this->returnToMain( null, $displayReturnto );
2147 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2148 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2153 * Display an error page indicating that a given version of MediaWiki is
2154 * required to use it
2156 * @param $version Mixed: the version of MediaWiki needed to use the page
2158 public function versionRequired( $version ) {
2159 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2161 $this->addWikiMsg( 'versionrequiredtext', $version );
2162 $this->returnToMain();
2166 * Display an error page noting that a given permission bit is required.
2167 * @deprecated since 1.18, just throw the exception directly
2168 * @param $permission String: key required
2169 * @throws PermissionsError
2171 public function permissionRequired( $permission ) {
2172 throw new PermissionsError( $permission );
2176 * Produce the stock "please login to use the wiki" page
2178 * @deprecated in 1.19; throw the exception directly
2180 public function loginToUse() {
2181 throw new PermissionsError( 'read' );
2185 * Format a list of error messages
2187 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2188 * @param $action String: action that was denied or null if unknown
2189 * @return String: the wikitext error-messages, formatted into a list.
2191 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2192 if ( $action == null ) {
2193 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2195 $action_desc = $this->msg( "action-$action" )->plain();
2197 'permissionserrorstext-withaction',
2200 )->plain() . "\n\n";
2203 if ( count( $errors ) > 1 ) {
2204 $text .= '<ul class="permissions-errors">' . "\n";
2206 foreach( $errors as $error ) {
2208 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2213 $text .= "<div class=\"permissions-errors\">\n" .
2214 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2222 * Display a page stating that the Wiki is in read-only mode,
2223 * and optionally show the source of the page that the user
2224 * was trying to edit. Should only be called (for this
2225 * purpose) after wfReadOnly() has returned true.
2227 * For historical reasons, this function is _also_ used to
2228 * show the error message when a user tries to edit a page
2229 * they are not allowed to edit. (Unless it's because they're
2230 * blocked, then we show blockedPage() instead.) In this
2231 * case, the second parameter should be set to true and a list
2232 * of reasons supplied as the third parameter.
2234 * @todo Needs to be split into multiple functions.
2236 * @param $source String: source code to show (or null).
2237 * @param $protected Boolean: is this a permissions error?
2238 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2239 * @param $action String: action that was denied or null if unknown
2240 * @throws ReadOnlyError
2242 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2243 $this->setRobotPolicy( 'noindex,nofollow' );
2244 $this->setArticleRelated( false );
2246 // If no reason is given, just supply a default "I can't let you do
2247 // that, Dave" message. Should only occur if called by legacy code.
2248 if ( $protected && empty( $reasons ) ) {
2249 $reasons[] = array( 'badaccess-group0' );
2252 if ( !empty( $reasons ) ) {
2253 // Permissions error
2255 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2256 $this->addBacklinkSubtitle( $this->getTitle() );
2258 $this->setPageTitle( $this->msg( 'badaccess' ) );
2260 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2262 // Wiki is read only
2263 throw new ReadOnlyError
;
2266 // Show source, if supplied
2267 if( is_string( $source ) ) {
2268 $this->addWikiMsg( 'viewsourcetext' );
2270 $pageLang = $this->getTitle()->getPageLanguage();
2272 'id' => 'wpTextbox1',
2273 'name' => 'wpTextbox1',
2274 'cols' => $this->getUser()->getOption( 'cols' ),
2275 'rows' => $this->getUser()->getOption( 'rows' ),
2276 'readonly' => 'readonly',
2277 'lang' => $pageLang->getHtmlCode(),
2278 'dir' => $pageLang->getDir(),
2280 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2282 // Show templates used by this article
2283 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2284 $this->addHTML( "<div class='templatesUsed'>
2290 # If the title doesn't exist, it's fairly pointless to print a return
2291 # link to it. After all, you just tried editing it and couldn't, so
2292 # what's there to do there?
2293 if( $this->getTitle()->exists() ) {
2294 $this->returnToMain( null, $this->getTitle() );
2299 * Turn off regular page output and return an error reponse
2300 * for when rate limiting has triggered.
2302 public function rateLimited() {
2303 throw new ThrottledError
;
2307 * Show a warning about slave lag
2309 * If the lag is higher than $wgSlaveLagCritical seconds,
2310 * then the warning is a bit more obvious. If the lag is
2311 * lower than $wgSlaveLagWarning, then no warning is shown.
2313 * @param $lag Integer: slave lag
2315 public function showLagWarning( $lag ) {
2316 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2317 if( $lag >= $wgSlaveLagWarning ) {
2318 $message = $lag < $wgSlaveLagCritical
2321 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2322 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2326 public function showFatalError( $message ) {
2327 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2329 $this->addHTML( $message );
2332 public function showUnexpectedValueError( $name, $val ) {
2333 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2336 public function showFileCopyError( $old, $new ) {
2337 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2340 public function showFileRenameError( $old, $new ) {
2341 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2344 public function showFileDeleteError( $name ) {
2345 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2348 public function showFileNotFoundError( $name ) {
2349 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2353 * Add a "return to" link pointing to a specified title
2355 * @param $title Title to link
2356 * @param $query Array query string parameters
2357 * @param $text String text of the link (input is not escaped)
2358 * @param $options Options array to pass to Linker
2360 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2361 if( in_array( 'http', $options ) ) {
2362 $proto = PROTO_HTTP
;
2363 } elseif( in_array( 'https', $options ) ) {
2364 $proto = PROTO_HTTPS
;
2366 $proto = PROTO_RELATIVE
;
2369 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2370 $link = $this->msg( 'returnto' )->rawParams(
2371 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2372 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2376 * Add a "return to" link pointing to a specified title,
2377 * or the title indicated in the request, or else the main page
2380 * @param $returnto Title or String to return to
2381 * @param $returntoquery String: query string for the return to link
2383 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2384 if ( $returnto == null ) {
2385 $returnto = $this->getRequest()->getText( 'returnto' );
2388 if ( $returntoquery == null ) {
2389 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2392 if ( $returnto === '' ) {
2393 $returnto = Title
::newMainPage();
2396 if ( is_object( $returnto ) ) {
2397 $titleObj = $returnto;
2399 $titleObj = Title
::newFromText( $returnto );
2401 if ( !is_object( $titleObj ) ) {
2402 $titleObj = Title
::newMainPage();
2405 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2409 * @param $sk Skin The given Skin
2410 * @param $includeStyle Boolean: unused
2411 * @return String: The doctype, opening "<html>", and head element.
2413 public function headElement( Skin
$sk, $includeStyle = true ) {
2416 $userdir = $this->getLanguage()->getDir();
2417 $sitedir = $wgContLang->getDir();
2419 if ( $sk->commonPrintStylesheet() ) {
2420 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2423 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2425 if ( $this->getHTMLTitle() == '' ) {
2426 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2429 $openHead = Html
::openElement( 'head' );
2431 # Don't bother with the newline if $head == ''
2432 $ret .= "$openHead\n";
2435 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2437 $ret .= implode( "\n", array(
2438 $this->getHeadLinks( null, true ),
2439 $this->buildCssLinks(),
2440 $this->getHeadScripts(),
2441 $this->getHeadItems()
2444 $closeHead = Html
::closeElement( 'head' );
2446 $ret .= "$closeHead\n";
2449 $bodyAttrs = array();
2451 # Classes for LTR/RTL directionality support
2452 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2454 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2455 # A <body> class is probably not the best way to do this . . .
2456 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2458 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2459 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2460 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2462 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2463 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2465 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2471 * Add the default ResourceLoader modules to this object
2473 private function addDefaultModules() {
2474 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2475 $wgAjaxWatch, $wgResponsiveImages;
2477 // Add base resources
2478 $this->addModules( array(
2480 'mediawiki.page.startup',
2481 'mediawiki.page.ready',
2483 if ( $wgIncludeLegacyJavaScript ){
2484 $this->addModules( 'mediawiki.legacy.wikibits' );
2487 if ( $wgPreloadJavaScriptMwUtil ) {
2488 $this->addModules( 'mediawiki.util' );
2491 MWDebug
::addModules( $this );
2493 // Add various resources if required
2495 $this->addModules( 'mediawiki.legacy.ajax' );
2497 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2499 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2500 $this->addModules( 'mediawiki.page.watch.ajax' );
2503 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2504 $this->addModules( 'mediawiki.searchSuggest' );
2508 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2509 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2512 # Crazy edit-on-double-click stuff
2513 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2514 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2517 // Support for high-density display images
2518 if ( $wgResponsiveImages ) {
2519 $this->addModules( 'mediawiki.hidpi' );
2524 * Get a ResourceLoader object associated with this OutputPage
2526 * @return ResourceLoader
2528 public function getResourceLoader() {
2529 if ( is_null( $this->mResourceLoader
) ) {
2530 $this->mResourceLoader
= new ResourceLoader();
2532 return $this->mResourceLoader
;
2537 * @param $modules Array/string with the module name(s)
2538 * @param $only String ResourceLoaderModule TYPE_ class constant
2539 * @param $useESI boolean
2540 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2541 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2542 * @return string html "<script>" and "<style>" tags
2544 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2545 global $wgResourceLoaderUseESI;
2547 $modules = (array) $modules;
2549 if ( !count( $modules ) ) {
2553 if ( count( $modules ) > 1 ) {
2554 // Remove duplicate module requests
2555 $modules = array_unique( $modules );
2556 // Sort module names so requests are more uniform
2559 if ( ResourceLoader
::inDebugMode() ) {
2560 // Recursively call us for every item
2562 foreach ( $modules as $name ) {
2563 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2569 // Create keyed-by-group list of module objects from modules list
2571 $resourceLoader = $this->getResourceLoader();
2572 foreach ( $modules as $name ) {
2573 $module = $resourceLoader->getModule( $name );
2574 # Check that we're allowed to include this module on this page
2576 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2577 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2578 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2579 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2585 $group = $module->getGroup();
2586 if ( !isset( $groups[$group] ) ) {
2587 $groups[$group] = array();
2589 $groups[$group][$name] = $module;
2593 foreach ( $groups as $group => $grpModules ) {
2594 // Special handling for user-specific groups
2596 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2597 $user = $this->getUser()->getName();
2600 // Create a fake request based on the one we are about to make so modules return
2601 // correct timestamp and emptiness data
2602 $query = ResourceLoader
::makeLoaderQuery(
2603 array(), // modules; not determined yet
2604 $this->getLanguage()->getCode(),
2605 $this->getSkin()->getSkinName(),
2607 null, // version; not determined yet
2608 ResourceLoader
::inDebugMode(),
2609 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2610 $this->isPrintable(),
2611 $this->getRequest()->getBool( 'handheld' ),
2614 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2615 // Extract modules that know they're empty
2616 $emptyModules = array ();
2617 foreach ( $grpModules as $key => $module ) {
2618 if ( $module->isKnownEmpty( $context ) ) {
2619 $emptyModules[$key] = 'ready';
2620 unset( $grpModules[$key] );
2623 // Inline empty modules: since they're empty, just mark them as 'ready'
2624 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2625 // If we're only getting the styles, we don't need to do anything for empty modules.
2626 $links .= Html
::inlineScript(
2628 ResourceLoader
::makeLoaderConditionalScript(
2630 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2637 // If there are no modules left, skip this group
2638 if ( count( $grpModules ) === 0 ) {
2642 // Inline private modules. These can't be loaded through load.php for security
2643 // reasons, see bug 34907. Note that these modules should be loaded from
2644 // getHeadScripts() before the first loader call. Otherwise other modules can't
2645 // properly use them as dependencies (bug 30914)
2646 if ( $group === 'private' ) {
2647 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2648 $links .= Html
::inlineStyle(
2649 $resourceLoader->makeModuleResponse( $context, $grpModules )
2652 $links .= Html
::inlineScript(
2653 ResourceLoader
::makeLoaderConditionalScript(
2654 $resourceLoader->makeModuleResponse( $context, $grpModules )
2661 // Special handling for the user group; because users might change their stuff
2662 // on-wiki like user pages, or user preferences; we need to find the highest
2663 // timestamp of these user-changable modules so we can ensure cache misses on change
2664 // This should NOT be done for the site group (bug 27564) because anons get that too
2665 // and we shouldn't be putting timestamps in Squid-cached HTML
2667 if ( $group === 'user' ) {
2668 // Get the maximum timestamp
2670 foreach ( $grpModules as $module ) {
2671 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2673 // Add a version parameter so cache will break when things change
2674 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2677 $url = ResourceLoader
::makeLoaderURL(
2678 array_keys( $grpModules ),
2679 $this->getLanguage()->getCode(),
2680 $this->getSkin()->getSkinName(),
2683 ResourceLoader
::inDebugMode(),
2684 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2685 $this->isPrintable(),
2686 $this->getRequest()->getBool( 'handheld' ),
2689 if ( $useESI && $wgResourceLoaderUseESI ) {
2690 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2691 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2692 $link = Html
::inlineStyle( $esi );
2694 $link = Html
::inlineScript( $esi );
2697 // Automatically select style/script elements
2698 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2699 $link = Html
::linkedStyle( $url );
2700 } else if ( $loadCall ) {
2701 $link = Html
::inlineScript(
2702 ResourceLoader
::makeLoaderConditionalScript(
2703 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2707 $link = Html
::linkedScript( $url );
2711 if( $group == 'noscript' ){
2712 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2714 $links .= $link . "\n";
2721 * JS stuff to put in the "<head>". This is the startup module, config
2722 * vars and modules marked with position 'top'
2724 * @return String: HTML fragment
2726 function getHeadScripts() {
2727 global $wgResourceLoaderExperimentalAsyncLoading;
2729 // Startup - this will immediately load jquery and mediawiki modules
2730 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2732 // Load config before anything else
2733 $scripts .= Html
::inlineScript(
2734 ResourceLoader
::makeLoaderConditionalScript(
2735 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2739 // Load embeddable private modules before any loader links
2740 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2741 // in mw.loader.implement() calls and deferred until mw.user is available
2742 $embedScripts = array( 'user.options', 'user.tokens' );
2743 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2745 // Script and Messages "only" requests marked for top inclusion
2746 // Messages should go first
2747 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2748 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2750 // Modules requests - let the client calculate dependencies and batch requests as it likes
2751 // Only load modules that have marked themselves for loading at the top
2752 $modules = $this->getModules( true, 'top' );
2754 $scripts .= Html
::inlineScript(
2755 ResourceLoader
::makeLoaderConditionalScript(
2756 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2761 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2762 $scripts .= $this->getScriptsForBottomQueue( true );
2769 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2770 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2771 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2772 * user preferences, site JS and user JS
2774 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2777 function getScriptsForBottomQueue( $inHead ) {
2778 global $wgUseSiteJs, $wgAllowUserJs;
2780 // Script and Messages "only" requests marked for bottom inclusion
2781 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2782 // Messages should go first
2783 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2784 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2785 /* $loadCall = */ $inHead
2787 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2788 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2789 /* $loadCall = */ $inHead
2792 // Modules requests - let the client calculate dependencies and batch requests as it likes
2793 // Only load modules that have marked themselves for loading at the bottom
2794 $modules = $this->getModules( true, 'bottom' );
2796 $scripts .= Html
::inlineScript(
2797 ResourceLoader
::makeLoaderConditionalScript(
2798 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2804 $scripts .= "\n" . $this->mScripts
;
2806 $defaultModules = array();
2808 // Add site JS if enabled
2809 if ( $wgUseSiteJs ) {
2810 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2811 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2813 $defaultModules['site'] = 'loading';
2815 // The wiki is configured to not allow a site module.
2816 $defaultModules['site'] = 'missing';
2819 // Add user JS if enabled
2820 if ( $wgAllowUserJs ) {
2821 if ( $this->getUser()->isLoggedIn() ) {
2822 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2823 # XXX: additional security check/prompt?
2824 // We're on a preview of a JS subpage
2825 // Exclude this page from the user module in case it's in there (bug 26283)
2826 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2827 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2829 // Load the previewed JS
2830 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2831 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2832 // asynchronously and may arrive *after* the inline script here. So the previewed code
2833 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2835 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2836 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2837 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2840 $defaultModules['user'] = 'loading';
2842 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2843 // blocking default gadgets that might depend on it. Although arguably default-enabled
2844 // gadgets should not depend on the user module, it's harmless and less error-prone to
2845 // handle this case.
2846 $defaultModules['user'] = 'ready';
2850 $defaultModules['user'] = 'missing';
2853 // Group JS is only enabled if site JS is enabled.
2854 if ( $wgUseSiteJs ) {
2855 if ( $this->getUser()->isLoggedIn() ) {
2856 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2857 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2859 $defaultModules['user.groups'] = 'loading';
2861 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2862 // avoid blocking gadgets that might depend upon the module.
2863 $defaultModules['user.groups'] = 'ready';
2866 // Site (and group JS) disabled
2867 $defaultModules['user.groups'] = 'missing';
2872 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2873 foreach ( $defaultModules as $m => $state ) {
2874 if ( $state == 'loading' ) {
2875 unset( $defaultModules[$m] );
2879 if ( count( $defaultModules ) > 0 ) {
2880 $loaderInit = Html
::inlineScript(
2881 ResourceLoader
::makeLoaderConditionalScript(
2882 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2886 return $loaderInit . $scripts;
2890 * JS stuff to put at the bottom of the "<body>"
2893 function getBottomScripts() {
2894 global $wgResourceLoaderExperimentalAsyncLoading;
2895 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2896 return $this->getScriptsForBottomQueue( false );
2903 * Add one or more variables to be set in mw.config in JavaScript.
2905 * @param $keys {String|Array} Key or array of key/value pairs.
2906 * @param $value {Mixed} [optional] Value of the configuration variable.
2908 public function addJsConfigVars( $keys, $value = null ) {
2909 if ( is_array( $keys ) ) {
2910 foreach ( $keys as $key => $value ) {
2911 $this->mJsConfigVars
[$key] = $value;
2916 $this->mJsConfigVars
[$keys] = $value;
2921 * Get an array containing the variables to be set in mw.config in JavaScript.
2923 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2924 * This is only public until that function is removed. You have been warned.
2926 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2927 * - in other words, page-independent/site-wide variables (without state).
2928 * You will only be adding bloat to the html page and causing page caches to
2929 * have to be purged on configuration changes.
2932 public function getJSVars() {
2937 $canonicalName = false; # bug 21115
2939 $title = $this->getTitle();
2940 $ns = $title->getNamespace();
2941 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2943 // Get the relevant title so that AJAX features can use the correct page name
2944 // when making API requests from certain special pages (bug 34972).
2945 $relevantTitle = $this->getSkin()->getRelevantTitle();
2947 if ( $ns == NS_SPECIAL
) {
2948 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2949 } elseif ( $this->canUseWikiPage() ) {
2950 $wikiPage = $this->getWikiPage();
2951 $latestRevID = $wikiPage->getLatest();
2952 $pageID = $wikiPage->getId();
2955 $lang = $title->getPageLanguage();
2957 // Pre-process information
2958 $separatorTransTable = $lang->separatorTransformTable();
2959 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2960 $compactSeparatorTransTable = array(
2961 implode( "\t", array_keys( $separatorTransTable ) ),
2962 implode( "\t", $separatorTransTable ),
2964 $digitTransTable = $lang->digitTransformTable();
2965 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2966 $compactDigitTransTable = array(
2967 implode( "\t", array_keys( $digitTransTable ) ),
2968 implode( "\t", $digitTransTable ),
2972 'wgCanonicalNamespace' => $nsname,
2973 'wgCanonicalSpecialPageName' => $canonicalName,
2974 'wgNamespaceNumber' => $title->getNamespace(),
2975 'wgPageName' => $title->getPrefixedDBKey(),
2976 'wgTitle' => $title->getText(),
2977 'wgCurRevisionId' => $latestRevID,
2978 'wgArticleId' => $pageID,
2979 'wgIsArticle' => $this->isArticle(),
2980 'wgAction' => Action
::getActionName( $this->getContext() ),
2981 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2982 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2983 'wgCategories' => $this->getCategories(),
2984 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2985 'wgPageContentLanguage' => $lang->getCode(),
2986 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2987 'wgDigitTransformTable' => $compactDigitTransTable,
2988 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
2989 'wgMonthNames' => $lang->getMonthNamesArray(),
2990 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
2991 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2993 if ( $wgContLang->hasVariants() ) {
2994 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2996 foreach ( $title->getRestrictionTypes() as $type ) {
2997 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2999 if ( $title->isMainPage() ) {
3000 $vars['wgIsMainPage'] = true;
3002 if ( $this->mRedirectedFrom
) {
3003 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
3006 // Allow extensions to add their custom variables to the mw.config map.
3007 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3008 // page-dependant but site-wide (without state).
3009 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3010 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3012 // Merge in variables from addJsConfigVars last
3013 return array_merge( $vars, $this->mJsConfigVars
);
3017 * To make it harder for someone to slip a user a fake
3018 * user-JavaScript or user-CSS preview, a random token
3019 * is associated with the login session. If it's not
3020 * passed back with the preview request, we won't render
3025 public function userCanPreview() {
3026 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3027 ||
!$this->getRequest()->wasPosted()
3028 ||
!$this->getUser()->matchEditToken(
3029 $this->getRequest()->getVal( 'wpEditToken' ) )
3033 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3037 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3041 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3043 * @return array in format "link name or number => 'link html'".
3045 public function getHeadLinksArray( $addContentType = false ) {
3046 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3047 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3048 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3049 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3050 $wgRightsPage, $wgRightsUrl;
3054 $canonicalUrl = $this->mCanonicalUrl
;
3056 if ( $addContentType ) {
3058 # More succinct than <meta http-equiv=Content-Type>, has the
3060 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3062 $tags['meta-content-type'] = Html
::element( 'meta', array(
3063 'http-equiv' => 'Content-Type',
3064 'content' => "$wgMimeType; charset=UTF-8"
3066 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3067 'http-equiv' => 'Content-Style-Type',
3068 'content' => 'text/css'
3073 $tags['meta-generator'] = Html
::element( 'meta', array(
3074 'name' => 'generator',
3075 'content' => "MediaWiki $wgVersion",
3078 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3079 if( $p !== 'index,follow' ) {
3080 // http://www.robotstxt.org/wc/meta-user.html
3081 // Only show if it's different from the default robots policy
3082 $tags['meta-robots'] = Html
::element( 'meta', array(
3088 if ( count( $this->mKeywords
) > 0 ) {
3090 "/<.*?" . ">/" => '',
3093 $tags['meta-keywords'] = Html
::element( 'meta', array(
3094 'name' => 'keywords',
3095 'content' => preg_replace(
3096 array_keys( $strip ),
3097 array_values( $strip ),
3098 implode( ',', $this->mKeywords
)
3103 foreach ( $this->mMetatags
as $tag ) {
3104 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3106 $tag[0] = substr( $tag[0], 5 );
3110 $tagName = "meta-{$tag[0]}";
3111 if ( isset( $tags[$tagName] ) ) {
3112 $tagName .= $tag[1];
3114 $tags[$tagName] = Html
::element( 'meta',
3117 'content' => $tag[1]
3122 foreach ( $this->mLinktags
as $tag ) {
3123 $tags[] = Html
::element( 'link', $tag );
3126 # Universal edit button
3127 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3128 $user = $this->getUser();
3129 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3130 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3131 // Original UniversalEditButton
3132 $msg = $this->msg( 'edit' )->text();
3133 $tags['universal-edit-button'] = Html
::element( 'link', array(
3134 'rel' => 'alternate',
3135 'type' => 'application/x-wiki',
3137 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3139 // Alternate edit link
3140 $tags['alternative-edit'] = Html
::element( 'link', array(
3143 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3148 # Generally the order of the favicon and apple-touch-icon links
3149 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3150 # uses whichever one appears later in the HTML source. Make sure
3151 # apple-touch-icon is specified first to avoid this.
3152 if ( $wgAppleTouchIcon !== false ) {
3153 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3156 if ( $wgFavicon !== false ) {
3157 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3160 # OpenSearch description link
3161 $tags['opensearch'] = Html
::element( 'link', array(
3163 'type' => 'application/opensearchdescription+xml',
3164 'href' => wfScript( 'opensearch_desc' ),
3165 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3168 if ( $wgEnableAPI ) {
3169 # Real Simple Discovery link, provides auto-discovery information
3170 # for the MediaWiki API (and potentially additional custom API
3171 # support such as WordPress or Twitter-compatible APIs for a
3172 # blogging extension, etc)
3173 $tags['rsd'] = Html
::element( 'link', array(
3175 'type' => 'application/rsd+xml',
3176 // Output a protocol-relative URL here if $wgServer is protocol-relative
3177 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3178 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3184 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3185 $lang = $this->getTitle()->getPageLanguage();
3186 if ( $lang->hasVariants() ) {
3188 $urlvar = $lang->getURLVariant();
3191 $variants = $lang->getVariants();
3192 foreach ( $variants as $_v ) {
3193 $tags["variant-$_v"] = Html
::element( 'link', array(
3194 'rel' => 'alternate',
3196 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3200 $canonicalUrl = $this->getTitle()->getLocalURL();
3207 if ( $wgRightsPage ) {
3208 $copy = Title
::newFromText( $wgRightsPage );
3211 $copyright = $copy->getLocalURL();
3215 if ( !$copyright && $wgRightsUrl ) {
3216 $copyright = $wgRightsUrl;
3220 $tags['copyright'] = Html
::element( 'link', array(
3221 'rel' => 'copyright',
3222 'href' => $copyright )
3228 foreach( $this->getSyndicationLinks() as $format => $link ) {
3229 # Use the page name for the title. In principle, this could
3230 # lead to issues with having the same name for different feeds
3231 # corresponding to the same page, but we can't avoid that at
3234 $tags[] = $this->feedLink(
3237 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3238 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3242 # Recent changes feed should appear on every page (except recentchanges,
3243 # that would be redundant). Put it after the per-page feed to avoid
3244 # changing existing behavior. It's still available, probably via a
3245 # menu in your browser. Some sites might have a different feed they'd
3246 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3247 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3248 # If so, use it instead.
3249 if ( $wgOverrideSiteFeed ) {
3250 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3251 // Note, this->feedLink escapes the url.
3252 $tags[] = $this->feedLink(
3255 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3258 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3259 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3260 foreach ( $wgAdvertisedFeedTypes as $format ) {
3261 $tags[] = $this->feedLink(
3263 $rctitle->getLocalURL( "feed={$format}" ),
3264 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3271 global $wgEnableCanonicalServerLink;
3272 if ( $wgEnableCanonicalServerLink ) {
3273 if ( $canonicalUrl !== false ) {
3274 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3276 $reqUrl = $this->getRequest()->getRequestURL();
3277 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3280 if ( $canonicalUrl !== false ) {
3281 $tags[] = Html
::element( 'link', array(
3282 'rel' => 'canonical',
3283 'href' => $canonicalUrl
3292 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3294 * @return string HTML tag links to be put in the header.
3296 public function getHeadLinks( $unused = null, $addContentType = false ) {
3297 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3301 * Generate a "<link rel/>" for a feed.
3303 * @param $type String: feed type
3304 * @param $url String: URL to the feed
3305 * @param $text String: value of the "title" attribute
3306 * @return String: HTML fragment
3308 private function feedLink( $type, $url, $text ) {
3309 return Html
::element( 'link', array(
3310 'rel' => 'alternate',
3311 'type' => "application/$type+xml",
3318 * Add a local or specified stylesheet, with the given media options.
3319 * Meant primarily for internal use...
3321 * @param $style String: URL to the file
3322 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3323 * @param $condition String: for IE conditional comments, specifying an IE version
3324 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3326 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3328 // Even though we expect the media type to be lowercase, but here we
3329 // force it to lowercase to be safe.
3331 $options['media'] = $media;
3334 $options['condition'] = $condition;
3337 $options['dir'] = $dir;
3339 $this->styles
[$style] = $options;
3343 * Adds inline CSS styles
3344 * @param $style_css Mixed: inline CSS
3345 * @param $flip String: Set to 'flip' to flip the CSS if needed
3347 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3348 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3349 # If wanted, and the interface is right-to-left, flip the CSS
3350 $style_css = CSSJanus
::transform( $style_css, true, false );
3352 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3356 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3357 * These will be applied to various media & IE conditionals.
3361 public function buildCssLinks() {
3362 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3363 $wgLang, $wgContLang;
3365 $this->getSkin()->setupSkinUserCss( $this );
3367 // Add ResourceLoader styles
3368 // Split the styles into four groups
3369 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3370 $otherTags = ''; // Tags to append after the normal <link> tags
3371 $resourceLoader = $this->getResourceLoader();
3373 $moduleStyles = $this->getModuleStyles();
3375 // Per-site custom styles
3376 if ( $wgUseSiteCss ) {
3377 $moduleStyles[] = 'site';
3378 $moduleStyles[] = 'noscript';
3379 if( $this->getUser()->isLoggedIn() ){
3380 $moduleStyles[] = 'user.groups';
3384 // Per-user custom styles
3385 if ( $wgAllowUserCss ) {
3386 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3387 // We're on a preview of a CSS subpage
3388 // Exclude this page from the user module in case it's in there (bug 26283)
3389 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3390 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3393 // Load the previewed CSS
3394 // If needed, Janus it first. This is user-supplied CSS, so it's
3395 // assumed to be right for the content language directionality.
3396 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3397 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3398 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3400 $otherTags .= Html
::inlineStyle( $previewedCSS );
3402 // Load the user styles normally
3403 $moduleStyles[] = 'user';
3407 // Per-user preference styles
3408 if ( $wgAllowUserCssPrefs ) {
3409 $moduleStyles[] = 'user.cssprefs';
3412 foreach ( $moduleStyles as $name ) {
3413 $module = $resourceLoader->getModule( $name );
3417 $group = $module->getGroup();
3418 // Modules in groups named "other" or anything different than "user", "site" or "private"
3419 // will be placed in the "other" group
3420 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3423 // We want site, private and user styles to override dynamically added styles from modules, but we want
3424 // dynamically added styles to override statically added styles from other modules. So the order
3425 // has to be other, dynamic, site, private, user
3426 // Add statically added styles for other modules
3427 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3428 // Add normal styles added through addStyle()/addInlineStyle() here
3429 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3430 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3431 // We use a <meta> tag with a made-up name for this because that's valid HTML
3432 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3434 // Add site, private and user styles
3435 // 'private' at present only contains user.options, so put that before 'user'
3436 // Any future private modules will likely have a similar user-specific character
3437 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3438 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3439 ResourceLoaderModule
::TYPE_STYLES
3443 // Add stuff in $otherTags (previewed user CSS if applicable)
3451 public function buildCssLinksArray() {
3454 // Add any extension CSS
3455 foreach ( $this->mExtStyles
as $url ) {
3456 $this->addStyle( $url );
3458 $this->mExtStyles
= array();
3460 foreach( $this->styles
as $file => $options ) {
3461 $link = $this->styleLink( $file, $options );
3463 $links[$file] = $link;
3470 * Generate \<link\> tags for stylesheets
3472 * @param $style String: URL to the file
3473 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3475 * @return String: HTML fragment
3477 protected function styleLink( $style, $options ) {
3478 if( isset( $options['dir'] ) ) {
3479 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3484 if( isset( $options['media'] ) ) {
3485 $media = self
::transformCssMedia( $options['media'] );
3486 if( is_null( $media ) ) {
3493 if( substr( $style, 0, 1 ) == '/' ||
3494 substr( $style, 0, 5 ) == 'http:' ||
3495 substr( $style, 0, 6 ) == 'https:' ) {
3498 global $wgStylePath, $wgStyleVersion;
3499 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3502 $link = Html
::linkedStyle( $url, $media );
3504 if( isset( $options['condition'] ) ) {
3505 $condition = htmlspecialchars( $options['condition'] );
3506 $link = "<!--[if $condition]>$link<![endif]-->";
3512 * Transform "media" attribute based on request parameters
3514 * @param $media String: current value of the "media" attribute
3515 * @return String: modified value of the "media" attribute
3517 public static function transformCssMedia( $media ) {
3518 global $wgRequest, $wgHandheldForIPhone;
3520 // Switch in on-screen display for media testing
3522 'printable' => 'print',
3523 'handheld' => 'handheld',
3525 foreach( $switches as $switch => $targetMedia ) {
3526 if( $wgRequest->getBool( $switch ) ) {
3527 if( $media == $targetMedia ) {
3529 } elseif( $media == 'screen' ) {
3535 // Expand longer media queries as iPhone doesn't grok 'handheld'
3536 if( $wgHandheldForIPhone ) {
3537 $mediaAliases = array(
3538 'screen' => 'screen and (min-device-width: 481px)',
3539 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3542 if( isset( $mediaAliases[$media] ) ) {
3543 $media = $mediaAliases[$media];
3551 * Add a wikitext-formatted message to the output.
3552 * This is equivalent to:
3554 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3556 public function addWikiMsg( /*...*/ ) {
3557 $args = func_get_args();
3558 $name = array_shift( $args );
3559 $this->addWikiMsgArray( $name, $args );
3563 * Add a wikitext-formatted message to the output.
3564 * Like addWikiMsg() except the parameters are taken as an array
3565 * instead of a variable argument list.
3567 * @param $name string
3568 * @param $args array
3570 public function addWikiMsgArray( $name, $args ) {
3571 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3575 * This function takes a number of message/argument specifications, wraps them in
3576 * some overall structure, and then parses the result and adds it to the output.
3578 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3579 * on. The subsequent arguments may either be strings, in which case they are the
3580 * message names, or arrays, in which case the first element is the message name,
3581 * and subsequent elements are the parameters to that message.
3583 * Don't use this for messages that are not in users interface language.
3587 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3591 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3593 * The newline after opening div is needed in some wikitext. See bug 19226.
3595 * @param $wrap string
3597 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3598 $msgSpecs = func_get_args();
3599 array_shift( $msgSpecs );
3600 $msgSpecs = array_values( $msgSpecs );
3602 foreach ( $msgSpecs as $n => $spec ) {
3603 if ( is_array( $spec ) ) {
3605 $name = array_shift( $args );
3606 if ( isset( $args['options'] ) ) {
3607 unset( $args['options'] );
3609 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3617 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3619 $this->addWikiText( $s );
3623 * Include jQuery core. Use this to avoid loading it multiple times
3624 * before we get a usable script loader.
3626 * @param $modules Array: list of jQuery modules which should be loaded
3627 * @return Array: the list of modules which were not loaded.
3629 * @deprecated since 1.17
3631 public function includeJQuery( $modules = array() ) {