2 if ( !defined( 'MEDIAWIKI' ) ) {
7 * This class should be covered by a general architecture document which does
8 * not exist as of January 2011. This is one of the Core classes and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * @todo FIXME: Another class handles sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
21 class OutputPage
extends ContextSource
{
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
33 /// Should be private - has getter and setter. Contains the HTML title
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
40 * Holds the debug lines that will be output as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 /// Should be private. Stores contents of <title> tag
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = false;
53 * Should be private. Has get/set methods properly documented.
54 * Stores "article flag" toggle.
56 var $mIsArticleRelated = true;
59 * Should be private. We have to set isPrintable(). Some pages should
60 * never be printed (ex: redirections).
62 var $mPrintable = false;
65 * Should be private. We have set/get/append methods.
67 * Contains the page subtitle. Special pages usually have some links here.
68 * Don't confuse with site subtitle added by skins.
70 private $mSubtitle = array();
76 * mLastModified and mEtag are used for sending cache control.
77 * The whole caching system should probably be moved into its own class.
79 var $mLastModified = '';
82 * Should be private. No getter but used in sendCacheControl();
83 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
84 * as a unique identifier for the content. It is later used by the client
85 * to compare its cached version with the server version. Client sends
86 * headers If-Match and If-None-Match containing its locally cached ETAG value.
88 * To get more information, you will have to look at HTTP/1.1 protocol which
89 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
93 var $mCategoryLinks = array();
94 var $mCategories = array();
96 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
97 var $mLanguageLinks = array();
100 * Should be private. Used for JavaScript (pre resource loader)
101 * We should split js / css.
102 * mScripts content is inserted as is in <head> by Skin. This might contains
103 * either a link to a stylesheet or inline css.
108 * Inline CSS styles. Use addInlineStyle() sparsingly
110 var $mInlineStyles = '';
116 * Used by skin template.
117 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
119 var $mPageLinkTitle = '';
121 /// Array of elements in <head>. Parser might add its own headers!
122 var $mHeadItems = array();
124 // @todo FIXME: Next variables probably comes from the resource loader
125 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
126 var $mResourceLoader;
127 var $mJsConfigVars = array();
129 /** @todo FIXME: Is this still used ?*/
130 var $mInlineMsg = array();
132 var $mTemplateIds = array();
133 var $mImageTimeKeys = array();
135 var $mRedirectCode = '';
137 var $mFeedLinksAppendQuery = null;
139 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
140 # @see ResourceLoaderModule::$origin
141 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
142 protected $mAllowedModules = array(
143 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
147 * @EasterEgg I just love the name for this self documenting variable.
150 var $mDoNothing = false;
153 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
156 * lazy initialised, use parserOptions()
159 protected $mParserOptions = null;
162 * Handles the atom / rss links.
163 * We probably only support atom in 2011.
164 * Looks like a private variable.
165 * @see $wgAdvertisedFeedTypes
167 var $mFeedLinks = array();
169 // Gwicke work on squid caching? Roughly from 2003.
170 var $mEnableClientCache = true;
173 * Flag if output should only contain the body of the article.
176 var $mArticleBodyOnly = false;
178 var $mNewSectionLink = false;
179 var $mHideNewSectionLink = false;
182 * Comes from the parser. This was probably made to load CSS/JS only
183 * if we had <gallery>. Used directly in CategoryPage.php
184 * Looks like resource loader can replace this.
186 var $mNoGallery = false;
188 // should be private.
189 var $mPageTitleActionText = '';
190 var $mParseWarnings = array();
192 // Cache stuff. Looks like mEnableClientCache
193 var $mSquidMaxage = 0;
196 var $mPreventClickjacking = true;
198 /// should be private. To include the variable {{REVISIONID}}
199 var $mRevisionId = null;
201 var $mFileVersion = null;
204 * An array of stylesheet filenames (relative from skins path), with options
205 * for CSS media, IE conditions, and RTL/LTR direction.
206 * For internal use; add settings in the skin via $this->addStyle()
208 * Style again! This seems like a code duplication since we already have
209 * mStyles. This is what makes OpenSource amazing.
211 var $styles = array();
214 * Whether jQuery is already handled.
216 protected $mJQueryDone = false;
218 private $mIndexPolicy = 'index';
219 private $mFollowPolicy = 'follow';
220 private $mVaryHeader = array(
221 'Accept-Encoding' => array( 'list-contains=gzip' ),
226 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
231 private $mRedirectedFrom = null;
234 * Constructor for OutputPage. This should not be called directly.
235 * Instead a new RequestContext should be created and it will implicitly create
236 * a OutputPage tied to that context.
238 function __construct( IContextSource
$context = null ) {
239 if ( $context === null ) {
240 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
241 wfDeprecated( __METHOD__
);
243 $this->setContext( $context );
248 * Redirect to $url rather than displaying the normal page
250 * @param $url String: URL
251 * @param $responsecode String: HTTP status code
253 public function redirect( $url, $responsecode = '302' ) {
254 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
255 $this->mRedirect
= str_replace( "\n", '', $url );
256 $this->mRedirectCode
= $responsecode;
260 * Get the URL to redirect to, or an empty string if not redirect URL set
264 public function getRedirect() {
265 return $this->mRedirect
;
269 * Set the HTTP status code to send with the output.
271 * @param $statusCode Integer
273 public function setStatusCode( $statusCode ) {
274 $this->mStatusCode
= $statusCode;
278 * Add a new <meta> tag
279 * To add an http-equiv meta tag, precede the name with "http:"
281 * @param $name String tag name
282 * @param $val String tag value
284 function addMeta( $name, $val ) {
285 array_push( $this->mMetatags
, array( $name, $val ) );
289 * Add a keyword or a list of keywords in the page header
291 * @param $text String or array of strings
293 function addKeyword( $text ) {
294 if( is_array( $text ) ) {
295 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
297 array_push( $this->mKeywords
, $text );
302 * Add a new \<link\> tag to the page header
304 * @param $linkarr Array: associative array of attributes.
306 function addLink( $linkarr ) {
307 array_push( $this->mLinktags
, $linkarr );
311 * Add a new \<link\> with "rel" attribute set to "meta"
313 * @param $linkarr Array: associative array mapping attribute names to their
314 * values, both keys and values will be escaped, and the
315 * "rel" attribute will be automatically added
317 function addMetadataLink( $linkarr ) {
318 $linkarr['rel'] = $this->getMetadataAttribute();
319 $this->addLink( $linkarr );
323 * Get the value of the "rel" attribute for metadata links
327 public function getMetadataAttribute() {
328 # note: buggy CC software only reads first "meta" link
329 static $haveMeta = false;
331 return 'alternate meta';
339 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
341 * @param $script String: raw HTML
343 function addScript( $script ) {
344 $this->mScripts
.= $script . "\n";
348 * Register and add a stylesheet from an extension directory.
350 * @param $url String path to sheet. Provide either a full url (beginning
351 * with 'http', etc) or a relative path from the document root
352 * (beginning with '/'). Otherwise it behaves identically to
353 * addStyle() and draws from the /skins folder.
355 public function addExtensionStyle( $url ) {
356 array_push( $this->mExtStyles
, $url );
360 * Get all styles added by extensions
364 function getExtStyle() {
365 return $this->mExtStyles
;
369 * Add a JavaScript file out of skins/common, or a given relative path.
371 * @param $file String: filename in skins/common or complete on-server path
373 * @param $version String: style version of the file. Defaults to $wgStyleVersion
375 public function addScriptFile( $file, $version = null ) {
376 global $wgStylePath, $wgStyleVersion;
377 // See if $file parameter is an absolute URL or begins with a slash
378 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
381 $path = "{$wgStylePath}/common/{$file}";
383 if ( is_null( $version ) )
384 $version = $wgStyleVersion;
385 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
389 * Add a self-contained script tag with the given contents
391 * @param $script String: JavaScript text, no <script> tags
393 public function addInlineScript( $script ) {
394 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
398 * Get all registered JS and CSS tags for the header.
402 function getScript() {
403 return $this->mScripts
. $this->getHeadItems();
407 * Filter an array of modules to remove insufficiently trustworthy members, and modules
408 * which are no longer registered (eg a page is cached before an extension is disabled)
409 * @param $modules Array
410 * @param $position String if not null, only return modules with this position
411 * @param $type string
414 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
415 $resourceLoader = $this->getResourceLoader();
416 $filteredModules = array();
417 foreach( $modules as $val ){
418 $module = $resourceLoader->getModule( $val );
419 if( $module instanceof ResourceLoaderModule
420 && $module->getOrigin() <= $this->getAllowedModules( $type )
421 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
423 $filteredModules[] = $val;
426 return $filteredModules;
430 * Get the list of modules to include on this page
432 * @param $filter Bool whether to filter out insufficiently trustworthy modules
433 * @param $position String if not null, only return modules with this position
434 * @param $param string
435 * @return Array of module names
437 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
438 $modules = array_values( array_unique( $this->$param ) );
440 ?
$this->filterModules( $modules, $position )
445 * Add one or more modules recognized by the resource loader. Modules added
446 * through this function will be loaded by the resource loader when the
449 * @param $modules Mixed: module name (string) or array of module names
451 public function addModules( $modules ) {
452 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
456 * Get the list of module JS to include on this page
461 * @return array of module names
463 public function getModuleScripts( $filter = false, $position = null ) {
464 return $this->getModules( $filter, $position, 'mModuleScripts' );
468 * Add only JS of one or more modules recognized by the resource loader. Module
469 * scripts added through this function will be loaded by the resource loader when
472 * @param $modules Mixed: module name (string) or array of module names
474 public function addModuleScripts( $modules ) {
475 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
479 * Get the list of module CSS to include on this page
484 * @return Array of module names
486 public function getModuleStyles( $filter = false, $position = null ) {
487 return $this->getModules( $filter, $position, 'mModuleStyles' );
491 * Add only CSS of one or more modules recognized by the resource loader. Module
492 * styles added through this function will be loaded by the resource loader when
495 * @param $modules Mixed: module name (string) or array of module names
497 public function addModuleStyles( $modules ) {
498 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
502 * Get the list of module messages to include on this page
507 * @return Array of module names
509 public function getModuleMessages( $filter = false, $position = null ) {
510 return $this->getModules( $filter, $position, 'mModuleMessages' );
514 * Add only messages of one or more modules recognized by the resource loader.
515 * Module messages added through this function will be loaded by the resource
516 * loader when the page loads.
518 * @param $modules Mixed: module name (string) or array of module names
520 public function addModuleMessages( $modules ) {
521 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
525 * Get an array of head items
529 function getHeadItemsArray() {
530 return $this->mHeadItems
;
534 * Get all header items in a string
538 function getHeadItems() {
540 foreach ( $this->mHeadItems
as $item ) {
547 * Add or replace an header item to the output
549 * @param $name String: item name
550 * @param $value String: raw HTML
552 public function addHeadItem( $name, $value ) {
553 $this->mHeadItems
[$name] = $value;
557 * Check if the header item $name is already set
559 * @param $name String: item name
562 public function hasHeadItem( $name ) {
563 return isset( $this->mHeadItems
[$name] );
567 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
569 * @param $tag String: value of "ETag" header
571 function setETag( $tag ) {
576 * Set whether the output should only contain the body of the article,
577 * without any skin, sidebar, etc.
578 * Used e.g. when calling with "action=render".
580 * @param $only Boolean: whether to output only the body of the article
582 public function setArticleBodyOnly( $only ) {
583 $this->mArticleBodyOnly
= $only;
587 * Return whether the output will contain only the body of the article
591 public function getArticleBodyOnly() {
592 return $this->mArticleBodyOnly
;
596 * checkLastModified tells the client to use the client-cached page if
597 * possible. If sucessful, the OutputPage is disabled so that
598 * any future call to OutputPage->output() have no effect.
600 * Side effect: sets mLastModified for Last-Modified header
602 * @param $timestamp string
604 * @return Boolean: true iff cache-ok headers was sent.
606 public function checkLastModified( $timestamp ) {
607 global $wgCachePages, $wgCacheEpoch;
609 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
610 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
613 if( !$wgCachePages ) {
614 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
617 if( $this->getUser()->getOption( 'nocache' ) ) {
618 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
622 $timestamp = wfTimestamp( TS_MW
, $timestamp );
623 $modifiedTimes = array(
624 'page' => $timestamp,
625 'user' => $this->getUser()->getTouched(),
626 'epoch' => $wgCacheEpoch
628 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
630 $maxModified = max( $modifiedTimes );
631 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
633 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
634 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
640 foreach ( $modifiedTimes as $name => $value ) {
641 if ( $info !== '' ) {
644 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
647 # IE sends sizes after the date like this:
648 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
649 # this breaks strtotime().
650 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
652 wfSuppressWarnings(); // E_STRICT system time bitching
653 $clientHeaderTime = strtotime( $clientHeader );
655 if ( !$clientHeaderTime ) {
656 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
659 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
661 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
662 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
663 wfDebug( __METHOD__
. ": effective Last-Modified: " .
664 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
665 if( $clientHeaderTime < $maxModified ) {
666 wfDebug( __METHOD__
. ": STALE, $info\n", false );
671 # Give a 304 response code and disable body output
672 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
673 ini_set( 'zlib.output_compression', 0 );
674 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
675 $this->sendCacheControl();
678 // Don't output a compressed blob when using ob_gzhandler;
679 // it's technically against HTTP spec and seems to confuse
680 // Firefox when the response gets split over two packets.
681 wfClearOutputBuffers();
687 * Override the last modified timestamp
689 * @param $timestamp String: new timestamp, in a format readable by
692 public function setLastModified( $timestamp ) {
693 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
697 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
699 * @param $policy String: the literal string to output as the contents of
700 * the meta tag. Will be parsed according to the spec and output in
704 public function setRobotPolicy( $policy ) {
705 $policy = Article
::formatRobotPolicy( $policy );
707 if( isset( $policy['index'] ) ) {
708 $this->setIndexPolicy( $policy['index'] );
710 if( isset( $policy['follow'] ) ) {
711 $this->setFollowPolicy( $policy['follow'] );
716 * Set the index policy for the page, but leave the follow policy un-
719 * @param $policy string Either 'index' or 'noindex'.
722 public function setIndexPolicy( $policy ) {
723 $policy = trim( $policy );
724 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
725 $this->mIndexPolicy
= $policy;
730 * Set the follow policy for the page, but leave the index policy un-
733 * @param $policy String: either 'follow' or 'nofollow'.
736 public function setFollowPolicy( $policy ) {
737 $policy = trim( $policy );
738 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
739 $this->mFollowPolicy
= $policy;
744 * Set the new value of the "action text", this will be added to the
745 * "HTML title", separated from it with " - ".
747 * @param $text String: new value of the "action text"
749 public function setPageTitleActionText( $text ) {
750 $this->mPageTitleActionText
= $text;
754 * Get the value of the "action text"
758 public function getPageTitleActionText() {
759 if ( isset( $this->mPageTitleActionText
) ) {
760 return $this->mPageTitleActionText
;
765 * "HTML title" means the contents of <title>.
766 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
768 * @param $name string
770 public function setHTMLTitle( $name ) {
771 if ( $name instanceof Message
) {
772 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
774 $this->mHTMLtitle
= $name;
779 * Return the "HTML title", i.e. the content of the <title> tag.
783 public function getHTMLTitle() {
784 return $this->mHTMLtitle
;
788 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
792 public function setRedirectedFrom( $t ) {
793 $this->mRedirectedFrom
= $t;
797 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
798 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
799 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
800 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
802 * @param $name string|Message
804 public function setPageTitle( $name ) {
805 if ( $name instanceof Message
) {
806 $name = $name->setContext( $this->getContext() )->text();
809 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
810 # but leave "<i>foobar</i>" alone
811 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
812 $this->mPagetitle
= $nameWithTags;
814 # change "<i>foo&bar</i>" to "foo&bar"
815 $this->setHTMLTitle( $this->msg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
819 * Return the "page title", i.e. the content of the \<h1\> tag.
823 public function getPageTitle() {
824 return $this->mPagetitle
;
828 * Set the Title object to use
830 * @param $t Title object
832 public function setTitle( Title
$t ) {
833 $this->getContext()->setTitle( $t );
838 * Replace the subtile with $str
840 * @param $str String|Message: new value of the subtitle
842 public function setSubtitle( $str ) {
843 $this->clearSubtitle();
844 $this->addSubtitle( $str );
848 * Add $str to the subtitle
850 * @deprecated in 1.19; use addSubtitle() instead
851 * @param $str String|Message to add to the subtitle
853 public function appendSubtitle( $str ) {
854 $this->addSubtitle( $str );
858 * Add $str to the subtitle
860 * @param $str String|Message to add to the subtitle
862 public function addSubtitle( $str ) {
863 if ( $str instanceof Message
) {
864 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
866 $this->mSubtitle
[] = $str;
871 * Add a subtitle containing a backlink to a page
873 * @param $title Title to link to
875 public function addBacklinkSubtitle( Title
$title ) {
877 if ( $title->isRedirect() ) {
878 $query['redirect'] = 'no';
880 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
884 * Clear the subtitles
886 public function clearSubtitle() {
887 $this->mSubtitle
= array();
895 public function getSubtitle() {
896 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
900 * Set the page as printable, i.e. it'll be displayed with with all
901 * print styles included
903 public function setPrintable() {
904 $this->mPrintable
= true;
908 * Return whether the page is "printable"
912 public function isPrintable() {
913 return $this->mPrintable
;
917 * Disable output completely, i.e. calling output() will have no effect
919 public function disable() {
920 $this->mDoNothing
= true;
924 * Return whether the output will be completely disabled
928 public function isDisabled() {
929 return $this->mDoNothing
;
933 * Show an "add new section" link?
937 public function showNewSectionLink() {
938 return $this->mNewSectionLink
;
942 * Forcibly hide the new section link?
946 public function forceHideNewSectionLink() {
947 return $this->mHideNewSectionLink
;
951 * Add or remove feed links in the page header
952 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
953 * for the new version
956 * @param $show Boolean: true: add default feeds, false: remove all feeds
958 public function setSyndicated( $show = true ) {
960 $this->setFeedAppendQuery( false );
962 $this->mFeedLinks
= array();
967 * Add default feeds to the page header
968 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
969 * for the new version
972 * @param $val String: query to append to feed links or false to output
975 public function setFeedAppendQuery( $val ) {
976 global $wgAdvertisedFeedTypes;
978 $this->mFeedLinks
= array();
980 foreach ( $wgAdvertisedFeedTypes as $type ) {
981 $query = "feed=$type";
982 if ( is_string( $val ) ) {
983 $query .= '&' . $val;
985 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
990 * Add a feed link to the page header
992 * @param $format String: feed type, should be a key of $wgFeedClasses
993 * @param $href String: URL
995 public function addFeedLink( $format, $href ) {
996 global $wgAdvertisedFeedTypes;
998 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
999 $this->mFeedLinks
[$format] = $href;
1004 * Should we output feed links for this page?
1007 public function isSyndicated() {
1008 return count( $this->mFeedLinks
) > 0;
1012 * Return URLs for each supported syndication format for this page.
1013 * @return array associating format keys with URLs
1015 public function getSyndicationLinks() {
1016 return $this->mFeedLinks
;
1020 * Will currently always return null
1024 public function getFeedAppendQuery() {
1025 return $this->mFeedLinksAppendQuery
;
1029 * Set whether the displayed content is related to the source of the
1030 * corresponding article on the wiki
1031 * Setting true will cause the change "article related" toggle to true
1035 public function setArticleFlag( $v ) {
1036 $this->mIsarticle
= $v;
1038 $this->mIsArticleRelated
= $v;
1043 * Return whether the content displayed page is related to the source of
1044 * the corresponding article on the wiki
1048 public function isArticle() {
1049 return $this->mIsarticle
;
1053 * Set whether this page is related an article on the wiki
1054 * Setting false will cause the change of "article flag" toggle to false
1058 public function setArticleRelated( $v ) {
1059 $this->mIsArticleRelated
= $v;
1061 $this->mIsarticle
= false;
1066 * Return whether this page is related an article on the wiki
1070 public function isArticleRelated() {
1071 return $this->mIsArticleRelated
;
1075 * Add new language links
1077 * @param $newLinkArray Associative array mapping language code to the page
1080 public function addLanguageLinks( $newLinkArray ) {
1081 $this->mLanguageLinks +
= $newLinkArray;
1085 * Reset the language links and add new language links
1087 * @param $newLinkArray Associative array mapping language code to the page
1090 public function setLanguageLinks( $newLinkArray ) {
1091 $this->mLanguageLinks
= $newLinkArray;
1095 * Get the list of language links
1097 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1099 public function getLanguageLinks() {
1100 return $this->mLanguageLinks
;
1104 * Add an array of categories, with names in the keys
1106 * @param $categories Array mapping category name => sort key
1108 public function addCategoryLinks( $categories ) {
1111 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1115 # Add the links to a LinkBatch
1116 $arr = array( NS_CATEGORY
=> $categories );
1117 $lb = new LinkBatch
;
1118 $lb->setArray( $arr );
1120 # Fetch existence plus the hiddencat property
1121 $dbr = wfGetDB( DB_SLAVE
);
1122 $res = $dbr->select( array( 'page', 'page_props' ),
1123 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1124 $lb->constructSet( 'page', $dbr ),
1127 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1130 # Add the results to the link cache
1131 $lb->addResultToCache( LinkCache
::singleton(), $res );
1133 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1134 $categories = array_combine(
1135 array_keys( $categories ),
1136 array_fill( 0, count( $categories ), 'normal' )
1139 # Mark hidden categories
1140 foreach ( $res as $row ) {
1141 if ( isset( $row->pp_value
) ) {
1142 $categories[$row->page_title
] = 'hidden';
1146 # Add the remaining categories to the skin
1147 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1148 foreach ( $categories as $category => $type ) {
1149 $origcategory = $category;
1150 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1151 $wgContLang->findVariantLink( $category, $title, true );
1152 if ( $category != $origcategory ) {
1153 if ( array_key_exists( $category, $categories ) ) {
1157 $text = $wgContLang->convertHtml( $title->getText() );
1158 $this->mCategories
[] = $title->getText();
1159 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1165 * Reset the category links (but not the category list) and add $categories
1167 * @param $categories Array mapping category name => sort key
1169 public function setCategoryLinks( $categories ) {
1170 $this->mCategoryLinks
= array();
1171 $this->addCategoryLinks( $categories );
1175 * Get the list of category links, in a 2-D array with the following format:
1176 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1177 * hidden categories) and $link a HTML fragment with a link to the category
1182 public function getCategoryLinks() {
1183 return $this->mCategoryLinks
;
1187 * Get the list of category names this page belongs to
1189 * @return Array of strings
1191 public function getCategories() {
1192 return $this->mCategories
;
1196 * Do not allow scripts which can be modified by wiki users to load on this page;
1197 * only allow scripts bundled with, or generated by, the software.
1199 public function disallowUserJs() {
1200 $this->reduceAllowedModules(
1201 ResourceLoaderModule
::TYPE_SCRIPTS
,
1202 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1207 * Return whether user JavaScript is allowed for this page
1208 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1209 * trustworthiness is identified and enforced automagically.
1212 public function isUserJsAllowed() {
1213 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1217 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1218 * @see ResourceLoaderModule::$origin
1219 * @param $type String ResourceLoaderModule TYPE_ constant
1220 * @return Int ResourceLoaderModule ORIGIN_ class constant
1222 public function getAllowedModules( $type ){
1223 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1224 return min( array_values( $this->mAllowedModules
) );
1226 return isset( $this->mAllowedModules
[$type] )
1227 ?
$this->mAllowedModules
[$type]
1228 : ResourceLoaderModule
::ORIGIN_ALL
;
1233 * Set the highest level of CSS/JS untrustworthiness allowed
1234 * @param $type String ResourceLoaderModule TYPE_ constant
1235 * @param $level Int ResourceLoaderModule class constant
1237 public function setAllowedModules( $type, $level ){
1238 $this->mAllowedModules
[$type] = $level;
1242 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1243 * @param $type String
1244 * @param $level Int ResourceLoaderModule class constant
1246 public function reduceAllowedModules( $type, $level ){
1247 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1251 * Prepend $text to the body HTML
1253 * @param $text String: HTML
1255 public function prependHTML( $text ) {
1256 $this->mBodytext
= $text . $this->mBodytext
;
1260 * Append $text to the body HTML
1262 * @param $text String: HTML
1264 public function addHTML( $text ) {
1265 $this->mBodytext
.= $text;
1269 * Shortcut for adding an Html::element via addHTML.
1273 * @param $element string
1274 * @param $attribs array
1275 * @param $contents string
1277 public function addElement( $element, $attribs = array(), $contents = '' ) {
1278 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1282 * Clear the body HTML
1284 public function clearHTML() {
1285 $this->mBodytext
= '';
1291 * @return String: HTML
1293 public function getHTML() {
1294 return $this->mBodytext
;
1298 * Add $text to the debug output
1300 * @param $text String: debug text
1302 public function debug( $text ) {
1303 $this->mDebugtext
.= $text;
1307 * Get/set the ParserOptions object to use for wikitext parsing
1309 * @param $options either the ParserOption to use or null to only get the
1310 * current ParserOption object
1311 * @return ParserOptions object
1313 public function parserOptions( $options = null ) {
1314 if ( !$this->mParserOptions
) {
1315 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1316 $this->mParserOptions
->setEditSection( false );
1318 return wfSetVar( $this->mParserOptions
, $options );
1322 * Set the revision ID which will be seen by the wiki text parser
1323 * for things such as embedded {{REVISIONID}} variable use.
1325 * @param $revid Mixed: an positive integer, or null
1326 * @return Mixed: previous value
1328 public function setRevisionId( $revid ) {
1329 $val = is_null( $revid ) ?
null : intval( $revid );
1330 return wfSetVar( $this->mRevisionId
, $val );
1334 * Get the displayed revision ID
1338 public function getRevisionId() {
1339 return $this->mRevisionId
;
1343 * Set the displayed file version
1345 * @param $file File|false
1346 * @return Mixed: previous value
1348 public function setFileVersion( $file ) {
1350 if ( $file instanceof File
&& $file->exists() ) {
1351 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1353 return wfSetVar( $this->mFileVersion
, $val, true );
1357 * Get the displayed file version
1359 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1361 public function getFileVersion() {
1362 return $this->mFileVersion
;
1366 * Get the templates used on this page
1368 * @return Array (namespace => dbKey => revId)
1371 public function getTemplateIds() {
1372 return $this->mTemplateIds
;
1376 * Get the files used on this page
1378 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1381 public function getFileSearchOptions() {
1382 return $this->mImageTimeKeys
;
1386 * Convert wikitext to HTML and add it to the buffer
1387 * Default assumes that the current page title will be used.
1389 * @param $text String
1390 * @param $linestart Boolean: is this the start of a line?
1391 * @param $interface Boolean: is this text in the user interface language?
1393 public function addWikiText( $text, $linestart = true, $interface = true ) {
1394 $title = $this->getTitle(); // Work arround E_STRICT
1395 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1399 * Add wikitext with a custom Title object
1401 * @param $text String: wikitext
1402 * @param $title Title object
1403 * @param $linestart Boolean: is this the start of a line?
1405 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1406 $this->addWikiTextTitle( $text, $title, $linestart );
1410 * Add wikitext with a custom Title object and tidy enabled.
1412 * @param $text String: wikitext
1413 * @param $title Title object
1414 * @param $linestart Boolean: is this the start of a line?
1416 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1417 $this->addWikiTextTitle( $text, $title, $linestart, true );
1421 * Add wikitext with tidy enabled
1423 * @param $text String: wikitext
1424 * @param $linestart Boolean: is this the start of a line?
1426 public function addWikiTextTidy( $text, $linestart = true ) {
1427 $title = $this->getTitle();
1428 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1432 * Add wikitext with a custom Title object
1434 * @param $text String: wikitext
1435 * @param $title Title object
1436 * @param $linestart Boolean: is this the start of a line?
1437 * @param $tidy Boolean: whether to use tidy
1438 * @param $interface Boolean: whether it is an interface message
1439 * (for example disables conversion)
1441 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1444 wfProfileIn( __METHOD__
);
1446 wfIncrStats( 'pcache_not_possible' );
1448 $popts = $this->parserOptions();
1449 $oldTidy = $popts->setTidy( $tidy );
1450 $popts->setInterfaceMessage( (bool) $interface );
1452 $parserOutput = $wgParser->parse(
1453 $text, $title, $popts,
1454 $linestart, true, $this->mRevisionId
1457 $popts->setTidy( $oldTidy );
1459 $this->addParserOutput( $parserOutput );
1461 wfProfileOut( __METHOD__
);
1465 * Add a ParserOutput object, but without Html
1467 * @param $parserOutput ParserOutput object
1469 public function addParserOutputNoText( &$parserOutput ) {
1470 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1471 $this->addCategoryLinks( $parserOutput->getCategories() );
1472 $this->mNewSectionLink
= $parserOutput->getNewSection();
1473 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1475 $this->mParseWarnings
= $parserOutput->getWarnings();
1476 if ( !$parserOutput->isCacheable() ) {
1477 $this->enableClientCache( false );
1479 $this->mNoGallery
= $parserOutput->getNoGallery();
1480 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1481 $this->addModules( $parserOutput->getModules() );
1482 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1483 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1484 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1486 // Template versioning...
1487 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1488 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1489 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1491 $this->mTemplateIds
[$ns] = $dbks;
1494 // File versioning...
1495 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1496 $this->mImageTimeKeys
[$dbk] = $data;
1499 // Hooks registered in the object
1500 global $wgParserOutputHooks;
1501 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1502 list( $hookName, $data ) = $hookInfo;
1503 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1504 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1508 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1512 * Add a ParserOutput object
1514 * @param $parserOutput ParserOutput
1516 function addParserOutput( &$parserOutput ) {
1517 $this->addParserOutputNoText( $parserOutput );
1518 $text = $parserOutput->getText();
1519 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1520 $this->addHTML( $text );
1525 * Add the output of a QuickTemplate to the output buffer
1527 * @param $template QuickTemplate
1529 public function addTemplate( &$template ) {
1531 $template->execute();
1532 $this->addHTML( ob_get_contents() );
1537 * Parse wikitext and return the HTML.
1539 * @param $text String
1540 * @param $linestart Boolean: is this the start of a line?
1541 * @param $interface Boolean: use interface language ($wgLang instead of
1542 * $wgContLang) while parsing language sensitive magic
1543 * words like GRAMMAR and PLURAL. This also disables
1544 * LanguageConverter.
1545 * @param $language Language object: target language object, will override
1547 * @return String: HTML
1549 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1552 if( is_null( $this->getTitle() ) ) {
1553 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1556 $popts = $this->parserOptions();
1558 $popts->setInterfaceMessage( true );
1560 if ( $language !== null ) {
1561 $oldLang = $popts->setTargetLanguage( $language );
1564 $parserOutput = $wgParser->parse(
1565 $text, $this->getTitle(), $popts,
1566 $linestart, true, $this->mRevisionId
1570 $popts->setInterfaceMessage( false );
1572 if ( $language !== null ) {
1573 $popts->setTargetLanguage( $oldLang );
1576 return $parserOutput->getText();
1580 * Parse wikitext, strip paragraphs, and return the HTML.
1582 * @param $text String
1583 * @param $linestart Boolean: is this the start of a line?
1584 * @param $interface Boolean: use interface language ($wgLang instead of
1585 * $wgContLang) while parsing language sensitive magic
1586 * words like GRAMMAR and PLURAL
1587 * @return String: HTML
1589 public function parseInline( $text, $linestart = true, $interface = false ) {
1590 $parsed = $this->parse( $text, $linestart, $interface );
1593 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1601 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1603 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1605 public function setSquidMaxage( $maxage ) {
1606 $this->mSquidMaxage
= $maxage;
1610 * Use enableClientCache(false) to force it to send nocache headers
1612 * @param $state bool
1616 public function enableClientCache( $state ) {
1617 return wfSetVar( $this->mEnableClientCache
, $state );
1621 * Get the list of cookies that will influence on the cache
1625 function getCacheVaryCookies() {
1626 global $wgCookiePrefix, $wgCacheVaryCookies;
1628 if ( $cookies === null ) {
1629 $cookies = array_merge(
1631 "{$wgCookiePrefix}Token",
1632 "{$wgCookiePrefix}LoggedOut",
1637 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1643 * Return whether this page is not cacheable because "useskin" or "uselang"
1644 * URL parameters were passed.
1648 function uncacheableBecauseRequestVars() {
1649 $request = $this->getRequest();
1650 return $request->getText( 'useskin', false ) === false
1651 && $request->getText( 'uselang', false ) === false;
1655 * Check if the request has a cache-varying cookie header
1656 * If it does, it's very important that we don't allow public caching
1660 function haveCacheVaryCookies() {
1661 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1662 if ( $cookieHeader === false ) {
1665 $cvCookies = $this->getCacheVaryCookies();
1666 foreach ( $cvCookies as $cookieName ) {
1667 # Check for a simple string match, like the way squid does it
1668 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1669 wfDebug( __METHOD__
. ": found $cookieName\n" );
1673 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1678 * Add an HTTP header that will influence on the cache
1680 * @param $header String: header name
1681 * @param $option Array|null
1682 * @todo FIXME: Document the $option parameter; it appears to be for
1683 * X-Vary-Options but what format is acceptable?
1685 public function addVaryHeader( $header, $option = null ) {
1686 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1687 $this->mVaryHeader
[$header] = (array)$option;
1688 } elseif( is_array( $option ) ) {
1689 if( is_array( $this->mVaryHeader
[$header] ) ) {
1690 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1692 $this->mVaryHeader
[$header] = $option;
1695 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1699 * Get a complete X-Vary-Options header
1703 public function getXVO() {
1704 $cvCookies = $this->getCacheVaryCookies();
1706 $cookiesOption = array();
1707 foreach ( $cvCookies as $cookieName ) {
1708 $cookiesOption[] = 'string-contains=' . $cookieName;
1710 $this->addVaryHeader( 'Cookie', $cookiesOption );
1713 foreach( $this->mVaryHeader
as $header => $option ) {
1714 $newheader = $header;
1715 if( is_array( $option ) ) {
1716 $newheader .= ';' . implode( ';', $option );
1718 $headers[] = $newheader;
1720 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1726 * bug 21672: Add Accept-Language to Vary and XVO headers
1727 * if there's no 'variant' parameter existed in GET.
1730 * /w/index.php?title=Main_page should always be served; but
1731 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1733 function addAcceptLanguage() {
1734 $lang = $this->getTitle()->getPageLanguage();
1735 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1736 $variants = $lang->getVariants();
1737 $aloption = array();
1738 foreach ( $variants as $variant ) {
1739 if( $variant === $lang->getCode() ) {
1742 $aloption[] = 'string-contains=' . $variant;
1744 // IE and some other browsers use another form of language code
1745 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1746 // We should handle these too.
1747 $ievariant = explode( '-', $variant );
1748 if ( count( $ievariant ) == 2 ) {
1749 $ievariant[1] = strtoupper( $ievariant[1] );
1750 $ievariant = implode( '-', $ievariant );
1751 $aloption[] = 'string-contains=' . $ievariant;
1755 $this->addVaryHeader( 'Accept-Language', $aloption );
1760 * Set a flag which will cause an X-Frame-Options header appropriate for
1761 * edit pages to be sent. The header value is controlled by
1762 * $wgEditPageFrameOptions.
1764 * This is the default for special pages. If you display a CSRF-protected
1765 * form on an ordinary view page, then you need to call this function.
1767 * @param $enable bool
1769 public function preventClickjacking( $enable = true ) {
1770 $this->mPreventClickjacking
= $enable;
1774 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1775 * This can be called from pages which do not contain any CSRF-protected
1778 public function allowClickjacking() {
1779 $this->mPreventClickjacking
= false;
1783 * Get the X-Frame-Options header value (without the name part), or false
1784 * if there isn't one. This is used by Skin to determine whether to enable
1785 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1789 public function getFrameOptions() {
1790 global $wgBreakFrames, $wgEditPageFrameOptions;
1791 if ( $wgBreakFrames ) {
1793 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1794 return $wgEditPageFrameOptions;
1800 * Send cache control HTTP headers
1802 public function sendCacheControl() {
1803 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1805 $response = $this->getRequest()->response();
1806 if ( $wgUseETag && $this->mETag
) {
1807 $response->header( "ETag: $this->mETag" );
1810 $this->addAcceptLanguage();
1812 # don't serve compressed data to clients who can't handle it
1813 # maintain different caches for logged-in users and non-logged in ones
1814 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1817 # Add an X-Vary-Options header for Squid with Wikimedia patches
1818 $response->header( $this->getXVO() );
1821 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1823 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1824 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1828 # We'll purge the proxy cache explicitly, but require end user agents
1829 # to revalidate against the proxy on each visit.
1830 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1831 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1832 # start with a shorter timeout for initial testing
1833 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1834 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1835 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1837 # We'll purge the proxy cache for anons explicitly, but require end user agents
1838 # to revalidate against the proxy on each visit.
1839 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1840 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1841 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1842 # start with a shorter timeout for initial testing
1843 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1844 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1847 # We do want clients to cache if they can, but they *must* check for updates
1848 # on revisiting the page.
1849 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1850 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1851 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1853 if($this->mLastModified
) {
1854 $response->header( "Last-Modified: {$this->mLastModified}" );
1857 wfDebug( __METHOD__
. ": no caching **\n", false );
1859 # In general, the absence of a last modified header should be enough to prevent
1860 # the client from using its cache. We send a few other things just to make sure.
1861 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1862 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1863 $response->header( 'Pragma: no-cache' );
1868 * Get the message associed with the HTTP response code $code
1870 * @param $code Integer: status code
1871 * @return String or null: message or null if $code is not in the list of
1874 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1876 public static function getStatusMessage( $code ) {
1877 wfDeprecated( __METHOD__
);
1878 return HttpStatus
::getMessage( $code );
1882 * Finally, all the text has been munged and accumulated into
1883 * the object, let's actually output it:
1885 public function output() {
1886 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1888 if( $this->mDoNothing
) {
1892 wfProfileIn( __METHOD__
);
1894 $response = $this->getRequest()->response();
1896 if ( $this->mRedirect
!= '' ) {
1897 # Standards require redirect URLs to be absolute
1898 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1899 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1900 if( !$wgDebugRedirects ) {
1901 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1902 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1904 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1906 if ( $wgVaryOnXFP ) {
1907 $this->addVaryHeader( 'X-Forwarded-Proto' );
1909 $this->sendCacheControl();
1911 $response->header( "Content-Type: text/html; charset=utf-8" );
1912 if( $wgDebugRedirects ) {
1913 $url = htmlspecialchars( $this->mRedirect
);
1914 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1915 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1916 print "</body>\n</html>\n";
1918 $response->header( 'Location: ' . $this->mRedirect
);
1920 wfProfileOut( __METHOD__
);
1922 } elseif ( $this->mStatusCode
) {
1923 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1925 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1929 # Buffer output; final headers may depend on later processing
1932 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1933 $response->header( 'Content-language: ' . $wgLanguageCode );
1935 // Prevent framing, if requested
1936 $frameOptions = $this->getFrameOptions();
1937 if ( $frameOptions ) {
1938 $response->header( "X-Frame-Options: $frameOptions" );
1941 if ( $this->mArticleBodyOnly
) {
1942 $this->out( $this->mBodytext
);
1944 $this->addDefaultModules();
1946 $sk = $this->getSkin();
1948 // Hook that allows last minute changes to the output page, e.g.
1949 // adding of CSS or Javascript by extensions.
1950 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1952 wfProfileIn( 'Output-skin' );
1954 wfProfileOut( 'Output-skin' );
1957 $this->sendCacheControl();
1959 wfProfileOut( __METHOD__
);
1963 * Actually output something with print().
1965 * @param $ins String: the string to output
1967 public function out( $ins ) {
1972 * Produce a "user is blocked" page.
1973 * @deprecated since 1.18
1975 function blockedPage() {
1976 throw new UserBlockedError( $this->getUser()->mBlock
);
1980 * Prepare this object to display an error page; disable caching and
1981 * indexing, clear the current text and redirect, set the page's title
1982 * and optionally an custom HTML title (content of the <title> tag).
1984 * @param $pageTitle String|Message will be passed directly to setPageTitle()
1985 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
1986 * optional, if not passed the <title> attribute will be
1987 * based on $pageTitle
1989 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
1990 if ( $this->getTitle() ) {
1991 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1994 $this->setPageTitle( $pageTitle );
1995 if ( $htmlTitle !== false ) {
1996 $this->setHTMLTitle( $htmlTitle );
1998 $this->setRobotPolicy( 'noindex,nofollow' );
1999 $this->setArticleRelated( false );
2000 $this->enableClientCache( false );
2001 $this->mRedirect
= '';
2002 $this->clearSubtitle();
2007 * Output a standard error page
2009 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2010 * showErrorPage( 'titlemsg', $messageObject );
2012 * @param $title String: message key for page title
2013 * @param $msg Mixed: message key (string) for page text, or a Message object
2014 * @param $params Array: message parameters; ignored if $msg is a Message object
2016 public function showErrorPage( $title, $msg, $params = array() ) {
2017 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2019 if ( $msg instanceof Message
){
2020 $this->addHTML( $msg->parse() );
2022 $this->addWikiMsgArray( $msg, $params );
2025 $this->returnToMain();
2029 * Output a standard permission error page
2031 * @param $errors Array: error message keys
2032 * @param $action String: action that was denied or null if unknown
2034 public function showPermissionsErrorPage( $errors, $action = null ) {
2035 global $wgGroupPermissions;
2037 // For some action (read, edit, create and upload), display a "login to do this action"
2038 // error if all of the following conditions are met:
2039 // 1. the user is not logged in
2040 // 2. the only error is insufficient permissions (i.e. no block or something else)
2041 // 3. the error can be avoided simply by logging in
2042 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2043 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2044 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2045 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2046 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2048 $displayReturnto = null;
2050 # Due to bug 32276, if a user does not have read permissions,
2051 # $this->getTitle() will just give Special:Badtitle, which is
2052 # not especially useful as a returnto parameter. Use the title
2053 # from the request instead, if there was one.
2054 $request = $this->getRequest();
2055 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2056 if ( $action == 'edit' ) {
2057 $msg = 'whitelistedittext';
2058 $displayReturnto = $returnto;
2059 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2060 $msg = 'nocreatetext';
2061 } elseif ( $action == 'upload' ) {
2062 $msg = 'uploadnologintext';
2064 $msg = 'loginreqpagetext';
2065 $displayReturnto = Title
::newMainPage();
2071 $query['returnto'] = $returnto->getPrefixedText();
2073 if ( !$request->wasPosted() ) {
2074 $returntoquery = $request->getValues();
2075 unset( $returntoquery['title'] );
2076 unset( $returntoquery['returnto'] );
2077 unset( $returntoquery['returntoquery'] );
2078 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2081 $loginLink = Linker
::linkKnown(
2082 SpecialPage
::getTitleFor( 'Userlogin' ),
2083 $this->msg( 'loginreqlink' )->escaped(),
2088 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2089 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2091 # Don't return to a page the user can't read otherwise
2092 # we'll end up in a pointless loop
2093 if ( $displayReturnto && $displayReturnto->userCanRead() ) {
2094 $this->returnToMain( null, $displayReturnto );
2097 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2098 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2103 * Display an error page indicating that a given version of MediaWiki is
2104 * required to use it
2106 * @param $version Mixed: the version of MediaWiki needed to use the page
2108 public function versionRequired( $version ) {
2109 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2111 $this->addWikiMsg( 'versionrequiredtext', $version );
2112 $this->returnToMain();
2116 * Display an error page noting that a given permission bit is required.
2117 * @deprecated since 1.18, just throw the exception directly
2118 * @param $permission String: key required
2120 public function permissionRequired( $permission ) {
2121 throw new PermissionsError( $permission );
2125 * Produce the stock "please login to use the wiki" page
2127 * @deprecated in 1.19; throw the exception directly
2129 public function loginToUse() {
2130 throw new PermissionsError( 'read' );
2134 * Format a list of error messages
2136 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2137 * @param $action String: action that was denied or null if unknown
2138 * @return String: the wikitext error-messages, formatted into a list.
2140 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2141 if ( $action == null ) {
2142 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2144 $action_desc = $this->msg( "action-$action" )->plain();
2146 'permissionserrorstext-withaction',
2149 )->plain() . "\n\n";
2152 if ( count( $errors ) > 1 ) {
2153 $text .= '<ul class="permissions-errors">' . "\n";
2155 foreach( $errors as $error ) {
2157 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2162 $text .= "<div class=\"permissions-errors\">\n" .
2163 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2171 * Display a page stating that the Wiki is in read-only mode,
2172 * and optionally show the source of the page that the user
2173 * was trying to edit. Should only be called (for this
2174 * purpose) after wfReadOnly() has returned true.
2176 * For historical reasons, this function is _also_ used to
2177 * show the error message when a user tries to edit a page
2178 * they are not allowed to edit. (Unless it's because they're
2179 * blocked, then we show blockedPage() instead.) In this
2180 * case, the second parameter should be set to true and a list
2181 * of reasons supplied as the third parameter.
2183 * @todo Needs to be split into multiple functions.
2185 * @param $source String: source code to show (or null).
2186 * @param $protected Boolean: is this a permissions error?
2187 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2188 * @param $action String: action that was denied or null if unknown
2190 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2191 $this->setRobotPolicy( 'noindex,nofollow' );
2192 $this->setArticleRelated( false );
2194 // If no reason is given, just supply a default "I can't let you do
2195 // that, Dave" message. Should only occur if called by legacy code.
2196 if ( $protected && empty( $reasons ) ) {
2197 $reasons[] = array( 'badaccess-group0' );
2200 if ( !empty( $reasons ) ) {
2201 // Permissions error
2203 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2204 $this->addBacklinkSubtitle( $this->getTitle() );
2206 $this->setPageTitle( $this->msg( 'badaccess' ) );
2208 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2210 // Wiki is read only
2211 throw new ReadOnlyError
;
2214 // Show source, if supplied
2215 if( is_string( $source ) ) {
2216 $this->addWikiMsg( 'viewsourcetext' );
2218 $pageLang = $this->getTitle()->getPageLanguage();
2220 'id' => 'wpTextbox1',
2221 'name' => 'wpTextbox1',
2222 'cols' => $this->getUser()->getOption( 'cols' ),
2223 'rows' => $this->getUser()->getOption( 'rows' ),
2224 'readonly' => 'readonly',
2225 'lang' => $pageLang->getCode(),
2226 'dir' => $pageLang->getDir(),
2228 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2230 // Show templates used by this article
2231 $page = WikiPage
::factory( $this->getTitle() );
2232 $templates = Linker
::formatTemplates( $page->getUsedTemplates() );
2233 $this->addHTML( "<div class='templatesUsed'>
2239 # If the title doesn't exist, it's fairly pointless to print a return
2240 # link to it. After all, you just tried editing it and couldn't, so
2241 # what's there to do there?
2242 if( $this->getTitle()->exists() ) {
2243 $this->returnToMain( null, $this->getTitle() );
2248 * Turn off regular page output and return an error reponse
2249 * for when rate limiting has triggered.
2251 public function rateLimited() {
2252 throw new ThrottledError
;
2256 * Show a warning about slave lag
2258 * If the lag is higher than $wgSlaveLagCritical seconds,
2259 * then the warning is a bit more obvious. If the lag is
2260 * lower than $wgSlaveLagWarning, then no warning is shown.
2262 * @param $lag Integer: slave lag
2264 public function showLagWarning( $lag ) {
2265 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2266 if( $lag >= $wgSlaveLagWarning ) {
2267 $message = $lag < $wgSlaveLagCritical
2270 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2271 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2275 public function showFatalError( $message ) {
2276 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2278 $this->addHTML( $message );
2281 public function showUnexpectedValueError( $name, $val ) {
2282 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2285 public function showFileCopyError( $old, $new ) {
2286 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2289 public function showFileRenameError( $old, $new ) {
2290 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2293 public function showFileDeleteError( $name ) {
2294 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2297 public function showFileNotFoundError( $name ) {
2298 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2302 * Add a "return to" link pointing to a specified title
2304 * @param $title Title to link
2305 * @param $query String query string
2306 * @param $text String text of the link (input is not escaped)
2308 public function addReturnTo( $title, $query = array(), $text = null ) {
2309 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2310 $link = $this->msg( 'returnto' )->rawParams(
2311 Linker
::link( $title, $text, array(), $query ) )->escaped();
2312 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2316 * Add a "return to" link pointing to a specified title,
2317 * or the title indicated in the request, or else the main page
2319 * @param $unused No longer used
2320 * @param $returnto Title or String to return to
2321 * @param $returntoquery String: query string for the return to link
2323 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2324 if ( $returnto == null ) {
2325 $returnto = $this->getRequest()->getText( 'returnto' );
2328 if ( $returntoquery == null ) {
2329 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2332 if ( $returnto === '' ) {
2333 $returnto = Title
::newMainPage();
2336 if ( is_object( $returnto ) ) {
2337 $titleObj = $returnto;
2339 $titleObj = Title
::newFromText( $returnto );
2341 if ( !is_object( $titleObj ) ) {
2342 $titleObj = Title
::newMainPage();
2345 $this->addReturnTo( $titleObj, $returntoquery );
2349 * @param $sk Skin The given Skin
2350 * @param $includeStyle Boolean: unused
2351 * @return String: The doctype, opening <html>, and head element.
2353 public function headElement( Skin
$sk, $includeStyle = true ) {
2355 $userdir = $this->getLanguage()->getDir();
2356 $sitedir = $wgContLang->getDir();
2358 if ( $sk->commonPrintStylesheet() ) {
2359 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2362 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2364 if ( $this->getHTMLTitle() == '' ) {
2365 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2368 $openHead = Html
::openElement( 'head' );
2370 # Don't bother with the newline if $head == ''
2371 $ret .= "$openHead\n";
2374 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2376 $ret .= implode( "\n", array(
2377 $this->getHeadLinks( null, true ),
2378 $this->buildCssLinks(),
2379 $this->getHeadScripts(),
2380 $this->getHeadItems()
2383 $closeHead = Html
::closeElement( 'head' );
2385 $ret .= "$closeHead\n";
2388 $bodyAttrs = array();
2390 # Classes for LTR/RTL directionality support
2391 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2393 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2394 # A <body> class is probably not the best way to do this . . .
2395 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2397 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2398 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2400 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2401 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2403 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2409 * Add the default ResourceLoader modules to this object
2411 private function addDefaultModules() {
2412 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2414 // Add base resources
2415 $this->addModules( array(
2418 'mediawiki.page.startup',
2419 'mediawiki.page.ready',
2421 if ( $wgIncludeLegacyJavaScript ){
2422 $this->addModules( 'mediawiki.legacy.wikibits' );
2425 // Add various resources if required
2427 $this->addModules( 'mediawiki.legacy.ajax' );
2429 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2431 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2432 $this->addModules( 'mediawiki.action.watch.ajax' );
2435 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2436 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2440 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2441 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2444 # Crazy edit-on-double-click stuff
2445 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2446 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2451 * Get a ResourceLoader object associated with this OutputPage
2453 * @return ResourceLoader
2455 public function getResourceLoader() {
2456 if ( is_null( $this->mResourceLoader
) ) {
2457 $this->mResourceLoader
= new ResourceLoader();
2459 return $this->mResourceLoader
;
2464 * @param $modules Array/string with the module name(s)
2465 * @param $only String ResourceLoaderModule TYPE_ class constant
2466 * @param $useESI boolean
2467 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2468 * @return string html <script> and <style> tags
2470 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2471 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2473 if ( !count( $modules ) ) {
2477 if ( count( $modules ) > 1 ) {
2478 // Remove duplicate module requests
2479 $modules = array_unique( (array) $modules );
2480 // Sort module names so requests are more uniform
2483 if ( ResourceLoader
::inDebugMode() ) {
2484 // Recursively call us for every item
2486 foreach ( $modules as $name ) {
2487 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2493 // Create keyed-by-group list of module objects from modules list
2495 $resourceLoader = $this->getResourceLoader();
2496 foreach ( (array) $modules as $name ) {
2497 $module = $resourceLoader->getModule( $name );
2498 # Check that we're allowed to include this module on this page
2500 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2501 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2502 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2503 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2509 $group = $module->getGroup();
2510 if ( !isset( $groups[$group] ) ) {
2511 $groups[$group] = array();
2513 $groups[$group][$name] = $module;
2517 foreach ( $groups as $group => $modules ) {
2518 // Special handling for user-specific groups
2520 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2521 $user = $this->getUser()->getName();
2524 // Create a fake request based on the one we are about to make so modules return
2525 // correct timestamp and emptiness data
2526 $query = ResourceLoader
::makeLoaderQuery(
2527 array(), // modules; not determined yet
2528 $this->getLanguage()->getCode(),
2529 $this->getSkin()->getSkinName(),
2531 null, // version; not determined yet
2532 ResourceLoader
::inDebugMode(),
2533 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2534 $this->isPrintable(),
2535 $this->getRequest()->getBool( 'handheld' ),
2538 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2539 // Drop modules that know they're empty
2540 foreach ( $modules as $key => $module ) {
2541 if ( $module->isKnownEmpty( $context ) ) {
2542 unset( $modules[$key] );
2545 // If there are no modules left, skip this group
2546 if ( $modules === array() ) {
2550 // Support inlining of private modules if configured as such
2551 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2552 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2553 $links .= Html
::inlineStyle(
2554 $resourceLoader->makeModuleResponse( $context, $modules )
2557 $links .= Html
::inlineScript(
2558 ResourceLoader
::makeLoaderConditionalScript(
2559 $resourceLoader->makeModuleResponse( $context, $modules )
2566 // Special handling for the user group; because users might change their stuff
2567 // on-wiki like user pages, or user preferences; we need to find the highest
2568 // timestamp of these user-changable modules so we can ensure cache misses on change
2569 // This should NOT be done for the site group (bug 27564) because anons get that too
2570 // and we shouldn't be putting timestamps in Squid-cached HTML
2572 if ( $group === 'user' ) {
2573 // Get the maximum timestamp
2575 foreach ( $modules as $module ) {
2576 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2578 // Add a version parameter so cache will break when things change
2579 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2582 $url = ResourceLoader
::makeLoaderURL(
2583 array_keys( $modules ),
2584 $this->getLanguage()->getCode(),
2585 $this->getSkin()->getSkinName(),
2588 ResourceLoader
::inDebugMode(),
2589 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2590 $this->isPrintable(),
2591 $this->getRequest()->getBool( 'handheld' ),
2594 if ( $useESI && $wgResourceLoaderUseESI ) {
2595 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2596 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2597 $link = Html
::inlineStyle( $esi );
2599 $link = Html
::inlineScript( $esi );
2602 // Automatically select style/script elements
2603 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2604 $link = Html
::linkedStyle( $url );
2606 $link = Html
::linkedScript( $url );
2610 if( $group == 'noscript' ){
2611 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2613 $links .= $link . "\n";
2620 * JS stuff to put in the <head>. This is the startup module, config
2621 * vars and modules marked with position 'top'
2623 * @return String: HTML fragment
2625 function getHeadScripts() {
2626 // Startup - this will immediately load jquery and mediawiki modules
2627 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2629 // Load config before anything else
2630 $scripts .= Html
::inlineScript(
2631 ResourceLoader
::makeLoaderConditionalScript(
2632 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2636 // Script and Messages "only" requests marked for top inclusion
2637 // Messages should go first
2638 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2639 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2641 // Modules requests - let the client calculate dependencies and batch requests as it likes
2642 // Only load modules that have marked themselves for loading at the top
2643 $modules = $this->getModules( true, 'top' );
2645 $scripts .= Html
::inlineScript(
2646 ResourceLoader
::makeLoaderConditionalScript(
2647 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2656 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2657 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2661 function getBottomScripts() {
2662 global $wgUseSiteJs, $wgAllowUserJs;
2664 // Script and Messages "only" requests marked for bottom inclusion
2665 // Messages should go first
2666 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2667 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2669 // Modules requests - let the client calculate dependencies and batch requests as it likes
2670 // Only load modules that have marked themselves for loading at the bottom
2671 $modules = $this->getModules( true, 'bottom' );
2673 $scripts .= Html
::inlineScript(
2674 ResourceLoader
::makeLoaderConditionalScript(
2675 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2681 $scripts .= "\n" . $this->mScripts
;
2683 $userScripts = array( 'user.options', 'user.tokens' );
2685 // Add site JS if enabled
2686 if ( $wgUseSiteJs ) {
2687 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2688 if( $this->getUser()->isLoggedIn() ){
2689 $userScripts[] = 'user.groups';
2693 // Add user JS if enabled
2694 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2695 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2696 # XXX: additional security check/prompt?
2697 // We're on a preview of a JS subpage
2698 // Exclude this page from the user module in case it's in there (bug 26283)
2699 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2700 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2702 // Load the previewed JS
2703 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2705 // Include the user module normally
2706 // We can't do $userScripts[] = 'user'; because the user module would end up
2707 // being wrapped in a closure, so load it raw like 'site'
2708 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2711 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2717 * Add one or more variables to be set in mw.config in JavaScript.
2719 * @param $key {String|Array} Key or array of key/value pars.
2720 * @param $value {Mixed} Value of the configuration variable.
2722 public function addJsConfigVars( $keys, $value ) {
2723 if ( is_array( $keys ) ) {
2724 foreach ( $keys as $key => $value ) {
2725 $this->mJsConfigVars
[$key] = $value;
2730 $this->mJsConfigVars
[$keys] = $value;
2735 * Get an array containing the variables to be set in mw.config in JavaScript.
2737 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2738 * - in other words, page-independent/site-wide variables (without state).
2739 * You will only be adding bloat to the html page and causing page caches to
2740 * have to be purged on configuration changes.
2743 protected function getJSVars() {
2744 global $wgUseAjax, $wgEnableMWSuggest;
2746 $title = $this->getTitle();
2747 $ns = $title->getNamespace();
2748 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2749 if ( $ns == NS_SPECIAL
) {
2750 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2752 $canonicalName = false; # bug 21115
2755 $lang = $title->getPageLanguage();
2757 // Pre-process information
2758 $separatorTransTable = $lang->separatorTransformTable();
2759 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2760 $compactSeparatorTransTable = array(
2761 implode( "\t", array_keys( $separatorTransTable ) ),
2762 implode( "\t", $separatorTransTable ),
2764 $digitTransTable = $lang->digitTransformTable();
2765 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2766 $compactDigitTransTable = array(
2767 implode( "\t", array_keys( $digitTransTable ) ),
2768 implode( "\t", $digitTransTable ),
2772 'wgCanonicalNamespace' => $nsname,
2773 'wgCanonicalSpecialPageName' => $canonicalName,
2774 'wgNamespaceNumber' => $title->getNamespace(),
2775 'wgPageName' => $title->getPrefixedDBKey(),
2776 'wgTitle' => $title->getText(),
2777 'wgCurRevisionId' => $title->getLatestRevID(),
2778 'wgArticleId' => $title->getArticleId(),
2779 'wgIsArticle' => $this->isArticle(),
2780 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2781 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2782 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2783 'wgCategories' => $this->getCategories(),
2784 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2785 'wgPageContentLanguage' => $lang->getCode(),
2786 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2787 'wgDigitTransformTable' => $compactDigitTransTable,
2789 if ( $lang->hasVariants() ) {
2790 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2792 foreach ( $title->getRestrictionTypes() as $type ) {
2793 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2795 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2796 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2798 if ( $title->isMainPage() ) {
2799 $vars['wgIsMainPage'] = true;
2801 if ( $this->mRedirectedFrom
) {
2802 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2805 // Allow extensions to add their custom variables to the mw.config map.
2806 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2807 // page-dependant but site-wide (without state).
2808 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2809 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2811 // Merge in variables from addJsConfigVars last
2812 return array_merge( $vars, $this->mJsConfigVars
);
2816 * To make it harder for someone to slip a user a fake
2817 * user-JavaScript or user-CSS preview, a random token
2818 * is associated with the login session. If it's not
2819 * passed back with the preview request, we won't render
2824 public function userCanPreview() {
2825 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2826 ||
!$this->getRequest()->wasPosted()
2827 ||
!$this->getUser()->matchEditToken(
2828 $this->getRequest()->getVal( 'wpEditToken' ) )
2832 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2836 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2840 * @param $unused Unused
2841 * @param $addContentType bool
2843 * @return string HTML tag links to be put in the header.
2845 public function getHeadLinks( $unused = null, $addContentType = false ) {
2846 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2847 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2848 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2849 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2850 $wgRightsPage, $wgRightsUrl;
2854 if ( $addContentType ) {
2856 # More succinct than <meta http-equiv=Content-Type>, has the
2858 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2860 $tags[] = Html
::element( 'meta', array(
2861 'http-equiv' => 'Content-Type',
2862 'content' => "$wgMimeType; charset=UTF-8"
2864 $tags[] = Html
::element( 'meta', array( // bug 15835
2865 'http-equiv' => 'Content-Style-Type',
2866 'content' => 'text/css'
2871 $tags[] = Html
::element( 'meta', array(
2872 'name' => 'generator',
2873 'content' => "MediaWiki $wgVersion",
2876 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2877 if( $p !== 'index,follow' ) {
2878 // http://www.robotstxt.org/wc/meta-user.html
2879 // Only show if it's different from the default robots policy
2880 $tags[] = Html
::element( 'meta', array(
2886 if ( count( $this->mKeywords
) > 0 ) {
2888 "/<.*?" . ">/" => '',
2891 $tags[] = Html
::element( 'meta', array(
2892 'name' => 'keywords',
2893 'content' => preg_replace(
2894 array_keys( $strip ),
2895 array_values( $strip ),
2896 implode( ',', $this->mKeywords
)
2901 foreach ( $this->mMetatags
as $tag ) {
2902 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2904 $tag[0] = substr( $tag[0], 5 );
2908 $tags[] = Html
::element( 'meta',
2911 'content' => $tag[1]
2916 foreach ( $this->mLinktags
as $tag ) {
2917 $tags[] = Html
::element( 'link', $tag );
2920 # Universal edit button
2921 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
2922 $user = $this->getUser();
2923 if ( $this->getTitle()->quickUserCan( 'edit', $user )
2924 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
2925 // Original UniversalEditButton
2926 $msg = $this->msg( 'edit' )->text();
2927 $tags[] = Html
::element( 'link', array(
2928 'rel' => 'alternate',
2929 'type' => 'application/x-wiki',
2931 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2933 // Alternate edit link
2934 $tags[] = Html
::element( 'link', array(
2937 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2942 # Generally the order of the favicon and apple-touch-icon links
2943 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2944 # uses whichever one appears later in the HTML source. Make sure
2945 # apple-touch-icon is specified first to avoid this.
2946 if ( $wgAppleTouchIcon !== false ) {
2947 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2950 if ( $wgFavicon !== false ) {
2951 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2954 # OpenSearch description link
2955 $tags[] = Html
::element( 'link', array(
2957 'type' => 'application/opensearchdescription+xml',
2958 'href' => wfScript( 'opensearch_desc' ),
2959 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
2962 if ( $wgEnableAPI ) {
2963 # Real Simple Discovery link, provides auto-discovery information
2964 # for the MediaWiki API (and potentially additional custom API
2965 # support such as WordPress or Twitter-compatible APIs for a
2966 # blogging extension, etc)
2967 $tags[] = Html
::element( 'link', array(
2969 'type' => 'application/rsd+xml',
2970 // Output a protocol-relative URL here if $wgServer is protocol-relative
2971 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2972 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
2978 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
2979 $lang = $this->getTitle()->getPageLanguage();
2980 if ( $lang->hasVariants() ) {
2982 $urlvar = $lang->getURLVariant();
2985 $variants = $lang->getVariants();
2986 foreach ( $variants as $_v ) {
2987 $tags[] = Html
::element( 'link', array(
2988 'rel' => 'alternate',
2990 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2994 $tags[] = Html
::element( 'link', array(
2995 'rel' => 'canonical',
2996 'href' => $this->getTitle()->getCanonicalUrl()
3004 if ( $wgRightsPage ) {
3005 $copy = Title
::newFromText( $wgRightsPage );
3008 $copyright = $copy->getLocalURL();
3012 if ( !$copyright && $wgRightsUrl ) {
3013 $copyright = $wgRightsUrl;
3017 $tags[] = Html
::element( 'link', array(
3018 'rel' => 'copyright',
3019 'href' => $copyright )
3025 foreach( $this->getSyndicationLinks() as $format => $link ) {
3026 # Use the page name for the title. In principle, this could
3027 # lead to issues with having the same name for different feeds
3028 # corresponding to the same page, but we can't avoid that at
3031 $tags[] = $this->feedLink(
3034 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3035 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3039 # Recent changes feed should appear on every page (except recentchanges,
3040 # that would be redundant). Put it after the per-page feed to avoid
3041 # changing existing behavior. It's still available, probably via a
3042 # menu in your browser. Some sites might have a different feed they'd
3043 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3044 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3045 # If so, use it instead.
3046 if ( $wgOverrideSiteFeed ) {
3047 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3048 // Note, this->feedLink escapes the url.
3049 $tags[] = $this->feedLink(
3052 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3055 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3056 foreach ( $wgAdvertisedFeedTypes as $format ) {
3057 $tags[] = $this->feedLink(
3059 $this->getTitle()->getLocalURL( "feed={$format}" ),
3060 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3065 return implode( "\n", $tags );
3069 * Generate a <link rel/> for a feed.
3071 * @param $type String: feed type
3072 * @param $url String: URL to the feed
3073 * @param $text String: value of the "title" attribute
3074 * @return String: HTML fragment
3076 private function feedLink( $type, $url, $text ) {
3077 return Html
::element( 'link', array(
3078 'rel' => 'alternate',
3079 'type' => "application/$type+xml",
3086 * Add a local or specified stylesheet, with the given media options.
3087 * Meant primarily for internal use...
3089 * @param $style String: URL to the file
3090 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3091 * @param $condition String: for IE conditional comments, specifying an IE version
3092 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3094 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3096 // Even though we expect the media type to be lowercase, but here we
3097 // force it to lowercase to be safe.
3099 $options['media'] = $media;
3102 $options['condition'] = $condition;
3105 $options['dir'] = $dir;
3107 $this->styles
[$style] = $options;
3111 * Adds inline CSS styles
3112 * @param $style_css Mixed: inline CSS
3113 * @param $flip String: Set to 'flip' to flip the CSS if needed
3115 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3116 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3117 # If wanted, and the interface is right-to-left, flip the CSS
3118 $style_css = CSSJanus
::transform( $style_css, true, false );
3120 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3124 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3125 * These will be applied to various media & IE conditionals.
3129 public function buildCssLinks() {
3130 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3132 $this->getSkin()->setupSkinUserCss( $this );
3134 // Add ResourceLoader styles
3135 // Split the styles into four groups
3136 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3137 $otherTags = ''; // Tags to append after the normal <link> tags
3138 $resourceLoader = $this->getResourceLoader();
3140 $moduleStyles = $this->getModuleStyles();
3142 // Per-site custom styles
3143 if ( $wgUseSiteCss ) {
3144 $moduleStyles[] = 'site';
3145 $moduleStyles[] = 'noscript';
3146 if( $this->getUser()->isLoggedIn() ){
3147 $moduleStyles[] = 'user.groups';
3151 // Per-user custom styles
3152 if ( $wgAllowUserCss ) {
3153 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3154 // We're on a preview of a CSS subpage
3155 // Exclude this page from the user module in case it's in there (bug 26283)
3156 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3157 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3159 // Load the previewed CSS
3160 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3162 // Load the user styles normally
3163 $moduleStyles[] = 'user';
3167 // Per-user preference styles
3168 if ( $wgAllowUserCssPrefs ) {
3169 $moduleStyles[] = 'user.options';
3172 foreach ( $moduleStyles as $name ) {
3173 $module = $resourceLoader->getModule( $name );
3177 $group = $module->getGroup();
3178 // Modules in groups named "other" or anything different than "user", "site" or "private"
3179 // will be placed in the "other" group
3180 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3183 // We want site, private and user styles to override dynamically added styles from modules, but we want
3184 // dynamically added styles to override statically added styles from other modules. So the order
3185 // has to be other, dynamic, site, private, user
3186 // Add statically added styles for other modules
3187 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3188 // Add normal styles added through addStyle()/addInlineStyle() here
3189 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3190 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3191 // We use a <meta> tag with a made-up name for this because that's valid HTML
3192 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3194 // Add site, private and user styles
3195 // 'private' at present only contains user.options, so put that before 'user'
3196 // Any future private modules will likely have a similar user-specific character
3197 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3198 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3199 ResourceLoaderModule
::TYPE_STYLES
3203 // Add stuff in $otherTags (previewed user CSS if applicable)
3211 public function buildCssLinksArray() {
3214 // Add any extension CSS
3215 foreach ( $this->mExtStyles
as $url ) {
3216 $this->addStyle( $url );
3218 $this->mExtStyles
= array();
3220 foreach( $this->styles
as $file => $options ) {
3221 $link = $this->styleLink( $file, $options );
3223 $links[$file] = $link;
3230 * Generate \<link\> tags for stylesheets
3232 * @param $style String: URL to the file
3233 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3235 * @return String: HTML fragment
3237 protected function styleLink( $style, $options ) {
3238 if( isset( $options['dir'] ) ) {
3239 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3244 if( isset( $options['media'] ) ) {
3245 $media = self
::transformCssMedia( $options['media'] );
3246 if( is_null( $media ) ) {
3253 if( substr( $style, 0, 1 ) == '/' ||
3254 substr( $style, 0, 5 ) == 'http:' ||
3255 substr( $style, 0, 6 ) == 'https:' ) {
3258 global $wgStylePath, $wgStyleVersion;
3259 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3262 $link = Html
::linkedStyle( $url, $media );
3264 if( isset( $options['condition'] ) ) {
3265 $condition = htmlspecialchars( $options['condition'] );
3266 $link = "<!--[if $condition]>$link<![endif]-->";
3272 * Transform "media" attribute based on request parameters
3274 * @param $media String: current value of the "media" attribute
3275 * @return String: modified value of the "media" attribute
3277 public static function transformCssMedia( $media ) {
3278 global $wgRequest, $wgHandheldForIPhone;
3280 // Switch in on-screen display for media testing
3282 'printable' => 'print',
3283 'handheld' => 'handheld',
3285 foreach( $switches as $switch => $targetMedia ) {
3286 if( $wgRequest->getBool( $switch ) ) {
3287 if( $media == $targetMedia ) {
3289 } elseif( $media == 'screen' ) {
3295 // Expand longer media queries as iPhone doesn't grok 'handheld'
3296 if( $wgHandheldForIPhone ) {
3297 $mediaAliases = array(
3298 'screen' => 'screen and (min-device-width: 481px)',
3299 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3302 if( isset( $mediaAliases[$media] ) ) {
3303 $media = $mediaAliases[$media];
3311 * Add a wikitext-formatted message to the output.
3312 * This is equivalent to:
3314 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3316 public function addWikiMsg( /*...*/ ) {
3317 $args = func_get_args();
3318 $name = array_shift( $args );
3319 $this->addWikiMsgArray( $name, $args );
3323 * Add a wikitext-formatted message to the output.
3324 * Like addWikiMsg() except the parameters are taken as an array
3325 * instead of a variable argument list.
3327 * @param $name string
3328 * @param $args array
3330 public function addWikiMsgArray( $name, $args ) {
3331 $this->addWikiText( $this->msg( $name, $args )->plain() );
3335 * This function takes a number of message/argument specifications, wraps them in
3336 * some overall structure, and then parses the result and adds it to the output.
3338 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3339 * on. The subsequent arguments may either be strings, in which case they are the
3340 * message names, or arrays, in which case the first element is the message name,
3341 * and subsequent elements are the parameters to that message.
3343 * The special named parameter 'options' in a message specification array is passed
3344 * through to the $options parameter of wfMsgExt().
3346 * Don't use this for messages that are not in users interface language.
3350 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3354 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3356 * The newline after opening div is needed in some wikitext. See bug 19226.
3358 * @param $wrap string
3360 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3361 $msgSpecs = func_get_args();
3362 array_shift( $msgSpecs );
3363 $msgSpecs = array_values( $msgSpecs );
3365 foreach ( $msgSpecs as $n => $spec ) {
3367 if ( is_array( $spec ) ) {
3369 $name = array_shift( $args );
3370 if ( isset( $args['options'] ) ) {
3371 $options = $args['options'];
3372 unset( $args['options'] );
3378 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3380 $this->addWikiText( $s );
3384 * Include jQuery core. Use this to avoid loading it multiple times
3385 * before we get a usable script loader.
3387 * @param $modules Array: list of jQuery modules which should be loaded
3388 * @return Array: the list of modules which were not loaded.
3390 * @deprecated since 1.17
3392 public function includeJQuery( $modules = array() ) {