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 * Constructor for OutputPage. This should not be called directly.
227 * Instead a new RequestContext should be created and it will implicitly create
228 * a OutputPage tied to that context.
230 function __construct( IContextSource
$context = null ) {
231 if ( $context === null ) {
232 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
233 wfDeprecated( __METHOD__
);
235 $this->setContext( $context );
240 * Redirect to $url rather than displaying the normal page
242 * @param $url String: URL
243 * @param $responsecode String: HTTP status code
245 public function redirect( $url, $responsecode = '302' ) {
246 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
247 $this->mRedirect
= str_replace( "\n", '', $url );
248 $this->mRedirectCode
= $responsecode;
252 * Get the URL to redirect to, or an empty string if not redirect URL set
256 public function getRedirect() {
257 return $this->mRedirect
;
261 * Set the HTTP status code to send with the output.
263 * @param $statusCode Integer
265 public function setStatusCode( $statusCode ) {
266 $this->mStatusCode
= $statusCode;
270 * Add a new <meta> tag
271 * To add an http-equiv meta tag, precede the name with "http:"
273 * @param $name String tag name
274 * @param $val String tag value
276 function addMeta( $name, $val ) {
277 array_push( $this->mMetatags
, array( $name, $val ) );
281 * Add a keyword or a list of keywords in the page header
283 * @param $text String or array of strings
285 function addKeyword( $text ) {
286 if( is_array( $text ) ) {
287 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
289 array_push( $this->mKeywords
, $text );
294 * Add a new \<link\> tag to the page header
296 * @param $linkarr Array: associative array of attributes.
298 function addLink( $linkarr ) {
299 array_push( $this->mLinktags
, $linkarr );
303 * Add a new \<link\> with "rel" attribute set to "meta"
305 * @param $linkarr Array: associative array mapping attribute names to their
306 * values, both keys and values will be escaped, and the
307 * "rel" attribute will be automatically added
309 function addMetadataLink( $linkarr ) {
310 $linkarr['rel'] = $this->getMetadataAttribute();
311 $this->addLink( $linkarr );
315 * Get the value of the "rel" attribute for metadata links
319 public function getMetadataAttribute() {
320 # note: buggy CC software only reads first "meta" link
321 static $haveMeta = false;
323 return 'alternate meta';
331 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
333 * @param $script String: raw HTML
335 function addScript( $script ) {
336 $this->mScripts
.= $script . "\n";
340 * Register and add a stylesheet from an extension directory.
342 * @param $url String path to sheet. Provide either a full url (beginning
343 * with 'http', etc) or a relative path from the document root
344 * (beginning with '/'). Otherwise it behaves identically to
345 * addStyle() and draws from the /skins folder.
347 public function addExtensionStyle( $url ) {
348 array_push( $this->mExtStyles
, $url );
352 * Get all styles added by extensions
356 function getExtStyle() {
357 return $this->mExtStyles
;
361 * Add a JavaScript file out of skins/common, or a given relative path.
363 * @param $file String: filename in skins/common or complete on-server path
365 * @param $version String: style version of the file. Defaults to $wgStyleVersion
367 public function addScriptFile( $file, $version = null ) {
368 global $wgStylePath, $wgStyleVersion;
369 // See if $file parameter is an absolute URL or begins with a slash
370 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
373 $path = "{$wgStylePath}/common/{$file}";
375 if ( is_null( $version ) )
376 $version = $wgStyleVersion;
377 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
381 * Add a self-contained script tag with the given contents
383 * @param $script String: JavaScript text, no <script> tags
385 public function addInlineScript( $script ) {
386 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
390 * Get all registered JS and CSS tags for the header.
394 function getScript() {
395 return $this->mScripts
. $this->getHeadItems();
399 * Filter an array of modules to remove insufficiently trustworthy members, and modules
400 * which are no longer registered (eg a page is cached before an extension is disabled)
401 * @param $modules Array
402 * @param $position String if not null, only return modules with this position
403 * @param $type string
406 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
407 $resourceLoader = $this->getResourceLoader();
408 $filteredModules = array();
409 foreach( $modules as $val ){
410 $module = $resourceLoader->getModule( $val );
411 if( $module instanceof ResourceLoaderModule
412 && $module->getOrigin() <= $this->getAllowedModules( $type )
413 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
415 $filteredModules[] = $val;
418 return $filteredModules;
422 * Get the list of modules to include on this page
424 * @param $filter Bool whether to filter out insufficiently trustworthy modules
425 * @param $position String if not null, only return modules with this position
426 * @param $param string
427 * @return Array of module names
429 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
430 $modules = array_values( array_unique( $this->$param ) );
432 ?
$this->filterModules( $modules, $position )
437 * Add one or more modules recognized by the resource loader. Modules added
438 * through this function will be loaded by the resource loader when the
441 * @param $modules Mixed: module name (string) or array of module names
443 public function addModules( $modules ) {
444 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
448 * Get the list of module JS to include on this page
453 * @return array of module names
455 public function getModuleScripts( $filter = false, $position = null ) {
456 return $this->getModules( $filter, $position, 'mModuleScripts' );
460 * Add only JS of one or more modules recognized by the resource loader. Module
461 * scripts added through this function will be loaded by the resource loader when
464 * @param $modules Mixed: module name (string) or array of module names
466 public function addModuleScripts( $modules ) {
467 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
471 * Get the list of module CSS to include on this page
476 * @return Array of module names
478 public function getModuleStyles( $filter = false, $position = null ) {
479 return $this->getModules( $filter, $position, 'mModuleStyles' );
483 * Add only CSS of one or more modules recognized by the resource loader. Module
484 * styles added through this function will be loaded by the resource loader when
487 * @param $modules Mixed: module name (string) or array of module names
489 public function addModuleStyles( $modules ) {
490 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
494 * Get the list of module messages to include on this page
499 * @return Array of module names
501 public function getModuleMessages( $filter = false, $position = null ) {
502 return $this->getModules( $filter, $position, 'mModuleMessages' );
506 * Add only messages of one or more modules recognized by the resource loader.
507 * Module messages added through this function will be loaded by the resource
508 * loader when the page loads.
510 * @param $modules Mixed: module name (string) or array of module names
512 public function addModuleMessages( $modules ) {
513 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
517 * Get an array of head items
521 function getHeadItemsArray() {
522 return $this->mHeadItems
;
526 * Get all header items in a string
530 function getHeadItems() {
532 foreach ( $this->mHeadItems
as $item ) {
539 * Add or replace an header item to the output
541 * @param $name String: item name
542 * @param $value String: raw HTML
544 public function addHeadItem( $name, $value ) {
545 $this->mHeadItems
[$name] = $value;
549 * Check if the header item $name is already set
551 * @param $name String: item name
554 public function hasHeadItem( $name ) {
555 return isset( $this->mHeadItems
[$name] );
559 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
561 * @param $tag String: value of "ETag" header
563 function setETag( $tag ) {
568 * Set whether the output should only contain the body of the article,
569 * without any skin, sidebar, etc.
570 * Used e.g. when calling with "action=render".
572 * @param $only Boolean: whether to output only the body of the article
574 public function setArticleBodyOnly( $only ) {
575 $this->mArticleBodyOnly
= $only;
579 * Return whether the output will contain only the body of the article
583 public function getArticleBodyOnly() {
584 return $this->mArticleBodyOnly
;
588 * checkLastModified tells the client to use the client-cached page if
589 * possible. If sucessful, the OutputPage is disabled so that
590 * any future call to OutputPage->output() have no effect.
592 * Side effect: sets mLastModified for Last-Modified header
594 * @param $timestamp string
596 * @return Boolean: true iff cache-ok headers was sent.
598 public function checkLastModified( $timestamp ) {
599 global $wgCachePages, $wgCacheEpoch;
601 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
602 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
605 if( !$wgCachePages ) {
606 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
609 if( $this->getUser()->getOption( 'nocache' ) ) {
610 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
614 $timestamp = wfTimestamp( TS_MW
, $timestamp );
615 $modifiedTimes = array(
616 'page' => $timestamp,
617 'user' => $this->getUser()->getTouched(),
618 'epoch' => $wgCacheEpoch
620 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
622 $maxModified = max( $modifiedTimes );
623 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
625 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
626 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
632 foreach ( $modifiedTimes as $name => $value ) {
633 if ( $info !== '' ) {
636 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
639 # IE sends sizes after the date like this:
640 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
641 # this breaks strtotime().
642 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
644 wfSuppressWarnings(); // E_STRICT system time bitching
645 $clientHeaderTime = strtotime( $clientHeader );
647 if ( !$clientHeaderTime ) {
648 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
651 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
653 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
654 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
655 wfDebug( __METHOD__
. ": effective Last-Modified: " .
656 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
657 if( $clientHeaderTime < $maxModified ) {
658 wfDebug( __METHOD__
. ": STALE, $info\n", false );
663 # Give a 304 response code and disable body output
664 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
665 ini_set( 'zlib.output_compression', 0 );
666 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
667 $this->sendCacheControl();
670 // Don't output a compressed blob when using ob_gzhandler;
671 // it's technically against HTTP spec and seems to confuse
672 // Firefox when the response gets split over two packets.
673 wfClearOutputBuffers();
679 * Override the last modified timestamp
681 * @param $timestamp String: new timestamp, in a format readable by
684 public function setLastModified( $timestamp ) {
685 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
689 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
691 * @param $policy String: the literal string to output as the contents of
692 * the meta tag. Will be parsed according to the spec and output in
696 public function setRobotPolicy( $policy ) {
697 $policy = Article
::formatRobotPolicy( $policy );
699 if( isset( $policy['index'] ) ) {
700 $this->setIndexPolicy( $policy['index'] );
702 if( isset( $policy['follow'] ) ) {
703 $this->setFollowPolicy( $policy['follow'] );
708 * Set the index policy for the page, but leave the follow policy un-
711 * @param $policy string Either 'index' or 'noindex'.
714 public function setIndexPolicy( $policy ) {
715 $policy = trim( $policy );
716 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
717 $this->mIndexPolicy
= $policy;
722 * Set the follow policy for the page, but leave the index policy un-
725 * @param $policy String: either 'follow' or 'nofollow'.
728 public function setFollowPolicy( $policy ) {
729 $policy = trim( $policy );
730 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
731 $this->mFollowPolicy
= $policy;
736 * Set the new value of the "action text", this will be added to the
737 * "HTML title", separated from it with " - ".
739 * @param $text String: new value of the "action text"
741 public function setPageTitleActionText( $text ) {
742 $this->mPageTitleActionText
= $text;
746 * Get the value of the "action text"
750 public function getPageTitleActionText() {
751 if ( isset( $this->mPageTitleActionText
) ) {
752 return $this->mPageTitleActionText
;
757 * "HTML title" means the contents of <title>.
758 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
760 * @param $name string
762 public function setHTMLTitle( $name ) {
763 if ( $name instanceof Message
) {
764 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
766 $this->mHTMLtitle
= $name;
771 * Return the "HTML title", i.e. the content of the <title> tag.
775 public function getHTMLTitle() {
776 return $this->mHTMLtitle
;
780 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
781 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
782 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
783 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
785 * @param $name string|Message
787 public function setPageTitle( $name ) {
788 if ( $name instanceof Message
) {
789 $name = $name->setContext( $this->getContext() )->text();
792 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
793 # but leave "<i>foobar</i>" alone
794 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
795 $this->mPagetitle
= $nameWithTags;
797 # change "<i>foo&bar</i>" to "foo&bar"
798 $this->setHTMLTitle( $this->msg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
802 * Return the "page title", i.e. the content of the \<h1\> tag.
806 public function getPageTitle() {
807 return $this->mPagetitle
;
811 * Set the Title object to use
813 * @param $t Title object
815 public function setTitle( Title
$t ) {
816 $this->getContext()->setTitle( $t );
821 * Replace the subtile with $str
823 * @param $str String|Message: new value of the subtitle
825 public function setSubtitle( $str ) {
826 $this->clearSubtitle();
827 $this->addSubtitle( $str );
831 * Add $str to the subtitle
833 * @deprecated in 1.19; use addSubtitle() instead
834 * @param $str String|Message to add to the subtitle
836 public function appendSubtitle( $str ) {
837 $this->addSubtitle( $str );
841 * Add $str to the subtitle
843 * @param $str String|Message to add to the subtitle
845 public function addSubtitle( $str ) {
846 if ( $str instanceof Message
) {
847 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
849 $this->mSubtitle
[] = $str;
854 * Add a subtitle containing a backlink to a page
856 * @param $title Title to link to
858 public function addBacklinkSubtitle( Title
$title ) {
860 if ( $title->isRedirect() ) {
861 $query['redirect'] = 'no';
863 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
867 * Clear the subtitles
869 public function clearSubtitle() {
870 $this->mSubtitle
= array();
878 public function getSubtitle() {
879 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
883 * Set the page as printable, i.e. it'll be displayed with with all
884 * print styles included
886 public function setPrintable() {
887 $this->mPrintable
= true;
891 * Return whether the page is "printable"
895 public function isPrintable() {
896 return $this->mPrintable
;
900 * Disable output completely, i.e. calling output() will have no effect
902 public function disable() {
903 $this->mDoNothing
= true;
907 * Return whether the output will be completely disabled
911 public function isDisabled() {
912 return $this->mDoNothing
;
916 * Show an "add new section" link?
920 public function showNewSectionLink() {
921 return $this->mNewSectionLink
;
925 * Forcibly hide the new section link?
929 public function forceHideNewSectionLink() {
930 return $this->mHideNewSectionLink
;
934 * Add or remove feed links in the page header
935 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
936 * for the new version
939 * @param $show Boolean: true: add default feeds, false: remove all feeds
941 public function setSyndicated( $show = true ) {
943 $this->setFeedAppendQuery( false );
945 $this->mFeedLinks
= array();
950 * Add default feeds to the page header
951 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
952 * for the new version
955 * @param $val String: query to append to feed links or false to output
958 public function setFeedAppendQuery( $val ) {
959 global $wgAdvertisedFeedTypes;
961 $this->mFeedLinks
= array();
963 foreach ( $wgAdvertisedFeedTypes as $type ) {
964 $query = "feed=$type";
965 if ( is_string( $val ) ) {
966 $query .= '&' . $val;
968 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
973 * Add a feed link to the page header
975 * @param $format String: feed type, should be a key of $wgFeedClasses
976 * @param $href String: URL
978 public function addFeedLink( $format, $href ) {
979 global $wgAdvertisedFeedTypes;
981 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
982 $this->mFeedLinks
[$format] = $href;
987 * Should we output feed links for this page?
990 public function isSyndicated() {
991 return count( $this->mFeedLinks
) > 0;
995 * Return URLs for each supported syndication format for this page.
996 * @return array associating format keys with URLs
998 public function getSyndicationLinks() {
999 return $this->mFeedLinks
;
1003 * Will currently always return null
1007 public function getFeedAppendQuery() {
1008 return $this->mFeedLinksAppendQuery
;
1012 * Set whether the displayed content is related to the source of the
1013 * corresponding article on the wiki
1014 * Setting true will cause the change "article related" toggle to true
1018 public function setArticleFlag( $v ) {
1019 $this->mIsarticle
= $v;
1021 $this->mIsArticleRelated
= $v;
1026 * Return whether the content displayed page is related to the source of
1027 * the corresponding article on the wiki
1031 public function isArticle() {
1032 return $this->mIsarticle
;
1036 * Set whether this page is related an article on the wiki
1037 * Setting false will cause the change of "article flag" toggle to false
1041 public function setArticleRelated( $v ) {
1042 $this->mIsArticleRelated
= $v;
1044 $this->mIsarticle
= false;
1049 * Return whether this page is related an article on the wiki
1053 public function isArticleRelated() {
1054 return $this->mIsArticleRelated
;
1058 * Add new language links
1060 * @param $newLinkArray Associative array mapping language code to the page
1063 public function addLanguageLinks( $newLinkArray ) {
1064 $this->mLanguageLinks +
= $newLinkArray;
1068 * Reset the language links and add new language links
1070 * @param $newLinkArray Associative array mapping language code to the page
1073 public function setLanguageLinks( $newLinkArray ) {
1074 $this->mLanguageLinks
= $newLinkArray;
1078 * Get the list of language links
1080 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1082 public function getLanguageLinks() {
1083 return $this->mLanguageLinks
;
1087 * Add an array of categories, with names in the keys
1089 * @param $categories Array mapping category name => sort key
1091 public function addCategoryLinks( $categories ) {
1094 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1098 # Add the links to a LinkBatch
1099 $arr = array( NS_CATEGORY
=> $categories );
1100 $lb = new LinkBatch
;
1101 $lb->setArray( $arr );
1103 # Fetch existence plus the hiddencat property
1104 $dbr = wfGetDB( DB_SLAVE
);
1105 $res = $dbr->select( array( 'page', 'page_props' ),
1106 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1107 $lb->constructSet( 'page', $dbr ),
1110 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1113 # Add the results to the link cache
1114 $lb->addResultToCache( LinkCache
::singleton(), $res );
1116 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1117 $categories = array_combine(
1118 array_keys( $categories ),
1119 array_fill( 0, count( $categories ), 'normal' )
1122 # Mark hidden categories
1123 foreach ( $res as $row ) {
1124 if ( isset( $row->pp_value
) ) {
1125 $categories[$row->page_title
] = 'hidden';
1129 # Add the remaining categories to the skin
1130 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1131 foreach ( $categories as $category => $type ) {
1132 $origcategory = $category;
1133 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1134 $wgContLang->findVariantLink( $category, $title, true );
1135 if ( $category != $origcategory ) {
1136 if ( array_key_exists( $category, $categories ) ) {
1140 $text = $wgContLang->convertHtml( $title->getText() );
1141 $this->mCategories
[] = $title->getText();
1142 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1148 * Reset the category links (but not the category list) and add $categories
1150 * @param $categories Array mapping category name => sort key
1152 public function setCategoryLinks( $categories ) {
1153 $this->mCategoryLinks
= array();
1154 $this->addCategoryLinks( $categories );
1158 * Get the list of category links, in a 2-D array with the following format:
1159 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1160 * hidden categories) and $link a HTML fragment with a link to the category
1165 public function getCategoryLinks() {
1166 return $this->mCategoryLinks
;
1170 * Get the list of category names this page belongs to
1172 * @return Array of strings
1174 public function getCategories() {
1175 return $this->mCategories
;
1179 * Do not allow scripts which can be modified by wiki users to load on this page;
1180 * only allow scripts bundled with, or generated by, the software.
1182 public function disallowUserJs() {
1183 $this->reduceAllowedModules(
1184 ResourceLoaderModule
::TYPE_SCRIPTS
,
1185 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1190 * Return whether user JavaScript is allowed for this page
1191 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1192 * trustworthiness is identified and enforced automagically.
1195 public function isUserJsAllowed() {
1196 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1200 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1201 * @see ResourceLoaderModule::$origin
1202 * @param $type String ResourceLoaderModule TYPE_ constant
1203 * @return Int ResourceLoaderModule ORIGIN_ class constant
1205 public function getAllowedModules( $type ){
1206 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1207 return min( array_values( $this->mAllowedModules
) );
1209 return isset( $this->mAllowedModules
[$type] )
1210 ?
$this->mAllowedModules
[$type]
1211 : ResourceLoaderModule
::ORIGIN_ALL
;
1216 * Set the highest level of CSS/JS untrustworthiness allowed
1217 * @param $type String ResourceLoaderModule TYPE_ constant
1218 * @param $level Int ResourceLoaderModule class constant
1220 public function setAllowedModules( $type, $level ){
1221 $this->mAllowedModules
[$type] = $level;
1225 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1226 * @param $type String
1227 * @param $level Int ResourceLoaderModule class constant
1229 public function reduceAllowedModules( $type, $level ){
1230 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1234 * Prepend $text to the body HTML
1236 * @param $text String: HTML
1238 public function prependHTML( $text ) {
1239 $this->mBodytext
= $text . $this->mBodytext
;
1243 * Append $text to the body HTML
1245 * @param $text String: HTML
1247 public function addHTML( $text ) {
1248 $this->mBodytext
.= $text;
1252 * Shortcut for adding an Html::element via addHTML.
1256 * @param $element string
1257 * @param $attribs array
1258 * @param $contents string
1260 public function addElement( $element, $attribs = array(), $contents = '' ) {
1261 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1265 * Clear the body HTML
1267 public function clearHTML() {
1268 $this->mBodytext
= '';
1274 * @return String: HTML
1276 public function getHTML() {
1277 return $this->mBodytext
;
1281 * Add $text to the debug output
1283 * @param $text String: debug text
1285 public function debug( $text ) {
1286 $this->mDebugtext
.= $text;
1290 * Get/set the ParserOptions object to use for wikitext parsing
1292 * @param $options either the ParserOption to use or null to only get the
1293 * current ParserOption object
1294 * @return ParserOptions object
1296 public function parserOptions( $options = null ) {
1297 if ( !$this->mParserOptions
) {
1298 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1299 $this->mParserOptions
->setEditSection( false );
1301 return wfSetVar( $this->mParserOptions
, $options );
1305 * Set the revision ID which will be seen by the wiki text parser
1306 * for things such as embedded {{REVISIONID}} variable use.
1308 * @param $revid Mixed: an positive integer, or null
1309 * @return Mixed: previous value
1311 public function setRevisionId( $revid ) {
1312 $val = is_null( $revid ) ?
null : intval( $revid );
1313 return wfSetVar( $this->mRevisionId
, $val );
1317 * Get the displayed revision ID
1321 public function getRevisionId() {
1322 return $this->mRevisionId
;
1326 * Set the displayed file version
1328 * @param $file File|false
1329 * @return Mixed: previous value
1331 public function setFileVersion( $file ) {
1333 if ( $file instanceof File
&& $file->exists() ) {
1334 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1336 return wfSetVar( $this->mFileVersion
, $val, true );
1340 * Get the displayed file version
1342 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1344 public function getFileVersion() {
1345 return $this->mFileVersion
;
1349 * Get the templates used on this page
1351 * @return Array (namespace => dbKey => revId)
1354 public function getTemplateIds() {
1355 return $this->mTemplateIds
;
1359 * Get the files used on this page
1361 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1364 public function getFileSearchOptions() {
1365 return $this->mImageTimeKeys
;
1369 * Convert wikitext to HTML and add it to the buffer
1370 * Default assumes that the current page title will be used.
1372 * @param $text String
1373 * @param $linestart Boolean: is this the start of a line?
1374 * @param $interface Boolean: is this text in the user interface language?
1376 public function addWikiText( $text, $linestart = true, $interface = true ) {
1377 $title = $this->getTitle(); // Work arround E_STRICT
1378 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1382 * Add wikitext with a custom Title object
1384 * @param $text String: wikitext
1385 * @param $title Title object
1386 * @param $linestart Boolean: is this the start of a line?
1388 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1389 $this->addWikiTextTitle( $text, $title, $linestart );
1393 * Add wikitext with a custom Title object and tidy enabled.
1395 * @param $text String: wikitext
1396 * @param $title Title object
1397 * @param $linestart Boolean: is this the start of a line?
1399 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1400 $this->addWikiTextTitle( $text, $title, $linestart, true );
1404 * Add wikitext with tidy enabled
1406 * @param $text String: wikitext
1407 * @param $linestart Boolean: is this the start of a line?
1409 public function addWikiTextTidy( $text, $linestart = true ) {
1410 $title = $this->getTitle();
1411 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1415 * Add wikitext with a custom Title object
1417 * @param $text String: wikitext
1418 * @param $title Title object
1419 * @param $linestart Boolean: is this the start of a line?
1420 * @param $tidy Boolean: whether to use tidy
1421 * @param $interface Boolean: whether it is an interface message
1422 * (for example disables conversion)
1424 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1427 wfProfileIn( __METHOD__
);
1429 wfIncrStats( 'pcache_not_possible' );
1431 $popts = $this->parserOptions();
1432 $oldTidy = $popts->setTidy( $tidy );
1433 $popts->setInterfaceMessage( (bool) $interface );
1435 $parserOutput = $wgParser->parse(
1436 $text, $title, $popts,
1437 $linestart, true, $this->mRevisionId
1440 $popts->setTidy( $oldTidy );
1442 $this->addParserOutput( $parserOutput );
1444 wfProfileOut( __METHOD__
);
1448 * Add a ParserOutput object, but without Html
1450 * @param $parserOutput ParserOutput object
1452 public function addParserOutputNoText( &$parserOutput ) {
1453 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1454 $this->addCategoryLinks( $parserOutput->getCategories() );
1455 $this->mNewSectionLink
= $parserOutput->getNewSection();
1456 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1458 $this->mParseWarnings
= $parserOutput->getWarnings();
1459 if ( !$parserOutput->isCacheable() ) {
1460 $this->enableClientCache( false );
1462 $this->mNoGallery
= $parserOutput->getNoGallery();
1463 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1464 $this->addModules( $parserOutput->getModules() );
1465 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1466 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1467 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1469 // Template versioning...
1470 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1471 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1472 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1474 $this->mTemplateIds
[$ns] = $dbks;
1477 // File versioning...
1478 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1479 $this->mImageTimeKeys
[$dbk] = $data;
1482 // Hooks registered in the object
1483 global $wgParserOutputHooks;
1484 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1485 list( $hookName, $data ) = $hookInfo;
1486 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1487 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1491 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1495 * Add a ParserOutput object
1497 * @param $parserOutput ParserOutput
1499 function addParserOutput( &$parserOutput ) {
1500 $this->addParserOutputNoText( $parserOutput );
1501 $text = $parserOutput->getText();
1502 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1503 $this->addHTML( $text );
1508 * Add the output of a QuickTemplate to the output buffer
1510 * @param $template QuickTemplate
1512 public function addTemplate( &$template ) {
1514 $template->execute();
1515 $this->addHTML( ob_get_contents() );
1520 * Parse wikitext and return the HTML.
1522 * @param $text String
1523 * @param $linestart Boolean: is this the start of a line?
1524 * @param $interface Boolean: use interface language ($wgLang instead of
1525 * $wgContLang) while parsing language sensitive magic
1526 * words like GRAMMAR and PLURAL. This also disables
1527 * LanguageConverter.
1528 * @param $language Language object: target language object, will override
1530 * @return String: HTML
1532 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1535 if( is_null( $this->getTitle() ) ) {
1536 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1539 $popts = $this->parserOptions();
1541 $popts->setInterfaceMessage( true );
1543 if ( $language !== null ) {
1544 $oldLang = $popts->setTargetLanguage( $language );
1547 $parserOutput = $wgParser->parse(
1548 $text, $this->getTitle(), $popts,
1549 $linestart, true, $this->mRevisionId
1553 $popts->setInterfaceMessage( false );
1555 if ( $language !== null ) {
1556 $popts->setTargetLanguage( $oldLang );
1559 return $parserOutput->getText();
1563 * Parse wikitext, strip paragraphs, and return the HTML.
1565 * @param $text String
1566 * @param $linestart Boolean: is this the start of a line?
1567 * @param $interface Boolean: use interface language ($wgLang instead of
1568 * $wgContLang) while parsing language sensitive magic
1569 * words like GRAMMAR and PLURAL
1570 * @return String: HTML
1572 public function parseInline( $text, $linestart = true, $interface = false ) {
1573 $parsed = $this->parse( $text, $linestart, $interface );
1576 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1584 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1586 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1588 public function setSquidMaxage( $maxage ) {
1589 $this->mSquidMaxage
= $maxage;
1593 * Use enableClientCache(false) to force it to send nocache headers
1595 * @param $state bool
1599 public function enableClientCache( $state ) {
1600 return wfSetVar( $this->mEnableClientCache
, $state );
1604 * Get the list of cookies that will influence on the cache
1608 function getCacheVaryCookies() {
1609 global $wgCookiePrefix, $wgCacheVaryCookies;
1611 if ( $cookies === null ) {
1612 $cookies = array_merge(
1614 "{$wgCookiePrefix}Token",
1615 "{$wgCookiePrefix}LoggedOut",
1620 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1626 * Return whether this page is not cacheable because "useskin" or "uselang"
1627 * URL parameters were passed.
1631 function uncacheableBecauseRequestVars() {
1632 $request = $this->getRequest();
1633 return $request->getText( 'useskin', false ) === false
1634 && $request->getText( 'uselang', false ) === false;
1638 * Check if the request has a cache-varying cookie header
1639 * If it does, it's very important that we don't allow public caching
1643 function haveCacheVaryCookies() {
1644 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1645 if ( $cookieHeader === false ) {
1648 $cvCookies = $this->getCacheVaryCookies();
1649 foreach ( $cvCookies as $cookieName ) {
1650 # Check for a simple string match, like the way squid does it
1651 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1652 wfDebug( __METHOD__
. ": found $cookieName\n" );
1656 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1661 * Add an HTTP header that will influence on the cache
1663 * @param $header String: header name
1664 * @param $option Array|null
1665 * @todo FIXME: Document the $option parameter; it appears to be for
1666 * X-Vary-Options but what format is acceptable?
1668 public function addVaryHeader( $header, $option = null ) {
1669 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1670 $this->mVaryHeader
[$header] = (array)$option;
1671 } elseif( is_array( $option ) ) {
1672 if( is_array( $this->mVaryHeader
[$header] ) ) {
1673 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1675 $this->mVaryHeader
[$header] = $option;
1678 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1682 * Get a complete X-Vary-Options header
1686 public function getXVO() {
1687 $cvCookies = $this->getCacheVaryCookies();
1689 $cookiesOption = array();
1690 foreach ( $cvCookies as $cookieName ) {
1691 $cookiesOption[] = 'string-contains=' . $cookieName;
1693 $this->addVaryHeader( 'Cookie', $cookiesOption );
1696 foreach( $this->mVaryHeader
as $header => $option ) {
1697 $newheader = $header;
1698 if( is_array( $option ) ) {
1699 $newheader .= ';' . implode( ';', $option );
1701 $headers[] = $newheader;
1703 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1709 * bug 21672: Add Accept-Language to Vary and XVO headers
1710 * if there's no 'variant' parameter existed in GET.
1713 * /w/index.php?title=Main_page should always be served; but
1714 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1716 function addAcceptLanguage() {
1717 $lang = $this->getTitle()->getPageLanguage();
1718 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1719 $variants = $lang->getVariants();
1720 $aloption = array();
1721 foreach ( $variants as $variant ) {
1722 if( $variant === $lang->getCode() ) {
1725 $aloption[] = 'string-contains=' . $variant;
1727 // IE and some other browsers use another form of language code
1728 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1729 // We should handle these too.
1730 $ievariant = explode( '-', $variant );
1731 if ( count( $ievariant ) == 2 ) {
1732 $ievariant[1] = strtoupper( $ievariant[1] );
1733 $ievariant = implode( '-', $ievariant );
1734 $aloption[] = 'string-contains=' . $ievariant;
1738 $this->addVaryHeader( 'Accept-Language', $aloption );
1743 * Set a flag which will cause an X-Frame-Options header appropriate for
1744 * edit pages to be sent. The header value is controlled by
1745 * $wgEditPageFrameOptions.
1747 * This is the default for special pages. If you display a CSRF-protected
1748 * form on an ordinary view page, then you need to call this function.
1750 * @param $enable bool
1752 public function preventClickjacking( $enable = true ) {
1753 $this->mPreventClickjacking
= $enable;
1757 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1758 * This can be called from pages which do not contain any CSRF-protected
1761 public function allowClickjacking() {
1762 $this->mPreventClickjacking
= false;
1766 * Get the X-Frame-Options header value (without the name part), or false
1767 * if there isn't one. This is used by Skin to determine whether to enable
1768 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1772 public function getFrameOptions() {
1773 global $wgBreakFrames, $wgEditPageFrameOptions;
1774 if ( $wgBreakFrames ) {
1776 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1777 return $wgEditPageFrameOptions;
1783 * Send cache control HTTP headers
1785 public function sendCacheControl() {
1786 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1788 $response = $this->getRequest()->response();
1789 if ( $wgUseETag && $this->mETag
) {
1790 $response->header( "ETag: $this->mETag" );
1793 $this->addAcceptLanguage();
1795 # don't serve compressed data to clients who can't handle it
1796 # maintain different caches for logged-in users and non-logged in ones
1797 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1800 # Add an X-Vary-Options header for Squid with Wikimedia patches
1801 $response->header( $this->getXVO() );
1804 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1806 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1807 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1811 # We'll purge the proxy cache explicitly, but require end user agents
1812 # to revalidate against the proxy on each visit.
1813 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1814 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1815 # start with a shorter timeout for initial testing
1816 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1817 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1818 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1820 # We'll purge the proxy cache for anons explicitly, but require end user agents
1821 # to revalidate against the proxy on each visit.
1822 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1823 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1824 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1825 # start with a shorter timeout for initial testing
1826 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1827 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1830 # We do want clients to cache if they can, but they *must* check for updates
1831 # on revisiting the page.
1832 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1833 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1834 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1836 if($this->mLastModified
) {
1837 $response->header( "Last-Modified: {$this->mLastModified}" );
1840 wfDebug( __METHOD__
. ": no caching **\n", false );
1842 # In general, the absence of a last modified header should be enough to prevent
1843 # the client from using its cache. We send a few other things just to make sure.
1844 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1845 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1846 $response->header( 'Pragma: no-cache' );
1851 * Get the message associed with the HTTP response code $code
1853 * @param $code Integer: status code
1854 * @return String or null: message or null if $code is not in the list of
1857 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1859 public static function getStatusMessage( $code ) {
1860 wfDeprecated( __METHOD__
);
1861 return HttpStatus
::getMessage( $code );
1865 * Finally, all the text has been munged and accumulated into
1866 * the object, let's actually output it:
1868 public function output() {
1869 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1871 if( $this->mDoNothing
) {
1875 wfProfileIn( __METHOD__
);
1877 $response = $this->getRequest()->response();
1879 if ( $this->mRedirect
!= '' ) {
1880 # Standards require redirect URLs to be absolute
1881 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1882 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1883 if( !$wgDebugRedirects ) {
1884 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1885 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1887 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1889 if ( $wgVaryOnXFP ) {
1890 $this->addVaryHeader( 'X-Forwarded-Proto' );
1892 $this->sendCacheControl();
1894 $response->header( "Content-Type: text/html; charset=utf-8" );
1895 if( $wgDebugRedirects ) {
1896 $url = htmlspecialchars( $this->mRedirect
);
1897 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1898 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1899 print "</body>\n</html>\n";
1901 $response->header( 'Location: ' . $this->mRedirect
);
1903 wfProfileOut( __METHOD__
);
1905 } elseif ( $this->mStatusCode
) {
1906 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1908 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1912 # Buffer output; final headers may depend on later processing
1915 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1916 $response->header( 'Content-language: ' . $wgLanguageCode );
1918 // Prevent framing, if requested
1919 $frameOptions = $this->getFrameOptions();
1920 if ( $frameOptions ) {
1921 $response->header( "X-Frame-Options: $frameOptions" );
1924 if ( $this->mArticleBodyOnly
) {
1925 $this->out( $this->mBodytext
);
1927 $this->addDefaultModules();
1929 $sk = $this->getSkin();
1931 // Hook that allows last minute changes to the output page, e.g.
1932 // adding of CSS or Javascript by extensions.
1933 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1935 wfProfileIn( 'Output-skin' );
1937 wfProfileOut( 'Output-skin' );
1940 $this->sendCacheControl();
1942 wfProfileOut( __METHOD__
);
1946 * Actually output something with print().
1948 * @param $ins String: the string to output
1950 public function out( $ins ) {
1955 * Produce a "user is blocked" page.
1956 * @deprecated since 1.18
1958 function blockedPage() {
1959 throw new UserBlockedError( $this->getUser()->mBlock
);
1963 * Prepare this object to display an error page; disable caching and
1964 * indexing, clear the current text and redirect, set the page's title
1965 * and optionally an custom HTML title (content of the <title> tag).
1967 * @param $pageTitle String|Message will be passed directly to setPageTitle()
1968 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
1969 * optional, if not passed the <title> attribute will be
1970 * based on $pageTitle
1972 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
1973 if ( $this->getTitle() ) {
1974 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1977 $this->setPageTitle( $pageTitle );
1978 if ( $htmlTitle !== false ) {
1979 $this->setHTMLTitle( $htmlTitle );
1981 $this->setRobotPolicy( 'noindex,nofollow' );
1982 $this->setArticleRelated( false );
1983 $this->enableClientCache( false );
1984 $this->mRedirect
= '';
1985 $this->clearSubtitle();
1990 * Output a standard error page
1992 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1993 * showErrorPage( 'titlemsg', $messageObject );
1995 * @param $title String: message key for page title
1996 * @param $msg Mixed: message key (string) for page text, or a Message object
1997 * @param $params Array: message parameters; ignored if $msg is a Message object
1999 public function showErrorPage( $title, $msg, $params = array() ) {
2000 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2002 if ( $msg instanceof Message
){
2003 $this->addHTML( $msg->parse() );
2005 $this->addWikiMsgArray( $msg, $params );
2008 $this->returnToMain();
2012 * Output a standard permission error page
2014 * @param $errors Array: error message keys
2015 * @param $action String: action that was denied or null if unknown
2017 public function showPermissionsErrorPage( $errors, $action = null ) {
2018 global $wgGroupPermissions;
2020 // For some action (read, edit, create and upload), display a "login to do this action"
2021 // error if all of the following conditions are met:
2022 // 1. the user is not logged in
2023 // 2. the only error is insufficient permissions (i.e. no block or something else)
2024 // 3. the error can be avoided simply by logging in
2025 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2026 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2027 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2028 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2029 ||
( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2031 $displayReturnto = null;
2033 # Due to bug 32276, if a user does not have read permissions,
2034 # $this->getTitle() will just give Special:Badtitle, which is
2035 # not especially useful as a returnto parameter. Use the title
2036 # from the request instead, if there was one.
2037 $request = $this->getRequest();
2038 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2039 if ( $action == 'edit' ) {
2040 $msg = 'whitelistedittext';
2041 $displayReturnto = $returnto;
2042 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2043 $msg = 'nocreatetext';
2044 } elseif ( $action == 'upload' ) {
2045 $msg = 'uploadnologintext';
2047 $msg = 'loginreqpagetext';
2048 $displayReturnto = Title
::newMainPage();
2054 $query['returnto'] = $returnto->getPrefixedText();
2056 if ( !$request->wasPosted() ) {
2057 $returntoquery = $request->getValues();
2058 unset( $returntoquery['title'] );
2059 unset( $returntoquery['returnto'] );
2060 unset( $returntoquery['returntoquery'] );
2061 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2064 $loginLink = Linker
::linkKnown(
2065 SpecialPage
::getTitleFor( 'Userlogin' ),
2066 $this->msg( 'loginreqlink' )->escaped(),
2071 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2072 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2074 # Don't return to a page the user can't read otherwise
2075 # we'll end up in a pointless loop
2076 if ( $displayReturnto && $displayReturnto->userCanRead() ) {
2077 $this->returnToMain( null, $displayReturnto );
2080 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2081 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2086 * Display an error page indicating that a given version of MediaWiki is
2087 * required to use it
2089 * @param $version Mixed: the version of MediaWiki needed to use the page
2091 public function versionRequired( $version ) {
2092 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2094 $this->addWikiMsg( 'versionrequiredtext', $version );
2095 $this->returnToMain();
2099 * Display an error page noting that a given permission bit is required.
2100 * @deprecated since 1.18, just throw the exception directly
2101 * @param $permission String: key required
2103 public function permissionRequired( $permission ) {
2104 throw new PermissionsError( $permission );
2108 * Produce the stock "please login to use the wiki" page
2110 * @deprecated in 1.19; throw the exception directly
2112 public function loginToUse() {
2113 throw new PermissionsError( 'read' );
2117 * Format a list of error messages
2119 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2120 * @param $action String: action that was denied or null if unknown
2121 * @return String: the wikitext error-messages, formatted into a list.
2123 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2124 if ( $action == null ) {
2125 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2127 $action_desc = $this->msg( "action-$action" )->plain();
2129 'permissionserrorstext-withaction',
2132 )->plain() . "\n\n";
2135 if ( count( $errors ) > 1 ) {
2136 $text .= '<ul class="permissions-errors">' . "\n";
2138 foreach( $errors as $error ) {
2140 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2145 $text .= "<div class=\"permissions-errors\">\n" .
2146 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2154 * Display a page stating that the Wiki is in read-only mode,
2155 * and optionally show the source of the page that the user
2156 * was trying to edit. Should only be called (for this
2157 * purpose) after wfReadOnly() has returned true.
2159 * For historical reasons, this function is _also_ used to
2160 * show the error message when a user tries to edit a page
2161 * they are not allowed to edit. (Unless it's because they're
2162 * blocked, then we show blockedPage() instead.) In this
2163 * case, the second parameter should be set to true and a list
2164 * of reasons supplied as the third parameter.
2166 * @todo Needs to be split into multiple functions.
2168 * @param $source String: source code to show (or null).
2169 * @param $protected Boolean: is this a permissions error?
2170 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2171 * @param $action String: action that was denied or null if unknown
2173 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2174 $this->setRobotPolicy( 'noindex,nofollow' );
2175 $this->setArticleRelated( false );
2177 // If no reason is given, just supply a default "I can't let you do
2178 // that, Dave" message. Should only occur if called by legacy code.
2179 if ( $protected && empty( $reasons ) ) {
2180 $reasons[] = array( 'badaccess-group0' );
2183 if ( !empty( $reasons ) ) {
2184 // Permissions error
2186 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2187 $this->addBacklinkSubtitle( $this->getTitle() );
2189 $this->setPageTitle( $this->msg( 'badaccess' ) );
2191 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2193 // Wiki is read only
2194 throw new ReadOnlyError
;
2197 // Show source, if supplied
2198 if( is_string( $source ) ) {
2199 $this->addWikiMsg( 'viewsourcetext' );
2201 $pageLang = $this->getTitle()->getPageLanguage();
2203 'id' => 'wpTextbox1',
2204 'name' => 'wpTextbox1',
2205 'cols' => $this->getUser()->getOption( 'cols' ),
2206 'rows' => $this->getUser()->getOption( 'rows' ),
2207 'readonly' => 'readonly',
2208 'lang' => $pageLang->getCode(),
2209 'dir' => $pageLang->getDir(),
2211 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2213 // Show templates used by this article
2214 $page = WikiPage
::factory( $this->getTitle() );
2215 $templates = Linker
::formatTemplates( $page->getUsedTemplates() );
2216 $this->addHTML( "<div class='templatesUsed'>
2222 # If the title doesn't exist, it's fairly pointless to print a return
2223 # link to it. After all, you just tried editing it and couldn't, so
2224 # what's there to do there?
2225 if( $this->getTitle()->exists() ) {
2226 $this->returnToMain( null, $this->getTitle() );
2231 * Turn off regular page output and return an error reponse
2232 * for when rate limiting has triggered.
2234 public function rateLimited() {
2235 throw new ThrottledError
;
2239 * Show a warning about slave lag
2241 * If the lag is higher than $wgSlaveLagCritical seconds,
2242 * then the warning is a bit more obvious. If the lag is
2243 * lower than $wgSlaveLagWarning, then no warning is shown.
2245 * @param $lag Integer: slave lag
2247 public function showLagWarning( $lag ) {
2248 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2249 if( $lag >= $wgSlaveLagWarning ) {
2250 $message = $lag < $wgSlaveLagCritical
2253 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2254 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2258 public function showFatalError( $message ) {
2259 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2261 $this->addHTML( $message );
2264 public function showUnexpectedValueError( $name, $val ) {
2265 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2268 public function showFileCopyError( $old, $new ) {
2269 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2272 public function showFileRenameError( $old, $new ) {
2273 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2276 public function showFileDeleteError( $name ) {
2277 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2280 public function showFileNotFoundError( $name ) {
2281 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2285 * Add a "return to" link pointing to a specified title
2287 * @param $title Title to link
2288 * @param $query String query string
2289 * @param $text String text of the link (input is not escaped)
2291 public function addReturnTo( $title, $query = array(), $text = null ) {
2292 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2293 $link = $this->msg( 'returnto' )->rawParams(
2294 Linker
::link( $title, $text, array(), $query ) )->escaped();
2295 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2299 * Add a "return to" link pointing to a specified title,
2300 * or the title indicated in the request, or else the main page
2302 * @param $unused No longer used
2303 * @param $returnto Title or String to return to
2304 * @param $returntoquery String: query string for the return to link
2306 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2307 if ( $returnto == null ) {
2308 $returnto = $this->getRequest()->getText( 'returnto' );
2311 if ( $returntoquery == null ) {
2312 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2315 if ( $returnto === '' ) {
2316 $returnto = Title
::newMainPage();
2319 if ( is_object( $returnto ) ) {
2320 $titleObj = $returnto;
2322 $titleObj = Title
::newFromText( $returnto );
2324 if ( !is_object( $titleObj ) ) {
2325 $titleObj = Title
::newMainPage();
2328 $this->addReturnTo( $titleObj, $returntoquery );
2332 * @param $sk Skin The given Skin
2333 * @param $includeStyle Boolean: unused
2334 * @return String: The doctype, opening <html>, and head element.
2336 public function headElement( Skin
$sk, $includeStyle = true ) {
2338 $userdir = $this->getLanguage()->getDir();
2339 $sitedir = $wgContLang->getDir();
2341 if ( $sk->commonPrintStylesheet() ) {
2342 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2345 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2347 if ( $this->getHTMLTitle() == '' ) {
2348 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2351 $openHead = Html
::openElement( 'head' );
2353 # Don't bother with the newline if $head == ''
2354 $ret .= "$openHead\n";
2357 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2359 $ret .= implode( "\n", array(
2360 $this->getHeadLinks( null, true ),
2361 $this->buildCssLinks(),
2362 $this->getHeadScripts(),
2363 $this->getHeadItems()
2366 $closeHead = Html
::closeElement( 'head' );
2368 $ret .= "$closeHead\n";
2371 $bodyAttrs = array();
2373 # Classes for LTR/RTL directionality support
2374 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2376 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2377 # A <body> class is probably not the best way to do this . . .
2378 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2380 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2381 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2383 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2384 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2386 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2392 * Add the default ResourceLoader modules to this object
2394 private function addDefaultModules() {
2395 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2397 // Add base resources
2398 $this->addModules( array(
2401 'mediawiki.page.startup',
2402 'mediawiki.page.ready',
2404 if ( $wgIncludeLegacyJavaScript ){
2405 $this->addModules( 'mediawiki.legacy.wikibits' );
2408 // Add various resources if required
2410 $this->addModules( 'mediawiki.legacy.ajax' );
2412 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2414 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2415 $this->addModules( 'mediawiki.action.watch.ajax' );
2418 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2419 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2423 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2424 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2427 # Crazy edit-on-double-click stuff
2428 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2429 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2434 * Get a ResourceLoader object associated with this OutputPage
2436 * @return ResourceLoader
2438 public function getResourceLoader() {
2439 if ( is_null( $this->mResourceLoader
) ) {
2440 $this->mResourceLoader
= new ResourceLoader();
2442 return $this->mResourceLoader
;
2447 * @param $modules Array/string with the module name(s)
2448 * @param $only String ResourceLoaderModule TYPE_ class constant
2449 * @param $useESI boolean
2450 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2451 * @return string html <script> and <style> tags
2453 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2454 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2456 if ( !count( $modules ) ) {
2460 if ( count( $modules ) > 1 ) {
2461 // Remove duplicate module requests
2462 $modules = array_unique( (array) $modules );
2463 // Sort module names so requests are more uniform
2466 if ( ResourceLoader
::inDebugMode() ) {
2467 // Recursively call us for every item
2469 foreach ( $modules as $name ) {
2470 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2476 // Create keyed-by-group list of module objects from modules list
2478 $resourceLoader = $this->getResourceLoader();
2479 foreach ( (array) $modules as $name ) {
2480 $module = $resourceLoader->getModule( $name );
2481 # Check that we're allowed to include this module on this page
2483 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2484 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2485 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2486 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2492 $group = $module->getGroup();
2493 if ( !isset( $groups[$group] ) ) {
2494 $groups[$group] = array();
2496 $groups[$group][$name] = $module;
2500 foreach ( $groups as $group => $modules ) {
2501 // Special handling for user-specific groups
2503 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2504 $user = $this->getUser()->getName();
2507 // Create a fake request based on the one we are about to make so modules return
2508 // correct timestamp and emptiness data
2509 $query = ResourceLoader
::makeLoaderQuery(
2510 array(), // modules; not determined yet
2511 $this->getLanguage()->getCode(),
2512 $this->getSkin()->getSkinName(),
2514 null, // version; not determined yet
2515 ResourceLoader
::inDebugMode(),
2516 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2517 $this->isPrintable(),
2518 $this->getRequest()->getBool( 'handheld' ),
2521 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2522 // Drop modules that know they're empty
2523 foreach ( $modules as $key => $module ) {
2524 if ( $module->isKnownEmpty( $context ) ) {
2525 unset( $modules[$key] );
2528 // If there are no modules left, skip this group
2529 if ( $modules === array() ) {
2533 // Support inlining of private modules if configured as such
2534 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2535 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2536 $links .= Html
::inlineStyle(
2537 $resourceLoader->makeModuleResponse( $context, $modules )
2540 $links .= Html
::inlineScript(
2541 ResourceLoader
::makeLoaderConditionalScript(
2542 $resourceLoader->makeModuleResponse( $context, $modules )
2549 // Special handling for the user group; because users might change their stuff
2550 // on-wiki like user pages, or user preferences; we need to find the highest
2551 // timestamp of these user-changable modules so we can ensure cache misses on change
2552 // This should NOT be done for the site group (bug 27564) because anons get that too
2553 // and we shouldn't be putting timestamps in Squid-cached HTML
2555 if ( $group === 'user' ) {
2556 // Get the maximum timestamp
2558 foreach ( $modules as $module ) {
2559 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2561 // Add a version parameter so cache will break when things change
2562 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2565 $url = ResourceLoader
::makeLoaderURL(
2566 array_keys( $modules ),
2567 $this->getLanguage()->getCode(),
2568 $this->getSkin()->getSkinName(),
2571 ResourceLoader
::inDebugMode(),
2572 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2573 $this->isPrintable(),
2574 $this->getRequest()->getBool( 'handheld' ),
2577 if ( $useESI && $wgResourceLoaderUseESI ) {
2578 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2579 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2580 $link = Html
::inlineStyle( $esi );
2582 $link = Html
::inlineScript( $esi );
2585 // Automatically select style/script elements
2586 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2587 $link = Html
::linkedStyle( $url );
2589 $link = Html
::linkedScript( $url );
2593 if( $group == 'noscript' ){
2594 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2596 $links .= $link . "\n";
2603 * JS stuff to put in the <head>. This is the startup module, config
2604 * vars and modules marked with position 'top'
2606 * @return String: HTML fragment
2608 function getHeadScripts() {
2609 // Startup - this will immediately load jquery and mediawiki modules
2610 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2612 // Load config before anything else
2613 $scripts .= Html
::inlineScript(
2614 ResourceLoader
::makeLoaderConditionalScript(
2615 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2619 // Script and Messages "only" requests marked for top inclusion
2620 // Messages should go first
2621 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2622 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2624 // Modules requests - let the client calculate dependencies and batch requests as it likes
2625 // Only load modules that have marked themselves for loading at the top
2626 $modules = $this->getModules( true, 'top' );
2628 $scripts .= Html
::inlineScript(
2629 ResourceLoader
::makeLoaderConditionalScript(
2630 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2639 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2640 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2644 function getBottomScripts() {
2645 global $wgUseSiteJs, $wgAllowUserJs;
2647 // Script and Messages "only" requests marked for bottom inclusion
2648 // Messages should go first
2649 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2650 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2652 // Modules requests - let the client calculate dependencies and batch requests as it likes
2653 // Only load modules that have marked themselves for loading at the bottom
2654 $modules = $this->getModules( true, 'bottom' );
2656 $scripts .= Html
::inlineScript(
2657 ResourceLoader
::makeLoaderConditionalScript(
2658 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2664 $scripts .= "\n" . $this->mScripts
;
2666 $userScripts = array( 'user.options', 'user.tokens' );
2668 // Add site JS if enabled
2669 if ( $wgUseSiteJs ) {
2670 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2671 if( $this->getUser()->isLoggedIn() ){
2672 $userScripts[] = 'user.groups';
2676 // Add user JS if enabled
2677 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2678 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2679 # XXX: additional security check/prompt?
2680 // We're on a preview of a JS subpage
2681 // Exclude this page from the user module in case it's in there (bug 26283)
2682 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2683 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2685 // Load the previewed JS
2686 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2688 // Include the user module normally
2689 // We can't do $userScripts[] = 'user'; because the user module would end up
2690 // being wrapped in a closure, so load it raw like 'site'
2691 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2694 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2700 * Add one or more variables to be set in mw.config in JavaScript.
2702 * @param $key {String|Array} Key or array of key/value pars.
2703 * @param $value {Mixed} Value of the configuration variable.
2705 public function addJsConfigVars( $keys, $value ) {
2706 if ( is_array( $keys ) ) {
2707 foreach ( $keys as $key => $value ) {
2708 $this->mJsConfigVars
[$key] = $value;
2713 $this->mJsConfigVars
[$keys] = $value;
2718 * Get an array containing the variables to be set in mw.config in JavaScript.
2720 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2721 * - in other words, page-independent/site-wide variables (without state).
2722 * You will only be adding bloat to the html page and causing page caches to
2723 * have to be purged on configuration changes.
2726 protected function getJSVars() {
2727 global $wgUseAjax, $wgEnableMWSuggest;
2729 $title = $this->getTitle();
2730 $ns = $title->getNamespace();
2731 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2732 if ( $ns == NS_SPECIAL
) {
2733 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2735 $canonicalName = false; # bug 21115
2738 $lang = $title->getPageLanguage();
2740 // Pre-process information
2741 $separatorTransTable = $lang->separatorTransformTable();
2742 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2743 $compactSeparatorTransTable = array(
2744 implode( "\t", array_keys( $separatorTransTable ) ),
2745 implode( "\t", $separatorTransTable ),
2747 $digitTransTable = $lang->digitTransformTable();
2748 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2749 $compactDigitTransTable = array(
2750 implode( "\t", array_keys( $digitTransTable ) ),
2751 implode( "\t", $digitTransTable ),
2755 'wgCanonicalNamespace' => $nsname,
2756 'wgCanonicalSpecialPageName' => $canonicalName,
2757 'wgNamespaceNumber' => $title->getNamespace(),
2758 'wgPageName' => $title->getPrefixedDBKey(),
2759 'wgTitle' => $title->getText(),
2760 'wgCurRevisionId' => $title->getLatestRevID(),
2761 'wgArticleId' => $title->getArticleId(),
2762 'wgIsArticle' => $this->isArticle(),
2763 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2764 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2765 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2766 'wgCategories' => $this->getCategories(),
2767 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2768 'wgPageContentLanguage' => $lang->getCode(),
2769 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2770 'wgDigitTransformTable' => $compactDigitTransTable,
2772 if ( $lang->hasVariants() ) {
2773 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2775 foreach ( $title->getRestrictionTypes() as $type ) {
2776 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2778 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2779 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2781 if ( $title->isMainPage() ) {
2782 $vars['wgIsMainPage'] = true;
2785 // Allow extensions to add their custom variables to the mw.config map.
2786 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2787 // page-dependant but site-wide (without state).
2788 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2789 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2791 // Merge in variables from addJsConfigVars last
2792 return array_merge( $vars, $this->mJsConfigVars
);
2796 * To make it harder for someone to slip a user a fake
2797 * user-JavaScript or user-CSS preview, a random token
2798 * is associated with the login session. If it's not
2799 * passed back with the preview request, we won't render
2804 public function userCanPreview() {
2805 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2806 ||
!$this->getRequest()->wasPosted()
2807 ||
!$this->getUser()->matchEditToken(
2808 $this->getRequest()->getVal( 'wpEditToken' ) )
2812 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2816 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2820 * @param $unused Unused
2821 * @param $addContentType bool
2823 * @return string HTML tag links to be put in the header.
2825 public function getHeadLinks( $unused = null, $addContentType = false ) {
2826 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2827 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2828 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2829 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2830 $wgRightsPage, $wgRightsUrl;
2834 if ( $addContentType ) {
2836 # More succinct than <meta http-equiv=Content-Type>, has the
2838 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2840 $tags[] = Html
::element( 'meta', array(
2841 'http-equiv' => 'Content-Type',
2842 'content' => "$wgMimeType; charset=UTF-8"
2844 $tags[] = Html
::element( 'meta', array( // bug 15835
2845 'http-equiv' => 'Content-Style-Type',
2846 'content' => 'text/css'
2851 $tags[] = Html
::element( 'meta', array(
2852 'name' => 'generator',
2853 'content' => "MediaWiki $wgVersion",
2856 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2857 if( $p !== 'index,follow' ) {
2858 // http://www.robotstxt.org/wc/meta-user.html
2859 // Only show if it's different from the default robots policy
2860 $tags[] = Html
::element( 'meta', array(
2866 if ( count( $this->mKeywords
) > 0 ) {
2868 "/<.*?" . ">/" => '',
2871 $tags[] = Html
::element( 'meta', array(
2872 'name' => 'keywords',
2873 'content' => preg_replace(
2874 array_keys( $strip ),
2875 array_values( $strip ),
2876 implode( ',', $this->mKeywords
)
2881 foreach ( $this->mMetatags
as $tag ) {
2882 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2884 $tag[0] = substr( $tag[0], 5 );
2888 $tags[] = Html
::element( 'meta',
2891 'content' => $tag[1]
2896 foreach ( $this->mLinktags
as $tag ) {
2897 $tags[] = Html
::element( 'link', $tag );
2900 # Universal edit button
2901 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
2902 $user = $this->getUser();
2903 if ( $this->getTitle()->quickUserCan( 'edit', $user )
2904 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
2905 // Original UniversalEditButton
2906 $msg = $this->msg( 'edit' )->text();
2907 $tags[] = Html
::element( 'link', array(
2908 'rel' => 'alternate',
2909 'type' => 'application/x-wiki',
2911 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2913 // Alternate edit link
2914 $tags[] = Html
::element( 'link', array(
2917 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2922 # Generally the order of the favicon and apple-touch-icon links
2923 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2924 # uses whichever one appears later in the HTML source. Make sure
2925 # apple-touch-icon is specified first to avoid this.
2926 if ( $wgAppleTouchIcon !== false ) {
2927 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2930 if ( $wgFavicon !== false ) {
2931 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2934 # OpenSearch description link
2935 $tags[] = Html
::element( 'link', array(
2937 'type' => 'application/opensearchdescription+xml',
2938 'href' => wfScript( 'opensearch_desc' ),
2939 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
2942 if ( $wgEnableAPI ) {
2943 # Real Simple Discovery link, provides auto-discovery information
2944 # for the MediaWiki API (and potentially additional custom API
2945 # support such as WordPress or Twitter-compatible APIs for a
2946 # blogging extension, etc)
2947 $tags[] = Html
::element( 'link', array(
2949 'type' => 'application/rsd+xml',
2950 // Output a protocol-relative URL here if $wgServer is protocol-relative
2951 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2952 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
2958 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
2959 $lang = $this->getTitle()->getPageLanguage();
2960 if ( $lang->hasVariants() ) {
2962 $urlvar = $lang->getURLVariant();
2965 $variants = $lang->getVariants();
2966 foreach ( $variants as $_v ) {
2967 $tags[] = Html
::element( 'link', array(
2968 'rel' => 'alternate',
2970 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2974 $tags[] = Html
::element( 'link', array(
2975 'rel' => 'canonical',
2976 'href' => $this->getTitle()->getCanonicalUrl()
2984 if ( $wgRightsPage ) {
2985 $copy = Title
::newFromText( $wgRightsPage );
2988 $copyright = $copy->getLocalURL();
2992 if ( !$copyright && $wgRightsUrl ) {
2993 $copyright = $wgRightsUrl;
2997 $tags[] = Html
::element( 'link', array(
2998 'rel' => 'copyright',
2999 'href' => $copyright )
3005 foreach( $this->getSyndicationLinks() as $format => $link ) {
3006 # Use the page name for the title. In principle, this could
3007 # lead to issues with having the same name for different feeds
3008 # corresponding to the same page, but we can't avoid that at
3011 $tags[] = $this->feedLink(
3014 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3015 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3019 # Recent changes feed should appear on every page (except recentchanges,
3020 # that would be redundant). Put it after the per-page feed to avoid
3021 # changing existing behavior. It's still available, probably via a
3022 # menu in your browser. Some sites might have a different feed they'd
3023 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3024 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3025 # If so, use it instead.
3026 if ( $wgOverrideSiteFeed ) {
3027 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3028 // Note, this->feedLink escapes the url.
3029 $tags[] = $this->feedLink(
3032 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3035 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3036 foreach ( $wgAdvertisedFeedTypes as $format ) {
3037 $tags[] = $this->feedLink(
3039 $this->getTitle()->getLocalURL( "feed={$format}" ),
3040 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3045 return implode( "\n", $tags );
3049 * Generate a <link rel/> for a feed.
3051 * @param $type String: feed type
3052 * @param $url String: URL to the feed
3053 * @param $text String: value of the "title" attribute
3054 * @return String: HTML fragment
3056 private function feedLink( $type, $url, $text ) {
3057 return Html
::element( 'link', array(
3058 'rel' => 'alternate',
3059 'type' => "application/$type+xml",
3066 * Add a local or specified stylesheet, with the given media options.
3067 * Meant primarily for internal use...
3069 * @param $style String: URL to the file
3070 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3071 * @param $condition String: for IE conditional comments, specifying an IE version
3072 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3074 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3076 // Even though we expect the media type to be lowercase, but here we
3077 // force it to lowercase to be safe.
3079 $options['media'] = $media;
3082 $options['condition'] = $condition;
3085 $options['dir'] = $dir;
3087 $this->styles
[$style] = $options;
3091 * Adds inline CSS styles
3092 * @param $style_css Mixed: inline CSS
3093 * @param $flip String: Set to 'flip' to flip the CSS if needed
3095 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3096 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3097 # If wanted, and the interface is right-to-left, flip the CSS
3098 $style_css = CSSJanus
::transform( $style_css, true, false );
3100 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3104 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3105 * These will be applied to various media & IE conditionals.
3109 public function buildCssLinks() {
3110 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3112 $this->getSkin()->setupSkinUserCss( $this );
3114 // Add ResourceLoader styles
3115 // Split the styles into four groups
3116 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3117 $otherTags = ''; // Tags to append after the normal <link> tags
3118 $resourceLoader = $this->getResourceLoader();
3120 $moduleStyles = $this->getModuleStyles();
3122 // Per-site custom styles
3123 if ( $wgUseSiteCss ) {
3124 $moduleStyles[] = 'site';
3125 $moduleStyles[] = 'noscript';
3126 if( $this->getUser()->isLoggedIn() ){
3127 $moduleStyles[] = 'user.groups';
3131 // Per-user custom styles
3132 if ( $wgAllowUserCss ) {
3133 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3134 // We're on a preview of a CSS subpage
3135 // Exclude this page from the user module in case it's in there (bug 26283)
3136 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3137 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3139 // Load the previewed CSS
3140 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3142 // Load the user styles normally
3143 $moduleStyles[] = 'user';
3147 // Per-user preference styles
3148 if ( $wgAllowUserCssPrefs ) {
3149 $moduleStyles[] = 'user.options';
3152 foreach ( $moduleStyles as $name ) {
3153 $module = $resourceLoader->getModule( $name );
3157 $group = $module->getGroup();
3158 // Modules in groups named "other" or anything different than "user", "site" or "private"
3159 // will be placed in the "other" group
3160 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3163 // We want site, private and user styles to override dynamically added styles from modules, but we want
3164 // dynamically added styles to override statically added styles from other modules. So the order
3165 // has to be other, dynamic, site, private, user
3166 // Add statically added styles for other modules
3167 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3168 // Add normal styles added through addStyle()/addInlineStyle() here
3169 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3170 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3171 // We use a <meta> tag with a made-up name for this because that's valid HTML
3172 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3174 // Add site, private and user styles
3175 // 'private' at present only contains user.options, so put that before 'user'
3176 // Any future private modules will likely have a similar user-specific character
3177 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3178 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3179 ResourceLoaderModule
::TYPE_STYLES
3183 // Add stuff in $otherTags (previewed user CSS if applicable)
3191 public function buildCssLinksArray() {
3194 // Add any extension CSS
3195 foreach ( $this->mExtStyles
as $url ) {
3196 $this->addStyle( $url );
3198 $this->mExtStyles
= array();
3200 foreach( $this->styles
as $file => $options ) {
3201 $link = $this->styleLink( $file, $options );
3203 $links[$file] = $link;
3210 * Generate \<link\> tags for stylesheets
3212 * @param $style String: URL to the file
3213 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3215 * @return String: HTML fragment
3217 protected function styleLink( $style, $options ) {
3218 if( isset( $options['dir'] ) ) {
3219 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3224 if( isset( $options['media'] ) ) {
3225 $media = self
::transformCssMedia( $options['media'] );
3226 if( is_null( $media ) ) {
3233 if( substr( $style, 0, 1 ) == '/' ||
3234 substr( $style, 0, 5 ) == 'http:' ||
3235 substr( $style, 0, 6 ) == 'https:' ) {
3238 global $wgStylePath, $wgStyleVersion;
3239 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3242 $link = Html
::linkedStyle( $url, $media );
3244 if( isset( $options['condition'] ) ) {
3245 $condition = htmlspecialchars( $options['condition'] );
3246 $link = "<!--[if $condition]>$link<![endif]-->";
3252 * Transform "media" attribute based on request parameters
3254 * @param $media String: current value of the "media" attribute
3255 * @return String: modified value of the "media" attribute
3257 public static function transformCssMedia( $media ) {
3258 global $wgRequest, $wgHandheldForIPhone;
3260 // Switch in on-screen display for media testing
3262 'printable' => 'print',
3263 'handheld' => 'handheld',
3265 foreach( $switches as $switch => $targetMedia ) {
3266 if( $wgRequest->getBool( $switch ) ) {
3267 if( $media == $targetMedia ) {
3269 } elseif( $media == 'screen' ) {
3275 // Expand longer media queries as iPhone doesn't grok 'handheld'
3276 if( $wgHandheldForIPhone ) {
3277 $mediaAliases = array(
3278 'screen' => 'screen and (min-device-width: 481px)',
3279 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3282 if( isset( $mediaAliases[$media] ) ) {
3283 $media = $mediaAliases[$media];
3291 * Add a wikitext-formatted message to the output.
3292 * This is equivalent to:
3294 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3296 public function addWikiMsg( /*...*/ ) {
3297 $args = func_get_args();
3298 $name = array_shift( $args );
3299 $this->addWikiMsgArray( $name, $args );
3303 * Add a wikitext-formatted message to the output.
3304 * Like addWikiMsg() except the parameters are taken as an array
3305 * instead of a variable argument list.
3307 * @param $name string
3308 * @param $args array
3310 public function addWikiMsgArray( $name, $args ) {
3311 $this->addWikiText( $this->msg( $name, $args )->plain() );
3315 * This function takes a number of message/argument specifications, wraps them in
3316 * some overall structure, and then parses the result and adds it to the output.
3318 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3319 * on. The subsequent arguments may either be strings, in which case they are the
3320 * message names, or arrays, in which case the first element is the message name,
3321 * and subsequent elements are the parameters to that message.
3323 * The special named parameter 'options' in a message specification array is passed
3324 * through to the $options parameter of wfMsgExt().
3326 * Don't use this for messages that are not in users interface language.
3330 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3334 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3336 * The newline after opening div is needed in some wikitext. See bug 19226.
3338 * @param $wrap string
3340 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3341 $msgSpecs = func_get_args();
3342 array_shift( $msgSpecs );
3343 $msgSpecs = array_values( $msgSpecs );
3345 foreach ( $msgSpecs as $n => $spec ) {
3347 if ( is_array( $spec ) ) {
3349 $name = array_shift( $args );
3350 if ( isset( $args['options'] ) ) {
3351 $options = $args['options'];
3352 unset( $args['options'] );
3358 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3360 $this->addWikiText( $s );
3364 * Include jQuery core. Use this to avoid loading it multiple times
3365 * before we get a usable script loader.
3367 * @param $modules Array: list of jQuery modules which should be loaded
3368 * @return Array: the list of modules which were not loaded.
3370 * @deprecated since 1.17
3372 public function includeJQuery( $modules = array() ) {