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 Ashar Voultoiz
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.
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;
128 /** @todo FIXME: Is this still used ?*/
129 var $mInlineMsg = array();
131 var $mTemplateIds = array();
132 var $mImageTimeKeys = array();
134 var $mRedirectCode = '';
136 var $mFeedLinksAppendQuery = null;
138 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
139 # @see ResourceLoaderModule::$origin
140 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
141 protected $mAllowedModules = array(
142 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
146 * @EasterEgg I just love the name for this self documenting variable.
149 var $mDoNothing = false;
152 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
154 /// lazy initialised, use parserOptions()
155 protected $mParserOptions = null;
158 * Handles the atom / rss links.
159 * We probably only support atom in 2011.
160 * Looks like a private variable.
161 * @see $wgAdvertisedFeedTypes
163 var $mFeedLinks = array();
165 // Gwicke work on squid caching? Roughly from 2003.
166 var $mEnableClientCache = true;
169 * Flag if output should only contain the body of the article.
172 var $mArticleBodyOnly = false;
174 var $mNewSectionLink = false;
175 var $mHideNewSectionLink = false;
178 * Comes from the parser. This was probably made to load CSS/JS only
179 * if we had <gallery>. Used directly in CategoryPage.php
180 * Looks like resource loader can replace this.
182 var $mNoGallery = false;
184 // should be private.
185 var $mPageTitleActionText = '';
186 var $mParseWarnings = array();
188 // Cache stuff. Looks like mEnableClientCache
189 var $mSquidMaxage = 0;
192 var $mPreventClickjacking = true;
194 /// should be private. To include the variable {{REVISIONID}}
195 var $mRevisionId = null;
197 var $mFileVersion = null;
200 * An array of stylesheet filenames (relative from skins path), with options
201 * for CSS media, IE conditions, and RTL/LTR direction.
202 * For internal use; add settings in the skin via $this->addStyle()
204 * Style again! This seems like a code duplication since we already have
205 * mStyles. This is what makes OpenSource amazing.
207 var $styles = array();
210 * Whether jQuery is already handled.
212 protected $mJQueryDone = false;
214 private $mIndexPolicy = 'index';
215 private $mFollowPolicy = 'follow';
216 private $mVaryHeader = array(
217 'Accept-Encoding' => array( 'list-contains=gzip' ),
222 * Constructor for OutputPage. This should not be called directly.
223 * Instead a new RequestContext should be created and it will implicitly create
224 * a OutputPage tied to that context.
226 function __construct( RequestContext
$context = null ) {
227 if ( $context === null ) {
228 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
229 wfDeprecated( __METHOD__
);
231 $this->setContext( $context );
236 * Redirect to $url rather than displaying the normal page
238 * @param $url String: URL
239 * @param $responsecode String: HTTP status code
241 public function redirect( $url, $responsecode = '302' ) {
242 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
243 $this->mRedirect
= str_replace( "\n", '', $url );
244 $this->mRedirectCode
= $responsecode;
248 * Get the URL to redirect to, or an empty string if not redirect URL set
252 public function getRedirect() {
253 return $this->mRedirect
;
257 * Set the HTTP status code to send with the output.
259 * @param $statusCode Integer
261 public function setStatusCode( $statusCode ) {
262 $this->mStatusCode
= $statusCode;
266 * Add a new <meta> tag
267 * To add an http-equiv meta tag, precede the name with "http:"
269 * @param $name String tag name
270 * @param $val String tag value
272 function addMeta( $name, $val ) {
273 array_push( $this->mMetatags
, array( $name, $val ) );
277 * Add a keyword or a list of keywords in the page header
279 * @param $text String or array of strings
281 function addKeyword( $text ) {
282 if( is_array( $text ) ) {
283 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
285 array_push( $this->mKeywords
, $text );
290 * Add a new \<link\> tag to the page header
292 * @param $linkarr Array: associative array of attributes.
294 function addLink( $linkarr ) {
295 array_push( $this->mLinktags
, $linkarr );
299 * Add a new \<link\> with "rel" attribute set to "meta"
301 * @param $linkarr Array: associative array mapping attribute names to their
302 * values, both keys and values will be escaped, and the
303 * "rel" attribute will be automatically added
305 function addMetadataLink( $linkarr ) {
306 $linkarr['rel'] = $this->getMetadataAttribute();
307 $this->addLink( $linkarr );
311 * Get the value of the "rel" attribute for metadata links
315 public function getMetadataAttribute() {
316 # note: buggy CC software only reads first "meta" link
317 static $haveMeta = false;
319 return 'alternate meta';
327 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
329 * @param $script String: raw HTML
331 function addScript( $script ) {
332 $this->mScripts
.= $script . "\n";
336 * Register and add a stylesheet from an extension directory.
338 * @param $url String path to sheet. Provide either a full url (beginning
339 * with 'http', etc) or a relative path from the document root
340 * (beginning with '/'). Otherwise it behaves identically to
341 * addStyle() and draws from the /skins folder.
343 public function addExtensionStyle( $url ) {
344 array_push( $this->mExtStyles
, $url );
348 * Get all styles added by extensions
352 function getExtStyle() {
353 return $this->mExtStyles
;
357 * Add a JavaScript file out of skins/common, or a given relative path.
359 * @param $file String: filename in skins/common or complete on-server path
361 * @param $version String: style version of the file. Defaults to $wgStyleVersion
363 public function addScriptFile( $file, $version = null ) {
364 global $wgStylePath, $wgStyleVersion;
365 // See if $file parameter is an absolute URL or begins with a slash
366 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
369 $path = "{$wgStylePath}/common/{$file}";
371 if ( is_null( $version ) )
372 $version = $wgStyleVersion;
373 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
377 * Add a self-contained script tag with the given contents
379 * @param $script String: JavaScript text, no <script> tags
381 public function addInlineScript( $script ) {
382 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
386 * Get all registered JS and CSS tags for the header.
390 function getScript() {
391 return $this->mScripts
. $this->getHeadItems();
395 * Filter an array of modules to remove insufficiently trustworthy members, and modules
396 * which are no longer registered (eg a page is cached before an extension is disabled)
397 * @param $modules Array
398 * @param $position String if not null, only return modules with this position
399 * @param $type string
402 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
403 $resourceLoader = $this->getResourceLoader();
404 $filteredModules = array();
405 foreach( $modules as $val ){
406 $module = $resourceLoader->getModule( $val );
407 if( $module instanceof ResourceLoaderModule
408 && $module->getOrigin() <= $this->getAllowedModules( $type )
409 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
411 $filteredModules[] = $val;
414 return $filteredModules;
418 * Get the list of modules to include on this page
420 * @param $filter Bool whether to filter out insufficiently trustworthy modules
421 * @param $position String if not null, only return modules with this position
422 * @param $param string
423 * @return Array of module names
425 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
426 $modules = array_values( array_unique( $this->$param ) );
428 ?
$this->filterModules( $modules, $position )
433 * Add one or more modules recognized by the resource loader. Modules added
434 * through this function will be loaded by the resource loader when the
437 * @param $modules Mixed: module name (string) or array of module names
439 public function addModules( $modules ) {
440 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
444 * Get the list of module JS to include on this page
449 * @return array of module names
451 public function getModuleScripts( $filter = false, $position = null ) {
452 return $this->getModules( $filter, $position, 'mModuleScripts' );
456 * Add only JS of one or more modules recognized by the resource loader. Module
457 * scripts added through this function will be loaded by the resource loader when
460 * @param $modules Mixed: module name (string) or array of module names
462 public function addModuleScripts( $modules ) {
463 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
467 * Get the list of module CSS to include on this page
472 * @return Array of module names
474 public function getModuleStyles( $filter = false, $position = null ) {
475 return $this->getModules( $filter, $position, 'mModuleStyles' );
479 * Add only CSS of one or more modules recognized by the resource loader. Module
480 * styles added through this function will be loaded by the resource loader when
483 * @param $modules Mixed: module name (string) or array of module names
485 public function addModuleStyles( $modules ) {
486 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
490 * Get the list of module messages to include on this page
495 * @return Array of module names
497 public function getModuleMessages( $filter = false, $position = null ) {
498 return $this->getModules( $filter, $position, 'mModuleMessages' );
502 * Add only messages of one or more modules recognized by the resource loader.
503 * Module messages added through this function will be loaded by the resource
504 * loader when the page loads.
506 * @param $modules Mixed: module name (string) or array of module names
508 public function addModuleMessages( $modules ) {
509 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
513 * Get an array of head items
517 function getHeadItemsArray() {
518 return $this->mHeadItems
;
522 * Get all header items in a string
526 function getHeadItems() {
528 foreach ( $this->mHeadItems
as $item ) {
535 * Add or replace an header item to the output
537 * @param $name String: item name
538 * @param $value String: raw HTML
540 public function addHeadItem( $name, $value ) {
541 $this->mHeadItems
[$name] = $value;
545 * Check if the header item $name is already set
547 * @param $name String: item name
550 public function hasHeadItem( $name ) {
551 return isset( $this->mHeadItems
[$name] );
555 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
557 * @param $tag String: value of "ETag" header
559 function setETag( $tag ) {
564 * Set whether the output should only contain the body of the article,
565 * without any skin, sidebar, etc.
566 * Used e.g. when calling with "action=render".
568 * @param $only Boolean: whether to output only the body of the article
570 public function setArticleBodyOnly( $only ) {
571 $this->mArticleBodyOnly
= $only;
575 * Return whether the output will contain only the body of the article
579 public function getArticleBodyOnly() {
580 return $this->mArticleBodyOnly
;
584 * checkLastModified tells the client to use the client-cached page if
585 * possible. If sucessful, the OutputPage is disabled so that
586 * any future call to OutputPage->output() have no effect.
588 * Side effect: sets mLastModified for Last-Modified header
590 * @param $timestamp string
592 * @return Boolean: true iff cache-ok headers was sent.
594 public function checkLastModified( $timestamp ) {
595 global $wgCachePages, $wgCacheEpoch;
597 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
598 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
601 if( !$wgCachePages ) {
602 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
605 if( $this->getUser()->getOption( 'nocache' ) ) {
606 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
610 $timestamp = wfTimestamp( TS_MW
, $timestamp );
611 $modifiedTimes = array(
612 'page' => $timestamp,
613 'user' => $this->getUser()->getTouched(),
614 'epoch' => $wgCacheEpoch
616 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
618 $maxModified = max( $modifiedTimes );
619 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
621 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
622 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
628 foreach ( $modifiedTimes as $name => $value ) {
629 if ( $info !== '' ) {
632 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
635 # IE sends sizes after the date like this:
636 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
637 # this breaks strtotime().
638 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
640 wfSuppressWarnings(); // E_STRICT system time bitching
641 $clientHeaderTime = strtotime( $clientHeader );
643 if ( !$clientHeaderTime ) {
644 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
647 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
649 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
650 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
651 wfDebug( __METHOD__
. ": effective Last-Modified: " .
652 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
653 if( $clientHeaderTime < $maxModified ) {
654 wfDebug( __METHOD__
. ": STALE, $info\n", false );
659 # Give a 304 response code and disable body output
660 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
661 ini_set( 'zlib.output_compression', 0 );
662 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
663 $this->sendCacheControl();
666 // Don't output a compressed blob when using ob_gzhandler;
667 // it's technically against HTTP spec and seems to confuse
668 // Firefox when the response gets split over two packets.
669 wfClearOutputBuffers();
675 * Override the last modified timestamp
677 * @param $timestamp String: new timestamp, in a format readable by
680 public function setLastModified( $timestamp ) {
681 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
685 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
687 * @param $policy String: the literal string to output as the contents of
688 * the meta tag. Will be parsed according to the spec and output in
692 public function setRobotPolicy( $policy ) {
693 $policy = Article
::formatRobotPolicy( $policy );
695 if( isset( $policy['index'] ) ) {
696 $this->setIndexPolicy( $policy['index'] );
698 if( isset( $policy['follow'] ) ) {
699 $this->setFollowPolicy( $policy['follow'] );
704 * Set the index policy for the page, but leave the follow policy un-
707 * @param $policy string Either 'index' or 'noindex'.
710 public function setIndexPolicy( $policy ) {
711 $policy = trim( $policy );
712 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
713 $this->mIndexPolicy
= $policy;
718 * Set the follow policy for the page, but leave the index policy un-
721 * @param $policy String: either 'follow' or 'nofollow'.
724 public function setFollowPolicy( $policy ) {
725 $policy = trim( $policy );
726 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
727 $this->mFollowPolicy
= $policy;
732 * Set the new value of the "action text", this will be added to the
733 * "HTML title", separated from it with " - ".
735 * @param $text String: new value of the "action text"
737 public function setPageTitleActionText( $text ) {
738 $this->mPageTitleActionText
= $text;
742 * Get the value of the "action text"
746 public function getPageTitleActionText() {
747 if ( isset( $this->mPageTitleActionText
) ) {
748 return $this->mPageTitleActionText
;
753 * "HTML title" means the contents of <title>.
754 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
756 * @param $name string
758 public function setHTMLTitle( $name ) {
759 $this->mHTMLtitle
= $name;
763 * Return the "HTML title", i.e. the content of the <title> tag.
767 public function getHTMLTitle() {
768 return $this->mHTMLtitle
;
772 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
773 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
774 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
775 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
777 * @param $name string
779 public function setPageTitle( $name ) {
780 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
781 # but leave "<i>foobar</i>" alone
782 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
783 $this->mPagetitle
= $nameWithTags;
785 # change "<i>foo&bar</i>" to "foo&bar"
786 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
790 * Return the "page title", i.e. the content of the \<h1\> tag.
794 public function getPageTitle() {
795 return $this->mPagetitle
;
799 * Set the Title object to use
801 * @param $t Title object
803 public function setTitle( Title
$t ) {
804 $this->getContext()->setTitle( $t );
809 * Replace the subtile with $str
811 * @param $str String: new value of the subtitle
813 public function setSubtitle( $str ) {
814 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
818 * Add $str to the subtitle
820 * @param $str String to add to the subtitle
822 public function appendSubtitle( $str ) {
823 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
831 public function getSubtitle() {
832 return $this->mSubtitle
;
836 * Set the page as printable, i.e. it'll be displayed with with all
837 * print styles included
839 public function setPrintable() {
840 $this->mPrintable
= true;
844 * Return whether the page is "printable"
848 public function isPrintable() {
849 return $this->mPrintable
;
853 * Disable output completely, i.e. calling output() will have no effect
855 public function disable() {
856 $this->mDoNothing
= true;
860 * Return whether the output will be completely disabled
864 public function isDisabled() {
865 return $this->mDoNothing
;
869 * Show an "add new section" link?
873 public function showNewSectionLink() {
874 return $this->mNewSectionLink
;
878 * Forcibly hide the new section link?
882 public function forceHideNewSectionLink() {
883 return $this->mHideNewSectionLink
;
887 * Add or remove feed links in the page header
888 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
889 * for the new version
892 * @param $show Boolean: true: add default feeds, false: remove all feeds
894 public function setSyndicated( $show = true ) {
896 $this->setFeedAppendQuery( false );
898 $this->mFeedLinks
= array();
903 * Add default feeds to the page header
904 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
905 * for the new version
908 * @param $val String: query to append to feed links or false to output
911 public function setFeedAppendQuery( $val ) {
912 global $wgAdvertisedFeedTypes;
914 $this->mFeedLinks
= array();
916 foreach ( $wgAdvertisedFeedTypes as $type ) {
917 $query = "feed=$type";
918 if ( is_string( $val ) ) {
919 $query .= '&' . $val;
921 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
926 * Add a feed link to the page header
928 * @param $format String: feed type, should be a key of $wgFeedClasses
929 * @param $href String: URL
931 public function addFeedLink( $format, $href ) {
932 global $wgAdvertisedFeedTypes;
934 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
935 $this->mFeedLinks
[$format] = $href;
940 * Should we output feed links for this page?
943 public function isSyndicated() {
944 return count( $this->mFeedLinks
) > 0;
948 * Return URLs for each supported syndication format for this page.
949 * @return array associating format keys with URLs
951 public function getSyndicationLinks() {
952 return $this->mFeedLinks
;
956 * Will currently always return null
960 public function getFeedAppendQuery() {
961 return $this->mFeedLinksAppendQuery
;
965 * Set whether the displayed content is related to the source of the
966 * corresponding article on the wiki
967 * Setting true will cause the change "article related" toggle to true
971 public function setArticleFlag( $v ) {
972 $this->mIsarticle
= $v;
974 $this->mIsArticleRelated
= $v;
979 * Return whether the content displayed page is related to the source of
980 * the corresponding article on the wiki
984 public function isArticle() {
985 return $this->mIsarticle
;
989 * Set whether this page is related an article on the wiki
990 * Setting false will cause the change of "article flag" toggle to false
994 public function setArticleRelated( $v ) {
995 $this->mIsArticleRelated
= $v;
997 $this->mIsarticle
= false;
1002 * Return whether this page is related an article on the wiki
1006 public function isArticleRelated() {
1007 return $this->mIsArticleRelated
;
1011 * Add new language links
1013 * @param $newLinkArray Associative array mapping language code to the page
1016 public function addLanguageLinks( $newLinkArray ) {
1017 $this->mLanguageLinks +
= $newLinkArray;
1021 * Reset the language links and add new language links
1023 * @param $newLinkArray Associative array mapping language code to the page
1026 public function setLanguageLinks( $newLinkArray ) {
1027 $this->mLanguageLinks
= $newLinkArray;
1031 * Get the list of language links
1033 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1035 public function getLanguageLinks() {
1036 return $this->mLanguageLinks
;
1040 * Add an array of categories, with names in the keys
1042 * @param $categories Array mapping category name => sort key
1044 public function addCategoryLinks( $categories ) {
1047 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1051 # Add the links to a LinkBatch
1052 $arr = array( NS_CATEGORY
=> $categories );
1053 $lb = new LinkBatch
;
1054 $lb->setArray( $arr );
1056 # Fetch existence plus the hiddencat property
1057 $dbr = wfGetDB( DB_SLAVE
);
1058 $res = $dbr->select( array( 'page', 'page_props' ),
1059 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1060 $lb->constructSet( 'page', $dbr ),
1063 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1066 # Add the results to the link cache
1067 $lb->addResultToCache( LinkCache
::singleton(), $res );
1069 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1070 $categories = array_combine(
1071 array_keys( $categories ),
1072 array_fill( 0, count( $categories ), 'normal' )
1075 # Mark hidden categories
1076 foreach ( $res as $row ) {
1077 if ( isset( $row->pp_value
) ) {
1078 $categories[$row->page_title
] = 'hidden';
1082 # Add the remaining categories to the skin
1083 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1084 foreach ( $categories as $category => $type ) {
1085 $origcategory = $category;
1086 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1087 $wgContLang->findVariantLink( $category, $title, true );
1088 if ( $category != $origcategory ) {
1089 if ( array_key_exists( $category, $categories ) ) {
1093 $text = $wgContLang->convertHtml( $title->getText() );
1094 $this->mCategories
[] = $title->getText();
1095 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1101 * Reset the category links (but not the category list) and add $categories
1103 * @param $categories Array mapping category name => sort key
1105 public function setCategoryLinks( $categories ) {
1106 $this->mCategoryLinks
= array();
1107 $this->addCategoryLinks( $categories );
1111 * Get the list of category links, in a 2-D array with the following format:
1112 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1113 * hidden categories) and $link a HTML fragment with a link to the category
1118 public function getCategoryLinks() {
1119 return $this->mCategoryLinks
;
1123 * Get the list of category names this page belongs to
1125 * @return Array of strings
1127 public function getCategories() {
1128 return $this->mCategories
;
1132 * Do not allow scripts which can be modified by wiki users to load on this page;
1133 * only allow scripts bundled with, or generated by, the software.
1135 public function disallowUserJs() {
1136 $this->reduceAllowedModules(
1137 ResourceLoaderModule
::TYPE_SCRIPTS
,
1138 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1143 * Return whether user JavaScript is allowed for this page
1144 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1145 * trustworthiness is identified and enforced automagically.
1148 public function isUserJsAllowed() {
1149 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1153 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1154 * @see ResourceLoaderModule::$origin
1155 * @param $type String ResourceLoaderModule TYPE_ constant
1156 * @return Int ResourceLoaderModule ORIGIN_ class constant
1158 public function getAllowedModules( $type ){
1159 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1160 return min( array_values( $this->mAllowedModules
) );
1162 return isset( $this->mAllowedModules
[$type] )
1163 ?
$this->mAllowedModules
[$type]
1164 : ResourceLoaderModule
::ORIGIN_ALL
;
1169 * Set the highest level of CSS/JS untrustworthiness allowed
1170 * @param $type String ResourceLoaderModule TYPE_ constant
1171 * @param $level Int ResourceLoaderModule class constant
1173 public function setAllowedModules( $type, $level ){
1174 $this->mAllowedModules
[$type] = $level;
1178 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1179 * @param $type String
1180 * @param $level Int ResourceLoaderModule class constant
1182 public function reduceAllowedModules( $type, $level ){
1183 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1187 * Prepend $text to the body HTML
1189 * @param $text String: HTML
1191 public function prependHTML( $text ) {
1192 $this->mBodytext
= $text . $this->mBodytext
;
1196 * Append $text to the body HTML
1198 * @param $text String: HTML
1200 public function addHTML( $text ) {
1201 $this->mBodytext
.= $text;
1205 * Clear the body HTML
1207 public function clearHTML() {
1208 $this->mBodytext
= '';
1214 * @return String: HTML
1216 public function getHTML() {
1217 return $this->mBodytext
;
1221 * Add $text to the debug output
1223 * @param $text String: debug text
1225 public function debug( $text ) {
1226 $this->mDebugtext
.= $text;
1230 * Get/set the ParserOptions object to use for wikitext parsing
1232 * @param $options either the ParserOption to use or null to only get the
1233 * current ParserOption object
1234 * @return ParserOptions object
1236 public function parserOptions( $options = null ) {
1237 if ( !$this->mParserOptions
) {
1238 $this->mParserOptions
= new ParserOptions
;
1239 $this->mParserOptions
->setEditSection( false );
1241 return wfSetVar( $this->mParserOptions
, $options );
1245 * Set the revision ID which will be seen by the wiki text parser
1246 * for things such as embedded {{REVISIONID}} variable use.
1248 * @param $revid Mixed: an positive integer, or null
1249 * @return Mixed: previous value
1251 public function setRevisionId( $revid ) {
1252 $val = is_null( $revid ) ?
null : intval( $revid );
1253 return wfSetVar( $this->mRevisionId
, $val );
1257 * Get the displayed revision ID
1261 public function getRevisionId() {
1262 return $this->mRevisionId
;
1266 * Set the displayed file version
1268 * @param $file File|false
1269 * @return Mixed: previous value
1271 public function setFileVersion( $file ) {
1273 if ( $file instanceof File
&& $file->exists() ) {
1274 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1276 return wfSetVar( $this->mFileVersion
, $val, true );
1280 * Get the displayed file version
1282 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1284 public function getFileVersion() {
1285 return $this->mFileVersion
;
1289 * Get the templates used on this page
1291 * @return Array (namespace => dbKey => revId)
1294 public function getTemplateIds() {
1295 return $this->mTemplateIds
;
1299 * Get the files used on this page
1301 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1304 public function getImageTimeKeys() {
1305 return $this->mImageTimeKeys
;
1309 * Convert wikitext to HTML and add it to the buffer
1310 * Default assumes that the current page title will be used.
1312 * @param $text String
1313 * @param $linestart Boolean: is this the start of a line?
1315 public function addWikiText( $text, $linestart = true ) {
1316 $title = $this->getTitle(); // Work arround E_STRICT
1317 $this->addWikiTextTitle( $text, $title, $linestart );
1321 * Add wikitext with a custom Title object
1323 * @param $text String: wikitext
1324 * @param $title Title object
1325 * @param $linestart Boolean: is this the start of a line?
1327 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1328 $this->addWikiTextTitle( $text, $title, $linestart );
1332 * Add wikitext with a custom Title object and
1334 * @param $text String: wikitext
1335 * @param $title Title object
1336 * @param $linestart Boolean: is this the start of a line?
1338 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1339 $this->addWikiTextTitle( $text, $title, $linestart, true );
1343 * Add wikitext with tidy enabled
1345 * @param $text String: wikitext
1346 * @param $linestart Boolean: is this the start of a line?
1348 public function addWikiTextTidy( $text, $linestart = true ) {
1349 $title = $this->getTitle();
1350 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1354 * Add wikitext with a custom Title object
1356 * @param $text String: wikitext
1357 * @param $title Title object
1358 * @param $linestart Boolean: is this the start of a line?
1359 * @param $tidy Boolean: whether to use tidy
1361 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1364 wfProfileIn( __METHOD__
);
1366 wfIncrStats( 'pcache_not_possible' );
1368 $popts = $this->parserOptions();
1369 $oldTidy = $popts->setTidy( $tidy );
1371 $parserOutput = $wgParser->parse(
1372 $text, $title, $popts,
1373 $linestart, true, $this->mRevisionId
1376 $popts->setTidy( $oldTidy );
1378 $this->addParserOutput( $parserOutput );
1380 wfProfileOut( __METHOD__
);
1384 * Add a ParserOutput object, but without Html
1386 * @param $parserOutput ParserOutput object
1388 public function addParserOutputNoText( &$parserOutput ) {
1389 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1390 $this->addCategoryLinks( $parserOutput->getCategories() );
1391 $this->mNewSectionLink
= $parserOutput->getNewSection();
1392 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1394 $this->mParseWarnings
= $parserOutput->getWarnings();
1395 if ( !$parserOutput->isCacheable() ) {
1396 $this->enableClientCache( false );
1398 $this->mNoGallery
= $parserOutput->getNoGallery();
1399 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1400 $this->addModules( $parserOutput->getModules() );
1401 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1402 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1403 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1405 // Template versioning...
1406 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1407 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1408 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1410 $this->mTemplateIds
[$ns] = $dbks;
1413 // File versioning...
1414 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1415 $this->mImageTimeKeys
[$dbk] = $data;
1418 // Hooks registered in the object
1419 global $wgParserOutputHooks;
1420 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1421 list( $hookName, $data ) = $hookInfo;
1422 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1423 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1427 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1431 * Add a ParserOutput object
1433 * @param $parserOutput ParserOutput
1435 function addParserOutput( &$parserOutput ) {
1436 $this->addParserOutputNoText( $parserOutput );
1437 $text = $parserOutput->getText();
1438 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1439 $this->addHTML( $text );
1444 * Add the output of a QuickTemplate to the output buffer
1446 * @param $template QuickTemplate
1448 public function addTemplate( &$template ) {
1450 $template->execute();
1451 $this->addHTML( ob_get_contents() );
1456 * Parse wikitext and return the HTML.
1458 * @param $text String
1459 * @param $linestart Boolean: is this the start of a line?
1460 * @param $interface Boolean: use interface language ($wgLang instead of
1461 * $wgContLang) while parsing language sensitive magic
1462 * words like GRAMMAR and PLURAL. This also disables
1463 * LanguageConverter.
1464 * @param $language Language object: target language object, will override
1466 * @return String: HTML
1468 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1471 if( is_null( $this->getTitle() ) ) {
1472 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1475 $popts = $this->parserOptions();
1477 $popts->setInterfaceMessage( true );
1479 if ( $language !== null ) {
1480 $oldLang = $popts->setTargetLanguage( $language );
1483 $parserOutput = $wgParser->parse(
1484 $text, $this->getTitle(), $popts,
1485 $linestart, true, $this->mRevisionId
1489 $popts->setInterfaceMessage( false );
1491 if ( $language !== null ) {
1492 $popts->setTargetLanguage( $oldLang );
1495 return $parserOutput->getText();
1499 * Parse wikitext, strip paragraphs, and return the HTML.
1501 * @param $text String
1502 * @param $linestart Boolean: is this the start of a line?
1503 * @param $interface Boolean: use interface language ($wgLang instead of
1504 * $wgContLang) while parsing language sensitive magic
1505 * words like GRAMMAR and PLURAL
1506 * @return String: HTML
1508 public function parseInline( $text, $linestart = true, $interface = false ) {
1509 $parsed = $this->parse( $text, $linestart, $interface );
1512 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1520 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1522 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1524 public function setSquidMaxage( $maxage ) {
1525 $this->mSquidMaxage
= $maxage;
1529 * Use enableClientCache(false) to force it to send nocache headers
1531 * @param $state bool
1535 public function enableClientCache( $state ) {
1536 return wfSetVar( $this->mEnableClientCache
, $state );
1540 * Get the list of cookies that will influence on the cache
1544 function getCacheVaryCookies() {
1545 global $wgCookiePrefix, $wgCacheVaryCookies;
1547 if ( $cookies === null ) {
1548 $cookies = array_merge(
1550 "{$wgCookiePrefix}Token",
1551 "{$wgCookiePrefix}LoggedOut",
1556 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1562 * Return whether this page is not cacheable because "useskin" or "uselang"
1563 * URL parameters were passed.
1567 function uncacheableBecauseRequestVars() {
1568 $request = $this->getRequest();
1569 return $request->getText( 'useskin', false ) === false
1570 && $request->getText( 'uselang', false ) === false;
1574 * Check if the request has a cache-varying cookie header
1575 * If it does, it's very important that we don't allow public caching
1579 function haveCacheVaryCookies() {
1580 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1581 if ( $cookieHeader === false ) {
1584 $cvCookies = $this->getCacheVaryCookies();
1585 foreach ( $cvCookies as $cookieName ) {
1586 # Check for a simple string match, like the way squid does it
1587 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1588 wfDebug( __METHOD__
. ": found $cookieName\n" );
1592 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1597 * Add an HTTP header that will influence on the cache
1599 * @param $header String: header name
1600 * @param $option Array|null
1601 * @todo FIXME: Document the $option parameter; it appears to be for
1602 * X-Vary-Options but what format is acceptable?
1604 public function addVaryHeader( $header, $option = null ) {
1605 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1606 $this->mVaryHeader
[$header] = (array)$option;
1607 } elseif( is_array( $option ) ) {
1608 if( is_array( $this->mVaryHeader
[$header] ) ) {
1609 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1611 $this->mVaryHeader
[$header] = $option;
1614 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1618 * Get a complete X-Vary-Options header
1622 public function getXVO() {
1623 $cvCookies = $this->getCacheVaryCookies();
1625 $cookiesOption = array();
1626 foreach ( $cvCookies as $cookieName ) {
1627 $cookiesOption[] = 'string-contains=' . $cookieName;
1629 $this->addVaryHeader( 'Cookie', $cookiesOption );
1632 foreach( $this->mVaryHeader
as $header => $option ) {
1633 $newheader = $header;
1634 if( is_array( $option ) ) {
1635 $newheader .= ';' . implode( ';', $option );
1637 $headers[] = $newheader;
1639 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1645 * bug 21672: Add Accept-Language to Vary and XVO headers
1646 * if there's no 'variant' parameter existed in GET.
1649 * /w/index.php?title=Main_page should always be served; but
1650 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1652 function addAcceptLanguage() {
1654 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1655 $variants = $wgContLang->getVariants();
1656 $aloption = array();
1657 foreach ( $variants as $variant ) {
1658 if( $variant === $wgContLang->getCode() ) {
1661 $aloption[] = 'string-contains=' . $variant;
1663 // IE and some other browsers use another form of language code
1664 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1665 // We should handle these too.
1666 $ievariant = explode( '-', $variant );
1667 if ( count( $ievariant ) == 2 ) {
1668 $ievariant[1] = strtoupper( $ievariant[1] );
1669 $ievariant = implode( '-', $ievariant );
1670 $aloption[] = 'string-contains=' . $ievariant;
1674 $this->addVaryHeader( 'Accept-Language', $aloption );
1679 * Set a flag which will cause an X-Frame-Options header appropriate for
1680 * edit pages to be sent. The header value is controlled by
1681 * $wgEditPageFrameOptions.
1683 * This is the default for special pages. If you display a CSRF-protected
1684 * form on an ordinary view page, then you need to call this function.
1686 * @param $enable bool
1688 public function preventClickjacking( $enable = true ) {
1689 $this->mPreventClickjacking
= $enable;
1693 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1694 * This can be called from pages which do not contain any CSRF-protected
1697 public function allowClickjacking() {
1698 $this->mPreventClickjacking
= false;
1702 * Get the X-Frame-Options header value (without the name part), or false
1703 * if there isn't one. This is used by Skin to determine whether to enable
1704 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1708 public function getFrameOptions() {
1709 global $wgBreakFrames, $wgEditPageFrameOptions;
1710 if ( $wgBreakFrames ) {
1712 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1713 return $wgEditPageFrameOptions;
1718 * Send cache control HTTP headers
1720 public function sendCacheControl() {
1721 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1723 $response = $this->getRequest()->response();
1724 if ( $wgUseETag && $this->mETag
) {
1725 $response->header( "ETag: $this->mETag" );
1728 $this->addAcceptLanguage();
1730 # don't serve compressed data to clients who can't handle it
1731 # maintain different caches for logged-in users and non-logged in ones
1732 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1735 # Add an X-Vary-Options header for Squid with Wikimedia patches
1736 $response->header( $this->getXVO() );
1739 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1741 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1742 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1746 # We'll purge the proxy cache explicitly, but require end user agents
1747 # to revalidate against the proxy on each visit.
1748 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1749 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1750 # start with a shorter timeout for initial testing
1751 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1752 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1753 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1755 # We'll purge the proxy cache for anons explicitly, but require end user agents
1756 # to revalidate against the proxy on each visit.
1757 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1758 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1759 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1760 # start with a shorter timeout for initial testing
1761 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1762 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1765 # We do want clients to cache if they can, but they *must* check for updates
1766 # on revisiting the page.
1767 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1768 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1769 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1771 if($this->mLastModified
) {
1772 $response->header( "Last-Modified: {$this->mLastModified}" );
1775 wfDebug( __METHOD__
. ": no caching **\n", false );
1777 # In general, the absence of a last modified header should be enough to prevent
1778 # the client from using its cache. We send a few other things just to make sure.
1779 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1780 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1781 $response->header( 'Pragma: no-cache' );
1786 * Get the message associed with the HTTP response code $code
1788 * @param $code Integer: status code
1789 * @return String or null: message or null if $code is not in the list of
1792 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1794 public static function getStatusMessage( $code ) {
1795 wfDeprecated( __METHOD__
);
1796 return HttpStatus
::getMessage( $code );
1800 * Finally, all the text has been munged and accumulated into
1801 * the object, let's actually output it:
1803 public function output() {
1804 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1806 if( $this->mDoNothing
) {
1810 wfProfileIn( __METHOD__
);
1812 $response = $this->getRequest()->response();
1814 if ( $this->mRedirect
!= '' ) {
1815 # Standards require redirect URLs to be absolute
1816 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1817 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1818 if( !$wgDebugRedirects ) {
1819 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1820 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1822 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1824 $this->sendCacheControl();
1826 $response->header( "Content-Type: text/html; charset=utf-8" );
1827 if( $wgDebugRedirects ) {
1828 $url = htmlspecialchars( $this->mRedirect
);
1829 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1830 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1831 print "</body>\n</html>\n";
1833 $response->header( 'Location: ' . $this->mRedirect
);
1835 wfProfileOut( __METHOD__
);
1837 } elseif ( $this->mStatusCode
) {
1838 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1840 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1844 # Buffer output; final headers may depend on later processing
1847 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1848 $response->header( 'Content-language: ' . $wgLanguageCode );
1850 // Prevent framing, if requested
1851 $frameOptions = $this->getFrameOptions();
1852 if ( $frameOptions ) {
1853 $response->header( "X-Frame-Options: $frameOptions" );
1856 if ( $this->mArticleBodyOnly
) {
1857 $this->out( $this->mBodytext
);
1859 $this->addDefaultModules();
1861 $sk = $this->getSkin();
1863 // Hook that allows last minute changes to the output page, e.g.
1864 // adding of CSS or Javascript by extensions.
1865 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1867 wfProfileIn( 'Output-skin' );
1869 wfProfileOut( 'Output-skin' );
1872 $this->sendCacheControl();
1874 wfProfileOut( __METHOD__
);
1878 * Actually output something with print().
1880 * @param $ins String: the string to output
1882 public function out( $ins ) {
1887 * Produce a "user is blocked" page.
1888 * @deprecated since 1.18
1890 function blockedPage() {
1891 throw new UserBlockedError( $this->getUser()->mBlock
);
1895 * Output a standard error page
1897 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1898 * showErrorPage( 'titlemsg', $messageObject );
1900 * @param $title String: message key for page title
1901 * @param $msg Mixed: message key (string) for page text, or a Message object
1902 * @param $params Array: message parameters; ignored if $msg is a Message object
1904 public function showErrorPage( $title, $msg, $params = array() ) {
1905 if ( $this->getTitle() ) {
1906 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1908 $this->setPageTitle( wfMsg( $title ) );
1909 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1910 $this->setRobotPolicy( 'noindex,nofollow' );
1911 $this->setArticleRelated( false );
1912 $this->enableClientCache( false );
1913 $this->mRedirect
= '';
1914 $this->mBodytext
= '';
1916 if ( $msg instanceof Message
){
1917 $this->addHTML( $msg->parse() );
1919 $this->addWikiMsgArray( $msg, $params );
1922 $this->returnToMain();
1926 * Output a standard permission error page
1928 * @param $errors Array: error message keys
1929 * @param $action String: action that was denied or null if unknown
1931 public function showPermissionsErrorPage( $errors, $action = null ) {
1932 $this->mDebugtext
.= 'Original title: ' .
1933 $this->getTitle()->getPrefixedText() . "\n";
1934 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1935 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1936 $this->setRobotPolicy( 'noindex,nofollow' );
1937 $this->setArticleRelated( false );
1938 $this->enableClientCache( false );
1939 $this->mRedirect
= '';
1940 $this->mBodytext
= '';
1941 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1945 * Display an error page indicating that a given version of MediaWiki is
1946 * required to use it
1948 * @param $version Mixed: the version of MediaWiki needed to use the page
1950 public function versionRequired( $version ) {
1951 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1952 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1953 $this->setRobotPolicy( 'noindex,nofollow' );
1954 $this->setArticleRelated( false );
1955 $this->mBodytext
= '';
1957 $this->addWikiMsg( 'versionrequiredtext', $version );
1958 $this->returnToMain();
1962 * Display an error page noting that a given permission bit is required.
1963 * @deprecated since 1.18, just throw the exception directly
1964 * @param $permission String: key required
1966 public function permissionRequired( $permission ) {
1967 throw new PermissionsError( $permission );
1971 * Produce the stock "please login to use the wiki" page
1973 public function loginToUse() {
1974 if( $this->getUser()->isLoggedIn() ) {
1975 throw new PermissionsError( 'read' );
1978 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1979 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1980 $this->setRobotPolicy( 'noindex,nofollow' );
1981 $this->setArticleRelated( false );
1983 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1984 $loginLink = Linker
::linkKnown(
1986 wfMsgHtml( 'loginreqlink' ),
1988 array( 'returnto' => $this->getTitle()->getPrefixedText() )
1990 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
1991 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1993 # Don't return to the main page if the user can't read it
1994 # otherwise we'll end up in a pointless loop
1995 $mainPage = Title
::newMainPage();
1996 if( $mainPage->userCanRead() ) {
1997 $this->returnToMain( null, $mainPage );
2002 * Format a list of error messages
2004 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2005 * @param $action String: action that was denied or null if unknown
2006 * @return String: the wikitext error-messages, formatted into a list.
2008 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2009 if ( $action == null ) {
2010 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2012 $action_desc = wfMsgNoTrans( "action-$action" );
2013 $text = wfMsgNoTrans(
2014 'permissionserrorstext-withaction',
2020 if ( count( $errors ) > 1 ) {
2021 $text .= '<ul class="permissions-errors">' . "\n";
2023 foreach( $errors as $error ) {
2025 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2030 $text .= "<div class=\"permissions-errors\">\n" .
2031 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2039 * Display a page stating that the Wiki is in read-only mode,
2040 * and optionally show the source of the page that the user
2041 * was trying to edit. Should only be called (for this
2042 * purpose) after wfReadOnly() has returned true.
2044 * For historical reasons, this function is _also_ used to
2045 * show the error message when a user tries to edit a page
2046 * they are not allowed to edit. (Unless it's because they're
2047 * blocked, then we show blockedPage() instead.) In this
2048 * case, the second parameter should be set to true and a list
2049 * of reasons supplied as the third parameter.
2051 * @todo Needs to be split into multiple functions.
2053 * @param $source String: source code to show (or null).
2054 * @param $protected Boolean: is this a permissions error?
2055 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2056 * @param $action String: action that was denied or null if unknown
2058 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2059 global $wgEnableInterwikiTranscluding, $wgEnableInterwikiTemplatesTracking;
2061 $this->setRobotPolicy( 'noindex,nofollow' );
2062 $this->setArticleRelated( false );
2064 // If no reason is given, just supply a default "I can't let you do
2065 // that, Dave" message. Should only occur if called by legacy code.
2066 if ( $protected && empty( $reasons ) ) {
2067 $reasons[] = array( 'badaccess-group0' );
2070 if ( !empty( $reasons ) ) {
2071 // Permissions error
2073 $this->setPageTitle( wfMsg( 'viewsource' ) );
2075 wfMsg( 'viewsourcefor', Linker
::linkKnown( $this->getTitle() ) )
2078 $this->setPageTitle( wfMsg( 'badaccess' ) );
2080 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2082 // Wiki is read only
2083 throw new ReadOnlyError
;
2086 // Show source, if supplied
2087 if( is_string( $source ) ) {
2088 $this->addWikiMsg( 'viewsourcetext' );
2090 $pageLang = $this->getTitle()->getPageLanguage();
2092 'id' => 'wpTextbox1',
2093 'name' => 'wpTextbox1',
2094 'cols' => $this->getUser()->getOption( 'cols' ),
2095 'rows' => $this->getUser()->getOption( 'rows' ),
2096 'readonly' => 'readonly',
2097 'lang' => $pageLang->getCode(),
2098 'dir' => $pageLang->getDir(),
2100 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2102 // Show templates used by this article
2103 $article = new Article( $this->getTitle() );
2104 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2105 $this->addHTML( "<div class='templatesUsed'>
2109 if ( $wgEnableInterwikiTranscluding && $wgEnableInterwikiTemplatesTracking ) {
2110 $distantTemplates = Linker
::formatDistantTemplates( $article->getUsedDistantTemplates() );
2111 $this->addHTML( "<div class='distantTemplatesUsed'>
2118 # If the title doesn't exist, it's fairly pointless to print a return
2119 # link to it. After all, you just tried editing it and couldn't, so
2120 # what's there to do there?
2121 if( $this->getTitle()->exists() ) {
2122 $this->returnToMain( null, $this->getTitle() );
2127 * Turn off regular page output and return an error reponse
2128 * for when rate limiting has triggered.
2130 public function rateLimited() {
2131 throw new ThrottledError
;
2135 * Show a warning about slave lag
2137 * If the lag is higher than $wgSlaveLagCritical seconds,
2138 * then the warning is a bit more obvious. If the lag is
2139 * lower than $wgSlaveLagWarning, then no warning is shown.
2141 * @param $lag Integer: slave lag
2143 public function showLagWarning( $lag ) {
2144 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2145 if( $lag >= $wgSlaveLagWarning ) {
2146 $message = $lag < $wgSlaveLagCritical
2149 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2150 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2154 public function showFatalError( $message ) {
2155 $this->setPageTitle( wfMsg( 'internalerror' ) );
2156 $this->setRobotPolicy( 'noindex,nofollow' );
2157 $this->setArticleRelated( false );
2158 $this->enableClientCache( false );
2159 $this->mRedirect
= '';
2160 $this->mBodytext
= $message;
2163 public function showUnexpectedValueError( $name, $val ) {
2164 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2167 public function showFileCopyError( $old, $new ) {
2168 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2171 public function showFileRenameError( $old, $new ) {
2172 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2175 public function showFileDeleteError( $name ) {
2176 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2179 public function showFileNotFoundError( $name ) {
2180 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2184 * Add a "return to" link pointing to a specified title
2186 * @param $title Title to link
2187 * @param $query String query string
2188 * @param $text String text of the link (input is not escaped)
2190 public function addReturnTo( $title, $query = array(), $text = null ) {
2191 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2194 Linker
::link( $title, $text, array(), $query )
2196 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2200 * Add a "return to" link pointing to a specified title,
2201 * or the title indicated in the request, or else the main page
2203 * @param $unused No longer used
2204 * @param $returnto Title or String to return to
2205 * @param $returntoquery String: query string for the return to link
2207 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2208 if ( $returnto == null ) {
2209 $returnto = $this->getRequest()->getText( 'returnto' );
2212 if ( $returntoquery == null ) {
2213 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2216 if ( $returnto === '' ) {
2217 $returnto = Title
::newMainPage();
2220 if ( is_object( $returnto ) ) {
2221 $titleObj = $returnto;
2223 $titleObj = Title
::newFromText( $returnto );
2225 if ( !is_object( $titleObj ) ) {
2226 $titleObj = Title
::newMainPage();
2229 $this->addReturnTo( $titleObj, $returntoquery );
2233 * @param $sk Skin The given Skin
2234 * @param $includeStyle Boolean: unused
2235 * @return String: The doctype, opening <html>, and head element.
2237 public function headElement( Skin
$sk, $includeStyle = true ) {
2238 global $wgContLang, $wgUseTrackbacks;
2239 $userdir = $this->getLang()->getDir();
2240 $sitedir = $wgContLang->getDir();
2242 if ( $sk->commonPrintStylesheet() ) {
2243 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2246 $ret = Html
::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2248 if ( $this->getHTMLTitle() == '' ) {
2249 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2252 $openHead = Html
::openElement( 'head' );
2254 # Don't bother with the newline if $head == ''
2255 $ret .= "$openHead\n";
2258 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2260 $ret .= implode( "\n", array(
2261 $this->getHeadLinks( null, true ),
2262 $this->buildCssLinks(),
2263 $this->getHeadScripts(),
2264 $this->getHeadItems()
2267 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2268 $ret .= $this->getTitle()->trackbackRDF();
2271 $closeHead = Html
::closeElement( 'head' );
2273 $ret .= "$closeHead\n";
2276 $bodyAttrs = array();
2278 # Classes for LTR/RTL directionality support
2279 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2281 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2282 # A <body> class is probably not the best way to do this . . .
2283 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2285 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2286 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2288 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2289 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2291 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2297 * Add the default ResourceLoader modules to this object
2299 private function addDefaultModules() {
2300 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2302 // Add base resources
2303 $this->addModules( array(
2306 'mediawiki.page.startup',
2307 'mediawiki.page.ready',
2309 if ( $wgIncludeLegacyJavaScript ){
2310 $this->addModules( 'mediawiki.legacy.wikibits' );
2313 // Add various resources if required
2315 $this->addModules( 'mediawiki.legacy.ajax' );
2317 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2319 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2320 $this->addModules( 'mediawiki.action.watch.ajax' );
2323 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2324 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2328 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2329 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2332 # Crazy edit-on-double-click stuff
2333 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2334 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2339 * Get a ResourceLoader object associated with this OutputPage
2341 * @return ResourceLoader
2343 public function getResourceLoader() {
2344 if ( is_null( $this->mResourceLoader
) ) {
2345 $this->mResourceLoader
= new ResourceLoader();
2347 return $this->mResourceLoader
;
2352 * @param $modules Array/string with the module name(s)
2353 * @param $only String ResourceLoaderModule TYPE_ class constant
2354 * @param $useESI boolean
2355 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2356 * @return string html <script> and <style> tags
2358 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2359 global $wgLoadScript, $wgResourceLoaderUseESI,
2360 $wgResourceLoaderInlinePrivateModules;
2362 'lang' => $this->getContext()->getLang()->getCode(),
2363 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2364 'skin' => $this->getSkin()->getSkinName(),
2366 if ( $only !== ResourceLoaderModule
::TYPE_COMBINED
) {
2367 $baseQuery['only'] = $only;
2369 // Propagate printable and handheld parameters if present
2370 if ( $this->isPrintable() ) {
2371 $baseQuery['printable'] = 1;
2373 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2374 $baseQuery['handheld'] = 1;
2377 if ( !count( $modules ) ) {
2381 if ( count( $modules ) > 1 ) {
2382 // Remove duplicate module requests
2383 $modules = array_unique( (array) $modules );
2384 // Sort module names so requests are more uniform
2387 if ( ResourceLoader
::inDebugMode() ) {
2388 // Recursively call us for every item
2390 foreach ( $modules as $name ) {
2391 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2397 // Create keyed-by-group list of module objects from modules list
2399 $resourceLoader = $this->getResourceLoader();
2400 foreach ( (array) $modules as $name ) {
2401 $module = $resourceLoader->getModule( $name );
2402 # Check that we're allowed to include this module on this page
2403 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2404 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2405 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2406 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2412 $group = $module->getGroup();
2413 if ( !isset( $groups[$group] ) ) {
2414 $groups[$group] = array();
2416 $groups[$group][$name] = $module;
2420 foreach ( $groups as $group => $modules ) {
2421 $query = $baseQuery;
2422 // Special handling for user-specific groups
2423 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2424 $query['user'] = $this->getUser()->getName();
2427 // Create a fake request based on the one we are about to make so modules return
2428 // correct timestamp and emptiness data
2429 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2430 // Drop modules that know they're empty
2431 foreach ( $modules as $key => $module ) {
2432 if ( $module->isKnownEmpty( $context ) ) {
2433 unset( $modules[$key] );
2436 // If there are no modules left, skip this group
2437 if ( $modules === array() ) {
2441 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $modules ) );
2443 // Support inlining of private modules if configured as such
2444 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2445 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2446 $links .= Html
::inlineStyle(
2447 $resourceLoader->makeModuleResponse( $context, $modules )
2450 $links .= Html
::inlineScript(
2451 ResourceLoader
::makeLoaderConditionalScript(
2452 $resourceLoader->makeModuleResponse( $context, $modules )
2459 // Special handling for the user group; because users might change their stuff
2460 // on-wiki like user pages, or user preferences; we need to find the highest
2461 // timestamp of these user-changable modules so we can ensure cache misses on change
2462 // This should NOT be done for the site group (bug 27564) because anons get that too
2463 // and we shouldn't be putting timestamps in Squid-cached HTML
2464 if ( $group === 'user' ) {
2465 // Get the maximum timestamp
2467 foreach ( $modules as $module ) {
2468 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2470 // Add a version parameter so cache will break when things change
2471 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2473 // Make queries uniform in order
2476 $url = wfAppendQuery( $wgLoadScript, $query );
2477 // Prevent the IE6 extension check from being triggered (bug 28840)
2478 // by appending a character that's invalid in Windows extensions ('*')
2480 if ( $useESI && $wgResourceLoaderUseESI ) {
2481 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2482 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2483 $link = Html
::inlineStyle( $esi );
2485 $link = Html
::inlineScript( $esi );
2488 // Automatically select style/script elements
2489 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2490 $link = Html
::linkedStyle( $url );
2492 $link = Html
::linkedScript( $url );
2496 if( $group == 'noscript' ){
2497 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2499 $links .= $link . "\n";
2506 * JS stuff to put in the <head>. This is the startup module, config
2507 * vars and modules marked with position 'top'
2509 * @return String: HTML fragment
2511 function getHeadScripts() {
2512 // Startup - this will immediately load jquery and mediawiki modules
2513 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2515 // Load config before anything else
2516 $scripts .= Html
::inlineScript(
2517 ResourceLoader
::makeLoaderConditionalScript(
2518 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2522 // Script and Messages "only" requests marked for top inclusion
2523 // Messages should go first
2524 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2525 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2527 // Modules requests - let the client calculate dependencies and batch requests as it likes
2528 // Only load modules that have marked themselves for loading at the top
2529 $modules = $this->getModules( true, 'top' );
2531 $scripts .= Html
::inlineScript(
2532 ResourceLoader
::makeLoaderConditionalScript(
2533 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2542 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2543 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2547 function getBottomScripts() {
2548 global $wgUseSiteJs, $wgAllowUserJs;
2550 // Script and Messages "only" requests marked for bottom inclusion
2551 // Messages should go first
2552 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2553 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2555 // Modules requests - let the client calculate dependencies and batch requests as it likes
2556 // Only load modules that have marked themselves for loading at the bottom
2557 $modules = $this->getModules( true, 'bottom' );
2559 $scripts .= Html
::inlineScript(
2560 ResourceLoader
::makeLoaderConditionalScript(
2561 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2567 $scripts .= "\n" . $this->mScripts
;
2569 $userScripts = array( 'user.options', 'user.tokens' );
2571 // Add site JS if enabled
2572 if ( $wgUseSiteJs ) {
2573 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2574 if( $this->getUser()->isLoggedIn() ){
2575 $userScripts[] = 'user.groups';
2579 // Add user JS if enabled
2580 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2581 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2582 # XXX: additional security check/prompt?
2583 // We're on a preview of a JS subpage
2584 // Exclude this page from the user module in case it's in there (bug 26283)
2585 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2586 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2588 // Load the previewed JS
2589 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2591 // Include the user module normally
2592 // We can't do $userScripts[] = 'user'; because the user module would end up
2593 // being wrapped in a closure, so load it raw like 'site'
2594 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2597 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2603 * Get an array containing global JS variables
2605 * Do not add things here which can be evaluated in
2606 * ResourceLoaderStartupScript - in other words, without state.
2607 * You will only be adding bloat to the page and causing page caches to
2608 * have to be purged on configuration changes.
2610 protected function getJSVars() {
2611 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2613 $title = $this->getTitle();
2614 $ns = $title->getNamespace();
2615 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2616 if ( $ns == NS_SPECIAL
) {
2617 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2619 $canonicalName = false; # bug 21115
2623 'wgCanonicalNamespace' => $nsname,
2624 'wgCanonicalSpecialPageName' => $canonicalName,
2625 'wgNamespaceNumber' => $title->getNamespace(),
2626 'wgPageName' => $title->getPrefixedDBKey(),
2627 'wgTitle' => $title->getText(),
2628 'wgCurRevisionId' => $title->getLatestRevID(),
2629 'wgArticleId' => $title->getArticleId(),
2630 'wgIsArticle' => $this->isArticle(),
2631 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2632 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2633 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2634 'wgCategories' => $this->getCategories(),
2635 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2637 if ( $wgContLang->hasVariants() ) {
2638 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2640 foreach ( $title->getRestrictionTypes() as $type ) {
2641 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2643 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2644 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2646 if ( $title->isMainPage() ) {
2647 $vars['wgIsMainPage'] = true;
2650 // Allow extensions to add their custom variables to the global JS variables
2651 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, &$this ) );
2657 * To make it harder for someone to slip a user a fake
2658 * user-JavaScript or user-CSS preview, a random token
2659 * is associated with the login session. If it's not
2660 * passed back with the preview request, we won't render
2665 public function userCanPreview() {
2666 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2667 ||
!$this->getRequest()->wasPosted()
2668 ||
!$this->getUser()->matchEditToken(
2669 $this->getRequest()->getVal( 'wpEditToken' ) )
2673 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2677 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2681 * @param $unused Unused
2682 * @param $addContentType bool
2684 * @return string HTML tag links to be put in the header.
2686 public function getHeadLinks( $unused = null, $addContentType = false ) {
2687 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2688 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2689 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2690 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2691 $wgRightsPage, $wgRightsUrl;
2695 if ( $addContentType ) {
2697 # More succinct than <meta http-equiv=Content-Type>, has the
2699 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2701 $tags[] = Html
::element( 'meta', array(
2702 'http-equiv' => 'Content-Type',
2703 'content' => "$wgMimeType; charset=UTF-8"
2705 $tags[] = Html
::element( 'meta', array( // bug 15835
2706 'http-equiv' => 'Content-Style-Type',
2707 'content' => 'text/css'
2712 $tags[] = Html
::element( 'meta', array(
2713 'name' => 'generator',
2714 'content' => "MediaWiki $wgVersion",
2717 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2718 if( $p !== 'index,follow' ) {
2719 // http://www.robotstxt.org/wc/meta-user.html
2720 // Only show if it's different from the default robots policy
2721 $tags[] = Html
::element( 'meta', array(
2727 if ( count( $this->mKeywords
) > 0 ) {
2729 "/<.*?" . ">/" => '',
2732 $tags[] = Html
::element( 'meta', array(
2733 'name' => 'keywords',
2734 'content' => preg_replace(
2735 array_keys( $strip ),
2736 array_values( $strip ),
2737 implode( ',', $this->mKeywords
)
2742 foreach ( $this->mMetatags
as $tag ) {
2743 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2745 $tag[0] = substr( $tag[0], 5 );
2749 $tags[] = Html
::element( 'meta',
2752 'content' => $tag[1]
2757 foreach ( $this->mLinktags
as $tag ) {
2758 $tags[] = Html
::element( 'link', $tag );
2761 # Universal edit button
2762 if ( $wgUniversalEditButton ) {
2763 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2764 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2765 // Original UniversalEditButton
2766 $msg = wfMsg( 'edit' );
2767 $tags[] = Html
::element( 'link', array(
2768 'rel' => 'alternate',
2769 'type' => 'application/x-wiki',
2771 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2773 // Alternate edit link
2774 $tags[] = Html
::element( 'link', array(
2777 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2782 # Generally the order of the favicon and apple-touch-icon links
2783 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2784 # uses whichever one appears later in the HTML source. Make sure
2785 # apple-touch-icon is specified first to avoid this.
2786 if ( $wgAppleTouchIcon !== false ) {
2787 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2790 if ( $wgFavicon !== false ) {
2791 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2794 # OpenSearch description link
2795 $tags[] = Html
::element( 'link', array(
2797 'type' => 'application/opensearchdescription+xml',
2798 'href' => wfScript( 'opensearch_desc' ),
2799 'title' => wfMsgForContent( 'opensearch-desc' ),
2802 if ( $wgEnableAPI ) {
2803 # Real Simple Discovery link, provides auto-discovery information
2804 # for the MediaWiki API (and potentially additional custom API
2805 # support such as WordPress or Twitter-compatible APIs for a
2806 # blogging extension, etc)
2807 $tags[] = Html
::element( 'link', array(
2809 'type' => 'application/rsd+xml',
2810 // Output a protocol-relative URL here if $wgServer is protocol-relative
2811 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2812 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
2817 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2818 && $wgContLang->hasVariants() ) {
2820 $urlvar = $wgContLang->getURLVariant();
2823 $variants = $wgContLang->getVariants();
2824 foreach ( $variants as $_v ) {
2825 $tags[] = Html
::element( 'link', array(
2826 'rel' => 'alternate',
2828 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2832 $tags[] = Html
::element( 'link', array(
2833 'rel' => 'canonical',
2834 'href' => $this->getTitle()->getCanonicalUrl()
2841 if ( $wgRightsPage ) {
2842 $copy = Title
::newFromText( $wgRightsPage );
2845 $copyright = $copy->getLocalURL();
2849 if ( !$copyright && $wgRightsUrl ) {
2850 $copyright = $wgRightsUrl;
2854 $tags[] = Html
::element( 'link', array(
2855 'rel' => 'copyright',
2856 'href' => $copyright )
2862 foreach( $this->getSyndicationLinks() as $format => $link ) {
2863 # Use the page name for the title. In principle, this could
2864 # lead to issues with having the same name for different feeds
2865 # corresponding to the same page, but we can't avoid that at
2868 $tags[] = $this->feedLink(
2871 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2872 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2876 # Recent changes feed should appear on every page (except recentchanges,
2877 # that would be redundant). Put it after the per-page feed to avoid
2878 # changing existing behavior. It's still available, probably via a
2879 # menu in your browser. Some sites might have a different feed they'd
2880 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2881 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2882 # If so, use it instead.
2884 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2886 if ( $wgOverrideSiteFeed ) {
2887 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2888 // Note, this->feedLink escapes the url.
2889 $tags[] = $this->feedLink(
2892 wfMsg( "site-{$type}-feed", $wgSitename )
2895 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2896 foreach ( $wgAdvertisedFeedTypes as $format ) {
2897 $tags[] = $this->feedLink(
2899 $rctitle->getLocalURL( "feed={$format}" ),
2900 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2905 return implode( "\n", $tags );
2909 * Generate a <link rel/> for a feed.
2911 * @param $type String: feed type
2912 * @param $url String: URL to the feed
2913 * @param $text String: value of the "title" attribute
2914 * @return String: HTML fragment
2916 private function feedLink( $type, $url, $text ) {
2917 return Html
::element( 'link', array(
2918 'rel' => 'alternate',
2919 'type' => "application/$type+xml",
2926 * Add a local or specified stylesheet, with the given media options.
2927 * Meant primarily for internal use...
2929 * @param $style String: URL to the file
2930 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2931 * @param $condition String: for IE conditional comments, specifying an IE version
2932 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2934 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2936 // Even though we expect the media type to be lowercase, but here we
2937 // force it to lowercase to be safe.
2939 $options['media'] = $media;
2942 $options['condition'] = $condition;
2945 $options['dir'] = $dir;
2947 $this->styles
[$style] = $options;
2951 * Adds inline CSS styles
2952 * @param $style_css Mixed: inline CSS
2953 * @param $flip Boolean: Whether to flip the CSS if needed
2955 public function addInlineStyle( $style_css, $flip = false ) {
2956 if( $flip && $this->getLang()->isRTL() ) {
2957 # If wanted, and the interface is right-to-left, flip the CSS
2958 $style_css = CSSJanus
::transform( $style_css, true, false );
2960 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2964 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2965 * These will be applied to various media & IE conditionals.
2969 public function buildCssLinks() {
2970 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
2972 $this->getSkin()->setupSkinUserCss( $this );
2974 // Add ResourceLoader styles
2975 // Split the styles into four groups
2976 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2977 $otherTags = ''; // Tags to append after the normal <link> tags
2978 $resourceLoader = $this->getResourceLoader();
2980 $moduleStyles = $this->getModuleStyles();
2982 // Per-site custom styles
2983 if ( $wgUseSiteCss ) {
2984 $moduleStyles[] = 'site';
2985 $moduleStyles[] = 'noscript';
2986 if( $this->getUser()->isLoggedIn() ){
2987 $moduleStyles[] = 'user.groups';
2991 // Per-user custom styles
2992 if ( $wgAllowUserCss ) {
2993 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
2994 // We're on a preview of a CSS subpage
2995 // Exclude this page from the user module in case it's in there (bug 26283)
2996 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
2997 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2999 // Load the previewed CSS
3000 $otherTags .= Html
::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3002 // Load the user styles normally
3003 $moduleStyles[] = 'user';
3007 // Per-user preference styles
3008 if ( $wgAllowUserCssPrefs ) {
3009 $moduleStyles[] = 'user.options';
3012 foreach ( $moduleStyles as $name ) {
3013 $group = $resourceLoader->getModule( $name )->getGroup();
3014 // Modules in groups named "other" or anything different than "user", "site" or "private"
3015 // will be placed in the "other" group
3016 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3019 // We want site, private and user styles to override dynamically added styles from modules, but we want
3020 // dynamically added styles to override statically added styles from other modules. So the order
3021 // has to be other, dynamic, site, private, user
3022 // Add statically added styles for other modules
3023 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3024 // Add normal styles added through addStyle()/addInlineStyle() here
3025 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3026 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3027 // We use a <meta> tag with a made-up name for this because that's valid HTML
3028 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3030 // Add site, private and user styles
3031 // 'private' at present only contains user.options, so put that before 'user'
3032 // Any future private modules will likely have a similar user-specific character
3033 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3034 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3035 ResourceLoaderModule
::TYPE_STYLES
3039 // Add stuff in $otherTags (previewed user CSS if applicable)
3044 public function buildCssLinksArray() {
3047 // Add any extension CSS
3048 foreach ( $this->mExtStyles
as $url ) {
3049 $this->addStyle( $url );
3051 $this->mExtStyles
= array();
3053 foreach( $this->styles
as $file => $options ) {
3054 $link = $this->styleLink( $file, $options );
3056 $links[$file] = $link;
3063 * Generate \<link\> tags for stylesheets
3065 * @param $style String: URL to the file
3066 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3068 * @return String: HTML fragment
3070 protected function styleLink( $style, $options ) {
3071 if( isset( $options['dir'] ) ) {
3072 if( $this->getLang()->getDir() != $options['dir'] ) {
3077 if( isset( $options['media'] ) ) {
3078 $media = self
::transformCssMedia( $options['media'] );
3079 if( is_null( $media ) ) {
3086 if( substr( $style, 0, 1 ) == '/' ||
3087 substr( $style, 0, 5 ) == 'http:' ||
3088 substr( $style, 0, 6 ) == 'https:' ) {
3091 global $wgStylePath, $wgStyleVersion;
3092 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3095 $link = Html
::linkedStyle( $url, $media );
3097 if( isset( $options['condition'] ) ) {
3098 $condition = htmlspecialchars( $options['condition'] );
3099 $link = "<!--[if $condition]>$link<![endif]-->";
3105 * Transform "media" attribute based on request parameters
3107 * @param $media String: current value of the "media" attribute
3108 * @return String: modified value of the "media" attribute
3110 public static function transformCssMedia( $media ) {
3111 global $wgRequest, $wgHandheldForIPhone;
3113 // Switch in on-screen display for media testing
3115 'printable' => 'print',
3116 'handheld' => 'handheld',
3118 foreach( $switches as $switch => $targetMedia ) {
3119 if( $wgRequest->getBool( $switch ) ) {
3120 if( $media == $targetMedia ) {
3122 } elseif( $media == 'screen' ) {
3128 // Expand longer media queries as iPhone doesn't grok 'handheld'
3129 if( $wgHandheldForIPhone ) {
3130 $mediaAliases = array(
3131 'screen' => 'screen and (min-device-width: 481px)',
3132 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3135 if( isset( $mediaAliases[$media] ) ) {
3136 $media = $mediaAliases[$media];
3144 * Add a wikitext-formatted message to the output.
3145 * This is equivalent to:
3147 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3149 public function addWikiMsg( /*...*/ ) {
3150 $args = func_get_args();
3151 $name = array_shift( $args );
3152 $this->addWikiMsgArray( $name, $args );
3156 * Add a wikitext-formatted message to the output.
3157 * Like addWikiMsg() except the parameters are taken as an array
3158 * instead of a variable argument list.
3160 * $options is passed through to wfMsgExt(), see that function for details.
3162 * @param $name string
3163 * @param $args array
3164 * @param $options array
3166 public function addWikiMsgArray( $name, $args, $options = array() ) {
3167 $options[] = 'parse';
3168 $text = wfMsgExt( $name, $options, $args );
3169 $this->addHTML( $text );
3173 * This function takes a number of message/argument specifications, wraps them in
3174 * some overall structure, and then parses the result and adds it to the output.
3176 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3177 * on. The subsequent arguments may either be strings, in which case they are the
3178 * message names, or arrays, in which case the first element is the message name,
3179 * and subsequent elements are the parameters to that message.
3181 * The special named parameter 'options' in a message specification array is passed
3182 * through to the $options parameter of wfMsgExt().
3184 * Don't use this for messages that are not in users interface language.
3188 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3192 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3194 * The newline after opening div is needed in some wikitext. See bug 19226.
3196 * @param $wrap string
3198 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3199 $msgSpecs = func_get_args();
3200 array_shift( $msgSpecs );
3201 $msgSpecs = array_values( $msgSpecs );
3203 foreach ( $msgSpecs as $n => $spec ) {
3205 if ( is_array( $spec ) ) {
3207 $name = array_shift( $args );
3208 if ( isset( $args['options'] ) ) {
3209 $options = $args['options'];
3210 unset( $args['options'] );
3216 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3218 $this->addWikiText( $s );
3222 * Include jQuery core. Use this to avoid loading it multiple times
3223 * before we get a usable script loader.
3225 * @param $modules Array: list of jQuery modules which should be loaded
3226 * @return Array: the list of modules which were not loaded.
3228 * @deprecated since 1.17
3230 public function includeJQuery( $modules = array() ) {