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 * Another class (fixme) 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 = true;
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
56 var $mPrintable = false;
59 * Should be private. We have set/get/append methods.
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved into its own class.
73 var $mLastModified = '';
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cached version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its locally cached ETAG value.
82 * To get more information, you will have to look at HTTP1/1 protocols which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
87 var $mCategoryLinks = array();
88 var $mCategories = array();
90 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
91 var $mLanguageLinks = array();
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
102 * Inline CSS styles. Use addInlineStyle() sparsingly
104 var $mInlineStyles = '';
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
113 var $mPageLinkTitle = '';
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
118 // Next variables probably comes from the resource loader @todo FIXME
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
122 /** @fixme is this still used ?*/
123 var $mInlineMsg = array();
125 var $mTemplateIds = array();
126 var $mImageTimeKeys = array();
128 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
129 # @see ResourceLoaderModule::$origin
130 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
131 protected $mAllowedModules = array(
132 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
136 * @EasterEgg I just love the name for this self documenting variable.
139 var $mDoNothing = false;
142 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
145 * Should be private. Has get/set methods properly documented.
146 * Stores "article flag" toggle.
148 var $mIsArticleRelated = true;
150 /// lazy initialised, use parserOptions()
151 protected $mParserOptions = null;
154 * Handles the atom / rss links.
155 * We probably only support atom in 2011.
156 * Looks like a private variable.
157 * @see $wgAdvertisedFeedTypes
159 var $mFeedLinks = array();
161 // Gwicke work on squid caching? Roughly from 2003.
162 var $mEnableClientCache = true;
165 * Flag if output should only contain the body of the article.
168 var $mArticleBodyOnly = false;
170 var $mNewSectionLink = false;
171 var $mHideNewSectionLink = false;
174 * Comes from the parser. This was probably made to load CSS/JS only
175 * if we had <gallery>. Used directly in CategoryPage.php
176 * Looks like resource loader can replace this.
178 var $mNoGallery = false;
180 // should be private.
181 var $mPageTitleActionText = '';
182 var $mParseWarnings = array();
184 // Cache stuff. Looks like mEnableClientCache
185 var $mSquidMaxage = 0;
188 var $mPreventClickjacking = true;
190 /// should be private. To include the variable {{REVISIONID}}
191 var $mRevisionId = null;
196 * An array of stylesheet filenames (relative from skins path), with options
197 * for CSS media, IE conditions, and RTL/LTR direction.
198 * For internal use; add settings in the skin via $this->addStyle()
200 * Style again! This seems like a code duplication since we already have
201 * mStyles. This is what makes OpenSource amazing.
203 var $styles = array();
206 * Whether jQuery is already handled.
208 protected $mJQueryDone = false;
210 private $mIndexPolicy = 'index';
211 private $mFollowPolicy = 'follow';
212 private $mVaryHeader = array(
213 'Accept-Encoding' => array( 'list-contains=gzip' ),
218 * Constructor for OutputPage. This should not be called directly.
219 * Instead a new RequestContext should be created and it will implicitly create
220 * a OutputPage tied to that context.
222 function __construct( RequestContext
$context = null ) {
223 if ( $context === null ) {
224 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
225 wfDeprecated( __METHOD__
);
226 $this->setContext( RequestContext
::getMain() );
228 $this->setContext( $context );
233 * Redirect to $url rather than displaying the normal page
235 * @param $url String: URL
236 * @param $responsecode String: HTTP status code
238 public function redirect( $url, $responsecode = '302' ) {
239 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
240 $this->mRedirect
= str_replace( "\n", '', $url );
241 $this->mRedirectCode
= $responsecode;
245 * Get the URL to redirect to, or an empty string if not redirect URL set
249 public function getRedirect() {
250 return $this->mRedirect
;
254 * Set the HTTP status code to send with the output.
256 * @param $statusCode Integer
258 public function setStatusCode( $statusCode ) {
259 $this->mStatusCode
= $statusCode;
263 * Add a new <meta> tag
264 * To add an http-equiv meta tag, precede the name with "http:"
266 * @param $name String tag name
267 * @param $val String tag value
269 function addMeta( $name, $val ) {
270 array_push( $this->mMetatags
, array( $name, $val ) );
274 * Add a keyword or a list of keywords in the page header
276 * @param $text String or array of strings
278 function addKeyword( $text ) {
279 if( is_array( $text ) ) {
280 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
282 array_push( $this->mKeywords
, $text );
287 * Add a new \<link\> tag to the page header
289 * @param $linkarr Array: associative array of attributes.
291 function addLink( $linkarr ) {
292 array_push( $this->mLinktags
, $linkarr );
296 * Add a new \<link\> with "rel" attribute set to "meta"
298 * @param $linkarr Array: associative array mapping attribute names to their
299 * values, both keys and values will be escaped, and the
300 * "rel" attribute will be automatically added
302 function addMetadataLink( $linkarr ) {
303 $linkarr['rel'] = $this->getMetadataAttribute();
304 $this->addLink( $linkarr );
308 * Get the value of the "rel" attribute for metadata links
312 private function getMetadataAttribute() {
313 # note: buggy CC software only reads first "meta" link
314 static $haveMeta = false;
316 return 'alternate meta';
324 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
326 * @param $script String: raw HTML
328 function addScript( $script ) {
329 $this->mScripts
.= $script . "\n";
333 * Register and add a stylesheet from an extension directory.
335 * @param $url String path to sheet. Provide either a full url (beginning
336 * with 'http', etc) or a relative path from the document root
337 * (beginning with '/'). Otherwise it behaves identically to
338 * addStyle() and draws from the /skins folder.
340 public function addExtensionStyle( $url ) {
341 array_push( $this->mExtStyles
, $url );
345 * Get all styles added by extensions
349 function getExtStyle() {
350 return $this->mExtStyles
;
354 * Add a JavaScript file out of skins/common, or a given relative path.
356 * @param $file String: filename in skins/common or complete on-server path
358 * @param $version String: style version of the file. Defaults to $wgStyleVersion
360 public function addScriptFile( $file, $version = null ) {
361 global $wgStylePath, $wgStyleVersion;
362 // See if $file parameter is an absolute URL or begins with a slash
363 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
366 $path = "{$wgStylePath}/common/{$file}";
368 if ( is_null( $version ) )
369 $version = $wgStyleVersion;
370 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
374 * Add a self-contained script tag with the given contents
376 * @param $script String: JavaScript text, no <script> tags
378 public function addInlineScript( $script ) {
379 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
383 * Get all registered JS and CSS tags for the header.
387 function getScript() {
388 return $this->mScripts
. $this->getHeadItems();
392 * Filter an array of modules to remove insufficiently trustworthy members, and modules
393 * which are no longer registered (eg a page is cached before an extension is disabled)
394 * @param $modules Array
395 * @param $position String if not null, only return modules with this position
398 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
399 $resourceLoader = $this->getResourceLoader();
400 $filteredModules = array();
401 foreach( $modules as $val ){
402 $module = $resourceLoader->getModule( $val );
403 if( $module instanceof ResourceLoaderModule
404 && $module->getOrigin() <= $this->getAllowedModules( $type )
405 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
407 $filteredModules[] = $val;
410 return $filteredModules;
414 * Get the list of modules to include on this page
416 * @param $filter Bool whether to filter out insufficiently trustworthy modules
417 * @param $position String if not null, only return modules with this position
418 * @return Array of module names
420 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
421 $modules = array_values( array_unique( $this->$param ) );
423 ?
$this->filterModules( $modules, $position )
428 * Add one or more modules recognized by the resource loader. Modules added
429 * through this function will be loaded by the resource loader when the
432 * @param $modules Mixed: module name (string) or array of module names
434 public function addModules( $modules ) {
435 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
439 * Get the list of module JS to include on this page
440 * @return array of module names
442 public function getModuleScripts( $filter = false, $position = null ) {
443 return $this->getModules( $filter, $position, 'mModuleScripts' );
447 * Add only JS of one or more modules recognized by the resource loader. Module
448 * scripts added through this function will be loaded by the resource loader when
451 * @param $modules Mixed: module name (string) or array of module names
453 public function addModuleScripts( $modules ) {
454 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
458 * Get the list of module CSS to include on this page
460 * @return Array of module names
462 public function getModuleStyles( $filter = false, $position = null ) {
463 return $this->getModules( $filter, $position, 'mModuleStyles' );
467 * Add only CSS of one or more modules recognized by the resource loader. Module
468 * styles added through this function will be loaded by the resource loader when
471 * @param $modules Mixed: module name (string) or array of module names
473 public function addModuleStyles( $modules ) {
474 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
478 * Get the list of module messages to include on this page
480 * @return Array of module names
482 public function getModuleMessages( $filter = false, $position = null ) {
483 return $this->getModules( $filter, $position, 'mModuleMessages' );
487 * Add only messages of one or more modules recognized by the resource loader.
488 * Module messages added through this function will be loaded by the resource
489 * loader when the page loads.
491 * @param $modules Mixed: module name (string) or array of module names
493 public function addModuleMessages( $modules ) {
494 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
498 * Get all header items in a string
502 function getHeadItems() {
504 foreach ( $this->mHeadItems
as $item ) {
511 * Add or replace an header item to the output
513 * @param $name String: item name
514 * @param $value String: raw HTML
516 public function addHeadItem( $name, $value ) {
517 $this->mHeadItems
[$name] = $value;
521 * Check if the header item $name is already set
523 * @param $name String: item name
526 public function hasHeadItem( $name ) {
527 return isset( $this->mHeadItems
[$name] );
531 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
533 * @param $tag String: value of "ETag" header
535 function setETag( $tag ) {
540 * Set whether the output should only contain the body of the article,
541 * without any skin, sidebar, etc.
542 * Used e.g. when calling with "action=render".
544 * @param $only Boolean: whether to output only the body of the article
546 public function setArticleBodyOnly( $only ) {
547 $this->mArticleBodyOnly
= $only;
551 * Return whether the output will contain only the body of the article
555 public function getArticleBodyOnly() {
556 return $this->mArticleBodyOnly
;
560 * checkLastModified tells the client to use the client-cached page if
561 * possible. If sucessful, the OutputPage is disabled so that
562 * any future call to OutputPage->output() have no effect.
564 * Side effect: sets mLastModified for Last-Modified header
566 * @return Boolean: true iff cache-ok headers was sent.
568 public function checkLastModified( $timestamp ) {
569 global $wgCachePages, $wgCacheEpoch;
571 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
572 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
575 if( !$wgCachePages ) {
576 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
579 if( $this->getUser()->getOption( 'nocache' ) ) {
580 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
584 $timestamp = wfTimestamp( TS_MW
, $timestamp );
585 $modifiedTimes = array(
586 'page' => $timestamp,
587 'user' => $this->getUser()->getTouched(),
588 'epoch' => $wgCacheEpoch
590 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
592 $maxModified = max( $modifiedTimes );
593 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
595 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
596 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
602 foreach ( $modifiedTimes as $name => $value ) {
603 if ( $info !== '' ) {
606 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
609 # IE sends sizes after the date like this:
610 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
611 # this breaks strtotime().
612 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
614 wfSuppressWarnings(); // E_STRICT system time bitching
615 $clientHeaderTime = strtotime( $clientHeader );
617 if ( !$clientHeaderTime ) {
618 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
621 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
623 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
624 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
625 wfDebug( __METHOD__
. ": effective Last-Modified: " .
626 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
627 if( $clientHeaderTime < $maxModified ) {
628 wfDebug( __METHOD__
. ": STALE, $info\n", false );
633 # Give a 304 response code and disable body output
634 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
635 ini_set( 'zlib.output_compression', 0 );
636 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
637 $this->sendCacheControl();
640 // Don't output a compressed blob when using ob_gzhandler;
641 // it's technically against HTTP spec and seems to confuse
642 // Firefox when the response gets split over two packets.
643 wfClearOutputBuffers();
649 * Override the last modified timestamp
651 * @param $timestamp String: new timestamp, in a format readable by
654 public function setLastModified( $timestamp ) {
655 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
659 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
661 * @param $policy String: the literal string to output as the contents of
662 * the meta tag. Will be parsed according to the spec and output in
666 public function setRobotPolicy( $policy ) {
667 $policy = Article
::formatRobotPolicy( $policy );
669 if( isset( $policy['index'] ) ) {
670 $this->setIndexPolicy( $policy['index'] );
672 if( isset( $policy['follow'] ) ) {
673 $this->setFollowPolicy( $policy['follow'] );
678 * Set the index policy for the page, but leave the follow policy un-
681 * @param $policy string Either 'index' or 'noindex'.
684 public function setIndexPolicy( $policy ) {
685 $policy = trim( $policy );
686 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
687 $this->mIndexPolicy
= $policy;
692 * Set the follow policy for the page, but leave the index policy un-
695 * @param $policy String: either 'follow' or 'nofollow'.
698 public function setFollowPolicy( $policy ) {
699 $policy = trim( $policy );
700 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
701 $this->mFollowPolicy
= $policy;
706 * Set the new value of the "action text", this will be added to the
707 * "HTML title", separated from it with " - ".
709 * @param $text String: new value of the "action text"
711 public function setPageTitleActionText( $text ) {
712 $this->mPageTitleActionText
= $text;
716 * Get the value of the "action text"
720 public function getPageTitleActionText() {
721 if ( isset( $this->mPageTitleActionText
) ) {
722 return $this->mPageTitleActionText
;
727 * "HTML title" means the contents of <title>.
728 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
730 public function setHTMLTitle( $name ) {
731 $this->mHTMLtitle
= $name;
735 * Return the "HTML title", i.e. the content of the <title> tag.
739 public function getHTMLTitle() {
740 return $this->mHTMLtitle
;
744 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
745 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
746 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
747 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
749 public function setPageTitle( $name ) {
750 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
751 # but leave "<i>foobar</i>" alone
752 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
753 $this->mPagetitle
= $nameWithTags;
755 # change "<i>foo&bar</i>" to "foo&bar"
756 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
760 * Return the "page title", i.e. the content of the \<h1\> tag.
764 public function getPageTitle() {
765 return $this->mPagetitle
;
769 * Set the Title object to use
771 * @param $t Title object
773 public function setTitle( $t ) {
774 $this->getContext()->setTitle( $t );
778 * Replace the subtile with $str
780 * @param $str String: new value of the subtitle
782 public function setSubtitle( $str ) {
783 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
787 * Add $str to the subtitle
789 * @param $str String to add to the subtitle
791 public function appendSubtitle( $str ) {
792 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
800 public function getSubtitle() {
801 return $this->mSubtitle
;
805 * Set the page as printable, i.e. it'll be displayed with with all
806 * print styles included
808 public function setPrintable() {
809 $this->mPrintable
= true;
813 * Return whether the page is "printable"
817 public function isPrintable() {
818 return $this->mPrintable
;
822 * Disable output completely, i.e. calling output() will have no effect
824 public function disable() {
825 $this->mDoNothing
= true;
829 * Return whether the output will be completely disabled
833 public function isDisabled() {
834 return $this->mDoNothing
;
838 * Show an "add new section" link?
842 public function showNewSectionLink() {
843 return $this->mNewSectionLink
;
847 * Forcibly hide the new section link?
851 public function forceHideNewSectionLink() {
852 return $this->mHideNewSectionLink
;
856 * Add or remove feed links in the page header
857 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
858 * for the new version
861 * @param $show Boolean: true: add default feeds, false: remove all feeds
863 public function setSyndicated( $show = true ) {
865 $this->setFeedAppendQuery( false );
867 $this->mFeedLinks
= array();
872 * Add default feeds to the page header
873 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
874 * for the new version
877 * @param $val String: query to append to feed links or false to output
880 public function setFeedAppendQuery( $val ) {
881 global $wgAdvertisedFeedTypes;
883 $this->mFeedLinks
= array();
885 foreach ( $wgAdvertisedFeedTypes as $type ) {
886 $query = "feed=$type";
887 if ( is_string( $val ) ) {
888 $query .= '&' . $val;
890 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
895 * Add a feed link to the page header
897 * @param $format String: feed type, should be a key of $wgFeedClasses
898 * @param $href String: URL
900 public function addFeedLink( $format, $href ) {
901 global $wgAdvertisedFeedTypes;
903 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
904 $this->mFeedLinks
[$format] = $href;
909 * Should we output feed links for this page?
912 public function isSyndicated() {
913 return count( $this->mFeedLinks
) > 0;
917 * Return URLs for each supported syndication format for this page.
918 * @return array associating format keys with URLs
920 public function getSyndicationLinks() {
921 return $this->mFeedLinks
;
925 * Will currently always return null
929 public function getFeedAppendQuery() {
930 return $this->mFeedLinksAppendQuery
;
934 * Set whether the displayed content is related to the source of the
935 * corresponding article on the wiki
936 * Setting true will cause the change "article related" toggle to true
940 public function setArticleFlag( $v ) {
941 $this->mIsarticle
= $v;
943 $this->mIsArticleRelated
= $v;
948 * Return whether the content displayed page is related to the source of
949 * the corresponding article on the wiki
953 public function isArticle() {
954 return $this->mIsarticle
;
958 * Set whether this page is related an article on the wiki
959 * Setting false will cause the change of "article flag" toggle to false
963 public function setArticleRelated( $v ) {
964 $this->mIsArticleRelated
= $v;
966 $this->mIsarticle
= false;
971 * Return whether this page is related an article on the wiki
975 public function isArticleRelated() {
976 return $this->mIsArticleRelated
;
980 * Add new language links
982 * @param $newLinkArray Associative array mapping language code to the page
985 public function addLanguageLinks( $newLinkArray ) {
986 $this->mLanguageLinks +
= $newLinkArray;
990 * Reset the language links and add new language links
992 * @param $newLinkArray Associative array mapping language code to the page
995 public function setLanguageLinks( $newLinkArray ) {
996 $this->mLanguageLinks
= $newLinkArray;
1000 * Get the list of language links
1002 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1004 public function getLanguageLinks() {
1005 return $this->mLanguageLinks
;
1009 * Add an array of categories, with names in the keys
1011 * @param $categories Array mapping category name => sort key
1013 public function addCategoryLinks( $categories ) {
1016 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1020 # Add the links to a LinkBatch
1021 $arr = array( NS_CATEGORY
=> $categories );
1022 $lb = new LinkBatch
;
1023 $lb->setArray( $arr );
1025 # Fetch existence plus the hiddencat property
1026 $dbr = wfGetDB( DB_SLAVE
);
1027 $res = $dbr->select( array( 'page', 'page_props' ),
1028 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1029 $lb->constructSet( 'page', $dbr ),
1032 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1035 # Add the results to the link cache
1036 $lb->addResultToCache( LinkCache
::singleton(), $res );
1038 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1039 $categories = array_combine(
1040 array_keys( $categories ),
1041 array_fill( 0, count( $categories ), 'normal' )
1044 # Mark hidden categories
1045 foreach ( $res as $row ) {
1046 if ( isset( $row->pp_value
) ) {
1047 $categories[$row->page_title
] = 'hidden';
1051 # Add the remaining categories to the skin
1052 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1053 foreach ( $categories as $category => $type ) {
1054 $origcategory = $category;
1055 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1056 $wgContLang->findVariantLink( $category, $title, true );
1057 if ( $category != $origcategory ) {
1058 if ( array_key_exists( $category, $categories ) ) {
1062 $text = $wgContLang->convertHtml( $title->getText() );
1063 $this->mCategories
[] = $title->getText();
1064 $this->mCategoryLinks
[$type][] = $this->getSkin()->link( $title, $text );
1070 * Reset the category links (but not the category list) and add $categories
1072 * @param $categories Array mapping category name => sort key
1074 public function setCategoryLinks( $categories ) {
1075 $this->mCategoryLinks
= array();
1076 $this->addCategoryLinks( $categories );
1080 * Get the list of category links, in a 2-D array with the following format:
1081 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1082 * hidden categories) and $link a HTML fragment with a link to the category
1087 public function getCategoryLinks() {
1088 return $this->mCategoryLinks
;
1092 * Get the list of category names this page belongs to
1094 * @return Array of strings
1096 public function getCategories() {
1097 return $this->mCategories
;
1101 * Do not allow scripts which can be modified by wiki users to load on this page;
1102 * only allow scripts bundled with, or generated by, the software.
1104 public function disallowUserJs() {
1105 $this->reduceAllowedModules(
1106 ResourceLoaderModule
::TYPE_SCRIPTS
,
1107 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1112 * Return whether user JavaScript is allowed for this page
1113 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1114 * trustworthiness is identified and enforced automagically.
1117 public function isUserJsAllowed() {
1118 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1122 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1123 * @see ResourceLoaderModule::$origin
1124 * @param $type String ResourceLoaderModule TYPE_ constant
1125 * @return Int ResourceLoaderModule ORIGIN_ class constant
1127 public function getAllowedModules( $type ){
1128 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1129 return min( array_values( $this->mAllowedModules
) );
1131 return isset( $this->mAllowedModules
[$type] )
1132 ?
$this->mAllowedModules
[$type]
1133 : ResourceLoaderModule
::ORIGIN_ALL
;
1138 * Set the highest level of CSS/JS untrustworthiness allowed
1139 * @param $type String ResourceLoaderModule TYPE_ constant
1140 * @param $level Int ResourceLoaderModule class constant
1142 public function setAllowedModules( $type, $level ){
1143 $this->mAllowedModules
[$type] = $level;
1147 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1148 * @param $type String
1149 * @param $level Int ResourceLoaderModule class constant
1151 public function reduceAllowedModules( $type, $level ){
1152 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1156 * Prepend $text to the body HTML
1158 * @param $text String: HTML
1160 public function prependHTML( $text ) {
1161 $this->mBodytext
= $text . $this->mBodytext
;
1165 * Append $text to the body HTML
1167 * @param $text String: HTML
1169 public function addHTML( $text ) {
1170 $this->mBodytext
.= $text;
1174 * Clear the body HTML
1176 public function clearHTML() {
1177 $this->mBodytext
= '';
1183 * @return String: HTML
1185 public function getHTML() {
1186 return $this->mBodytext
;
1190 * Add $text to the debug output
1192 * @param $text String: debug text
1194 public function debug( $text ) {
1195 $this->mDebugtext
.= $text;
1199 * Get/set the ParserOptions object to use for wikitext parsing
1201 * @param $options either the ParserOption to use or null to only get the
1202 * current ParserOption object
1203 * @return ParserOptions object
1205 public function parserOptions( $options = null ) {
1206 if ( !$this->mParserOptions
) {
1207 $this->mParserOptions
= new ParserOptions
;
1209 return wfSetVar( $this->mParserOptions
, $options );
1213 * Set the revision ID which will be seen by the wiki text parser
1214 * for things such as embedded {{REVISIONID}} variable use.
1216 * @param $revid Mixed: an positive integer, or null
1217 * @return Mixed: previous value
1219 public function setRevisionId( $revid ) {
1220 $val = is_null( $revid ) ?
null : intval( $revid );
1221 return wfSetVar( $this->mRevisionId
, $val );
1225 * Get the current revision ID
1229 public function getRevisionId() {
1230 return $this->mRevisionId
;
1234 * Get the templates used on this page
1236 * @return Array (namespace => dbKey => revId)
1239 public function getTemplateIds() {
1240 return $this->mTemplateIds
;
1244 * Get the files used on this page
1246 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1249 public function getImageTimeKeys() {
1250 return $this->mImageTimeKeys
;
1254 * Convert wikitext to HTML and add it to the buffer
1255 * Default assumes that the current page title will be used.
1257 * @param $text String
1258 * @param $linestart Boolean: is this the start of a line?
1260 public function addWikiText( $text, $linestart = true ) {
1261 $title = $this->getTitle(); // Work arround E_STRICT
1262 $this->addWikiTextTitle( $text, $title, $linestart );
1266 * Add wikitext with a custom Title object
1268 * @param $text String: wikitext
1269 * @param $title Title object
1270 * @param $linestart Boolean: is this the start of a line?
1272 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1273 $this->addWikiTextTitle( $text, $title, $linestart );
1277 * Add wikitext with a custom Title object and
1279 * @param $text String: wikitext
1280 * @param $title Title object
1281 * @param $linestart Boolean: is this the start of a line?
1283 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1284 $this->addWikiTextTitle( $text, $title, $linestart, true );
1288 * Add wikitext with tidy enabled
1290 * @param $text String: wikitext
1291 * @param $linestart Boolean: is this the start of a line?
1293 public function addWikiTextTidy( $text, $linestart = true ) {
1294 $title = $this->getTitle();
1295 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1299 * Add wikitext with a custom Title object
1301 * @param $text String: wikitext
1302 * @param $title Title object
1303 * @param $linestart Boolean: is this the start of a line?
1304 * @param $tidy Boolean: whether to use tidy
1306 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1309 wfProfileIn( __METHOD__
);
1311 wfIncrStats( 'pcache_not_possible' );
1313 $popts = $this->parserOptions();
1314 $oldTidy = $popts->setTidy( $tidy );
1316 $parserOutput = $wgParser->parse(
1317 $text, $title, $popts,
1318 $linestart, true, $this->mRevisionId
1321 $popts->setTidy( $oldTidy );
1323 $this->addParserOutput( $parserOutput );
1325 wfProfileOut( __METHOD__
);
1329 * Add a ParserOutput object, but without Html
1331 * @param $parserOutput ParserOutput object
1333 public function addParserOutputNoText( &$parserOutput ) {
1334 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1335 $this->addCategoryLinks( $parserOutput->getCategories() );
1336 $this->mNewSectionLink
= $parserOutput->getNewSection();
1337 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1339 $this->mParseWarnings
= $parserOutput->getWarnings();
1340 if ( !$parserOutput->isCacheable() ) {
1341 $this->enableClientCache( false );
1343 $this->mNoGallery
= $parserOutput->getNoGallery();
1344 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1345 $this->addModules( $parserOutput->getModules() );
1347 // Template versioning...
1348 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1349 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1350 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1352 $this->mTemplateIds
[$ns] = $dbks;
1355 // File versioning...
1356 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1357 $this->mImageTimeKeys
[$dbk] = $data;
1360 // Hooks registered in the object
1361 global $wgParserOutputHooks;
1362 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1363 list( $hookName, $data ) = $hookInfo;
1364 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1365 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1369 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1373 * Add a ParserOutput object
1375 * @param $parserOutput ParserOutput
1377 function addParserOutput( &$parserOutput ) {
1378 $this->addParserOutputNoText( $parserOutput );
1379 $text = $parserOutput->getText();
1380 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1381 $this->addHTML( $text );
1386 * Add the output of a QuickTemplate to the output buffer
1388 * @param $template QuickTemplate
1390 public function addTemplate( &$template ) {
1392 $template->execute();
1393 $this->addHTML( ob_get_contents() );
1398 * Parse wikitext and return the HTML.
1400 * @param $text String
1401 * @param $linestart Boolean: is this the start of a line?
1402 * @param $interface Boolean: use interface language ($wgLang instead of
1403 * $wgContLang) while parsing language sensitive magic
1404 * words like GRAMMAR and PLURAL
1405 * @param $language Language object: target language object, will override
1407 * @return String: HTML
1409 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1410 // Check one for one common cause for parser state resetting
1411 $callers = wfGetAllCallers( 10 );
1412 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1413 throw new MWException( "wfMsg* function with parsing cannot be used " .
1414 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1419 if( is_null( $this->getTitle() ) ) {
1420 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1423 $popts = $this->parserOptions();
1425 $popts->setInterfaceMessage( true );
1427 if ( $language !== null ) {
1428 $oldLang = $popts->setTargetLanguage( $language );
1431 $parserOutput = $wgParser->parse(
1432 $text, $this->getTitle(), $popts,
1433 $linestart, true, $this->mRevisionId
1437 $popts->setInterfaceMessage( false );
1439 if ( $language !== null ) {
1440 $popts->setTargetLanguage( $oldLang );
1443 return $parserOutput->getText();
1447 * Parse wikitext, strip paragraphs, and return the HTML.
1449 * @param $text String
1450 * @param $linestart Boolean: is this the start of a line?
1451 * @param $interface Boolean: use interface language ($wgLang instead of
1452 * $wgContLang) while parsing language sensitive magic
1453 * words like GRAMMAR and PLURAL
1454 * @return String: HTML
1456 public function parseInline( $text, $linestart = true, $interface = false ) {
1457 $parsed = $this->parse( $text, $linestart, $interface );
1460 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1468 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1470 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1472 public function setSquidMaxage( $maxage ) {
1473 $this->mSquidMaxage
= $maxage;
1477 * Use enableClientCache(false) to force it to send nocache headers
1481 public function enableClientCache( $state ) {
1482 return wfSetVar( $this->mEnableClientCache
, $state );
1486 * Get the list of cookies that will influence on the cache
1490 function getCacheVaryCookies() {
1491 global $wgCookiePrefix, $wgCacheVaryCookies;
1493 if ( $cookies === null ) {
1494 $cookies = array_merge(
1496 "{$wgCookiePrefix}Token",
1497 "{$wgCookiePrefix}LoggedOut",
1502 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1508 * Return whether this page is not cacheable because "useskin" or "uselang"
1509 * URL parameters were passed.
1513 function uncacheableBecauseRequestVars() {
1514 $request = $this->getRequest();
1515 return $request->getText( 'useskin', false ) === false
1516 && $request->getText( 'uselang', false ) === false;
1520 * Check if the request has a cache-varying cookie header
1521 * If it does, it's very important that we don't allow public caching
1525 function haveCacheVaryCookies() {
1526 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1527 if ( $cookieHeader === false ) {
1530 $cvCookies = $this->getCacheVaryCookies();
1531 foreach ( $cvCookies as $cookieName ) {
1532 # Check for a simple string match, like the way squid does it
1533 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1534 wfDebug( __METHOD__
. ": found $cookieName\n" );
1538 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1543 * Add an HTTP header that will influence on the cache
1545 * @param $header String: header name
1546 * @param $option Array|null
1547 * @fixme Document the $option parameter; it appears to be for
1548 * X-Vary-Options but what format is acceptable?
1550 public function addVaryHeader( $header, $option = null ) {
1551 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1552 $this->mVaryHeader
[$header] = (array)$option;
1553 } elseif( is_array( $option ) ) {
1554 if( is_array( $this->mVaryHeader
[$header] ) ) {
1555 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1557 $this->mVaryHeader
[$header] = $option;
1560 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1564 * Get a complete X-Vary-Options header
1568 public function getXVO() {
1569 $cvCookies = $this->getCacheVaryCookies();
1571 $cookiesOption = array();
1572 foreach ( $cvCookies as $cookieName ) {
1573 $cookiesOption[] = 'string-contains=' . $cookieName;
1575 $this->addVaryHeader( 'Cookie', $cookiesOption );
1578 foreach( $this->mVaryHeader
as $header => $option ) {
1579 $newheader = $header;
1580 if( is_array( $option ) ) {
1581 $newheader .= ';' . implode( ';', $option );
1583 $headers[] = $newheader;
1585 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1591 * bug 21672: Add Accept-Language to Vary and XVO headers
1592 * if there's no 'variant' parameter existed in GET.
1595 * /w/index.php?title=Main_page should always be served; but
1596 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1598 function addAcceptLanguage() {
1600 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1601 $variants = $wgContLang->getVariants();
1602 $aloption = array();
1603 foreach ( $variants as $variant ) {
1604 if( $variant === $wgContLang->getCode() ) {
1607 $aloption[] = 'string-contains=' . $variant;
1609 // IE and some other browsers use another form of language code
1610 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1611 // We should handle these too.
1612 $ievariant = explode( '-', $variant );
1613 if ( count( $ievariant ) == 2 ) {
1614 $ievariant[1] = strtoupper( $ievariant[1] );
1615 $ievariant = implode( '-', $ievariant );
1616 $aloption[] = 'string-contains=' . $ievariant;
1620 $this->addVaryHeader( 'Accept-Language', $aloption );
1625 * Set a flag which will cause an X-Frame-Options header appropriate for
1626 * edit pages to be sent. The header value is controlled by
1627 * $wgEditPageFrameOptions.
1629 * This is the default for special pages. If you display a CSRF-protected
1630 * form on an ordinary view page, then you need to call this function.
1632 public function preventClickjacking( $enable = true ) {
1633 $this->mPreventClickjacking
= $enable;
1637 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1638 * This can be called from pages which do not contain any CSRF-protected
1641 public function allowClickjacking() {
1642 $this->mPreventClickjacking
= false;
1646 * Get the X-Frame-Options header value (without the name part), or false
1647 * if there isn't one. This is used by Skin to determine whether to enable
1648 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1650 public function getFrameOptions() {
1651 global $wgBreakFrames, $wgEditPageFrameOptions;
1652 if ( $wgBreakFrames ) {
1654 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1655 return $wgEditPageFrameOptions;
1660 * Send cache control HTTP headers
1662 public function sendCacheControl() {
1663 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1665 $response = $this->getRequest()->response();
1666 if ( $wgUseETag && $this->mETag
) {
1667 $response->header( "ETag: $this->mETag" );
1670 $this->addAcceptLanguage();
1672 # don't serve compressed data to clients who can't handle it
1673 # maintain different caches for logged-in users and non-logged in ones
1674 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1677 # Add an X-Vary-Options header for Squid with Wikimedia patches
1678 $response->header( $this->getXVO() );
1681 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1683 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1684 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1688 # We'll purge the proxy cache explicitly, but require end user agents
1689 # to revalidate against the proxy on each visit.
1690 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1691 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1692 # start with a shorter timeout for initial testing
1693 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1694 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1695 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1697 # We'll purge the proxy cache for anons explicitly, but require end user agents
1698 # to revalidate against the proxy on each visit.
1699 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1700 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1701 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1702 # start with a shorter timeout for initial testing
1703 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1704 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1707 # We do want clients to cache if they can, but they *must* check for updates
1708 # on revisiting the page.
1709 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1710 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1711 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1713 if($this->mLastModified
) {
1714 $response->header( "Last-Modified: {$this->mLastModified}" );
1717 wfDebug( __METHOD__
. ": no caching **\n", false );
1719 # In general, the absence of a last modified header should be enough to prevent
1720 # the client from using its cache. We send a few other things just to make sure.
1721 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1722 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1723 $response->header( 'Pragma: no-cache' );
1728 * Get the message associed with the HTTP response code $code
1730 * @param $code Integer: status code
1731 * @return String or null: message or null if $code is not in the list of
1734 public static function getStatusMessage( $code ) {
1735 static $statusMessage = array(
1737 101 => 'Switching Protocols',
1738 102 => 'Processing',
1742 203 => 'Non-Authoritative Information',
1743 204 => 'No Content',
1744 205 => 'Reset Content',
1745 206 => 'Partial Content',
1746 207 => 'Multi-Status',
1747 300 => 'Multiple Choices',
1748 301 => 'Moved Permanently',
1751 304 => 'Not Modified',
1753 307 => 'Temporary Redirect',
1754 400 => 'Bad Request',
1755 401 => 'Unauthorized',
1756 402 => 'Payment Required',
1759 405 => 'Method Not Allowed',
1760 406 => 'Not Acceptable',
1761 407 => 'Proxy Authentication Required',
1762 408 => 'Request Timeout',
1765 411 => 'Length Required',
1766 412 => 'Precondition Failed',
1767 413 => 'Request Entity Too Large',
1768 414 => 'Request-URI Too Large',
1769 415 => 'Unsupported Media Type',
1770 416 => 'Request Range Not Satisfiable',
1771 417 => 'Expectation Failed',
1772 422 => 'Unprocessable Entity',
1774 424 => 'Failed Dependency',
1775 500 => 'Internal Server Error',
1776 501 => 'Not Implemented',
1777 502 => 'Bad Gateway',
1778 503 => 'Service Unavailable',
1779 504 => 'Gateway Timeout',
1780 505 => 'HTTP Version Not Supported',
1781 507 => 'Insufficient Storage'
1783 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1787 * Finally, all the text has been munged and accumulated into
1788 * the object, let's actually output it:
1790 public function output() {
1791 global $wgOutputEncoding;
1792 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1794 if( $this->mDoNothing
) {
1798 wfProfileIn( __METHOD__
);
1800 $response = $this->getRequest()->response();
1802 if ( $this->mRedirect
!= '' ) {
1803 # Standards require redirect URLs to be absolute
1804 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1805 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1806 if( !$wgDebugRedirects ) {
1807 $message = self
::getStatusMessage( $this->mRedirectCode
);
1808 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1810 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1812 $this->sendCacheControl();
1814 $response->header( "Content-Type: text/html; charset=utf-8" );
1815 if( $wgDebugRedirects ) {
1816 $url = htmlspecialchars( $this->mRedirect
);
1817 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1818 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1819 print "</body>\n</html>\n";
1821 $response->header( 'Location: ' . $this->mRedirect
);
1823 wfProfileOut( __METHOD__
);
1825 } elseif ( $this->mStatusCode
) {
1826 $message = self
::getStatusMessage( $this->mStatusCode
);
1828 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1832 # Buffer output; final headers may depend on later processing
1835 $response->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1836 $response->header( 'Content-language: ' . $wgLanguageCode );
1838 // Prevent framing, if requested
1839 $frameOptions = $this->getFrameOptions();
1840 if ( $frameOptions ) {
1841 $response->header( "X-Frame-Options: $frameOptions" );
1844 if ( $this->mArticleBodyOnly
) {
1845 $this->out( $this->mBodytext
);
1847 $this->addDefaultModules();
1849 $sk = $this->getSkin( $this->getTitle() );
1851 // Hook that allows last minute changes to the output page, e.g.
1852 // adding of CSS or Javascript by extensions.
1853 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1855 wfProfileIn( 'Output-skin' );
1856 $sk->outputPage( $this );
1857 wfProfileOut( 'Output-skin' );
1860 $this->sendCacheControl();
1862 wfProfileOut( __METHOD__
);
1866 * Actually output something with print(). Performs an iconv to the
1867 * output encoding, if needed.
1869 * @param $ins String: the string to output
1871 public function out( $ins ) {
1872 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1873 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1876 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1877 if ( false === $outs ) {
1885 * Produce a "user is blocked" page.
1886 * @deprecated since 1.18
1888 function blockedPage() {
1889 throw new UserBlockedError( $this->getUser()->mBlock
);
1893 * Output a standard error page
1895 * @param $title String: message key for page title
1896 * @param $msg String: message key for page text
1897 * @param $params Array: message parameters
1899 public function showErrorPage( $title, $msg, $params = array() ) {
1900 if ( $this->getTitle() ) {
1901 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1903 $this->setPageTitle( wfMsg( $title ) );
1904 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1905 $this->setRobotPolicy( 'noindex,nofollow' );
1906 $this->setArticleRelated( false );
1907 $this->enableClientCache( false );
1908 $this->mRedirect
= '';
1909 $this->mBodytext
= '';
1911 $this->addWikiMsgArray( $msg, $params );
1913 $this->returnToMain();
1917 * Output a standard permission error page
1919 * @param $errors Array: error message keys
1920 * @param $action String: action that was denied or null if unknown
1922 public function showPermissionsErrorPage( $errors, $action = null ) {
1923 $this->mDebugtext
.= 'Original title: ' .
1924 $this->getTitle()->getPrefixedText() . "\n";
1925 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1926 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1927 $this->setRobotPolicy( 'noindex,nofollow' );
1928 $this->setArticleRelated( false );
1929 $this->enableClientCache( false );
1930 $this->mRedirect
= '';
1931 $this->mBodytext
= '';
1932 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1936 * Display an error page indicating that a given version of MediaWiki is
1937 * required to use it
1939 * @param $version Mixed: the version of MediaWiki needed to use the page
1941 public function versionRequired( $version ) {
1942 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1943 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1944 $this->setRobotPolicy( 'noindex,nofollow' );
1945 $this->setArticleRelated( false );
1946 $this->mBodytext
= '';
1948 $this->addWikiMsg( 'versionrequiredtext', $version );
1949 $this->returnToMain();
1953 * Display an error page noting that a given permission bit is required.
1954 * @deprecated since 1.18, just throw the exception directly
1955 * @param $permission String: key required
1957 public function permissionRequired( $permission ) {
1958 throw new PermissionsError( $permission );
1962 * Produce the stock "please login to use the wiki" page
1964 public function loginToUse() {
1965 if( $this->getUser()->isLoggedIn() ) {
1966 throw new PermissionsError( 'read' );
1969 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1970 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1971 $this->setRobotPolicy( 'noindex,nofollow' );
1972 $this->setArticleRelated( false );
1974 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1975 $loginLink = $this->getSkin()->link(
1977 wfMsgHtml( 'loginreqlink' ),
1979 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1980 array( 'known', 'noclasses' )
1982 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
1983 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1985 # Don't return to the main page if the user can't read it
1986 # otherwise we'll end up in a pointless loop
1987 $mainPage = Title
::newMainPage();
1988 if( $mainPage->userCanRead() ) {
1989 $this->returnToMain( null, $mainPage );
1994 * Format a list of error messages
1996 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
1997 * @param $action String: action that was denied or null if unknown
1998 * @return String: the wikitext error-messages, formatted into a list.
2000 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2001 if ( $action == null ) {
2002 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2004 $action_desc = wfMsgNoTrans( "action-$action" );
2005 $text = wfMsgNoTrans(
2006 'permissionserrorstext-withaction',
2012 if ( count( $errors ) > 1 ) {
2013 $text .= '<ul class="permissions-errors">' . "\n";
2015 foreach( $errors as $error ) {
2017 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2022 $text .= "<div class=\"permissions-errors\">\n" .
2023 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2031 * Display a page stating that the Wiki is in read-only mode,
2032 * and optionally show the source of the page that the user
2033 * was trying to edit. Should only be called (for this
2034 * purpose) after wfReadOnly() has returned true.
2036 * For historical reasons, this function is _also_ used to
2037 * show the error message when a user tries to edit a page
2038 * they are not allowed to edit. (Unless it's because they're
2039 * blocked, then we show blockedPage() instead.) In this
2040 * case, the second parameter should be set to true and a list
2041 * of reasons supplied as the third parameter.
2043 * @todo Needs to be split into multiple functions.
2045 * @param $source String: source code to show (or null).
2046 * @param $protected Boolean: is this a permissions error?
2047 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2048 * @param $action String: action that was denied or null if unknown
2050 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2051 $this->setRobotPolicy( 'noindex,nofollow' );
2052 $this->setArticleRelated( false );
2054 // If no reason is given, just supply a default "I can't let you do
2055 // that, Dave" message. Should only occur if called by legacy code.
2056 if ( $protected && empty( $reasons ) ) {
2057 $reasons[] = array( 'badaccess-group0' );
2060 if ( !empty( $reasons ) ) {
2061 // Permissions error
2063 $this->setPageTitle( wfMsg( 'viewsource' ) );
2065 wfMsg( 'viewsourcefor', $this->getSkin()->linkKnown( $this->getTitle() ) )
2068 $this->setPageTitle( wfMsg( 'badaccess' ) );
2070 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2072 // Wiki is read only
2073 throw new ReadOnlyError
;
2076 // Show source, if supplied
2077 if( is_string( $source ) ) {
2078 $this->addWikiMsg( 'viewsourcetext' );
2081 'id' => 'wpTextbox1',
2082 'name' => 'wpTextbox1',
2083 'cols' => $this->getUser()->getOption( 'cols' ),
2084 'rows' => $this->getUser()->getOption( 'rows' ),
2085 'readonly' => 'readonly'
2087 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2089 // Show templates used by this article
2090 $skin = $this->getSkin();
2091 $article = new Article( $this->getTitle() );
2092 $this->addHTML( "<div class='templatesUsed'>
2093 {$skin->formatTemplates( $article->getUsedTemplates() )}
2098 # If the title doesn't exist, it's fairly pointless to print a return
2099 # link to it. After all, you just tried editing it and couldn't, so
2100 # what's there to do there?
2101 if( $this->getTitle()->exists() ) {
2102 $this->returnToMain( null, $this->getTitle() );
2107 * Turn off regular page output and return an error reponse
2108 * for when rate limiting has triggered.
2110 public function rateLimited() {
2111 throw new ThrottledError
;
2115 * Show a warning about slave lag
2117 * If the lag is higher than $wgSlaveLagCritical seconds,
2118 * then the warning is a bit more obvious. If the lag is
2119 * lower than $wgSlaveLagWarning, then no warning is shown.
2121 * @param $lag Integer: slave lag
2123 public function showLagWarning( $lag ) {
2124 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2125 if( $lag >= $wgSlaveLagWarning ) {
2126 $message = $lag < $wgSlaveLagCritical
2129 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2130 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLang()->formatNum( $lag ) ) );
2134 public function showFatalError( $message ) {
2135 $this->setPageTitle( wfMsg( 'internalerror' ) );
2136 $this->setRobotPolicy( 'noindex,nofollow' );
2137 $this->setArticleRelated( false );
2138 $this->enableClientCache( false );
2139 $this->mRedirect
= '';
2140 $this->mBodytext
= $message;
2143 public function showUnexpectedValueError( $name, $val ) {
2144 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2147 public function showFileCopyError( $old, $new ) {
2148 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2151 public function showFileRenameError( $old, $new ) {
2152 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2155 public function showFileDeleteError( $name ) {
2156 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2159 public function showFileNotFoundError( $name ) {
2160 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2164 * Add a "return to" link pointing to a specified title
2166 * @param $title Title to link
2167 * @param $query String: query string
2168 * @param $text String text of the link (input is not escaped)
2170 public function addReturnTo( $title, $query = array(), $text = null ) {
2171 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2174 $this->getSkin()->link( $title, $text, array(), $query )
2176 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2180 * Add a "return to" link pointing to a specified title,
2181 * or the title indicated in the request, or else the main page
2183 * @param $unused No longer used
2184 * @param $returnto Title or String to return to
2185 * @param $returntoquery String: query string for the return to link
2187 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2188 if ( $returnto == null ) {
2189 $returnto = $this->getRequest()->getText( 'returnto' );
2192 if ( $returntoquery == null ) {
2193 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2196 if ( $returnto === '' ) {
2197 $returnto = Title
::newMainPage();
2200 if ( is_object( $returnto ) ) {
2201 $titleObj = $returnto;
2203 $titleObj = Title
::newFromText( $returnto );
2205 if ( !is_object( $titleObj ) ) {
2206 $titleObj = Title
::newMainPage();
2209 $this->addReturnTo( $titleObj, $returntoquery );
2213 * @param $sk Skin The given Skin
2214 * @param $includeStyle Boolean: unused
2215 * @return String: The doctype, opening <html>, and head element.
2217 public function headElement( Skin
$sk, $includeStyle = true ) {
2218 global $wgUseTrackbacks;
2220 if ( $sk->commonPrintStylesheet() ) {
2221 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2223 $sk->setupUserCss( $this );
2226 $ret = Html
::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2228 if ( $this->getHTMLTitle() == '' ) {
2229 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2232 $openHead = Html
::openElement( 'head' );
2234 # Don't bother with the newline if $head == ''
2235 $ret .= "$openHead\n";
2238 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2240 $ret .= implode( "\n", array(
2241 $this->getHeadLinks( $sk, true ),
2242 $this->buildCssLinks( $sk ),
2243 $this->getHeadScripts( $sk ),
2244 $this->getHeadItems()
2247 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2248 $ret .= $this->getTitle()->trackbackRDF();
2251 $closeHead = Html
::closeElement( 'head' );
2253 $ret .= "$closeHead\n";
2256 $bodyAttrs = array();
2258 # Crazy edit-on-double-click stuff
2259 $action = $this->getRequest()->getVal( 'action', 'view' );
2262 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2263 in_array( $action, array( 'view', 'purge' ) ) &&
2264 $this->getUser()->getOption( 'editondblclick' )
2267 $editUrl = $this->getTitle()->getLocalUrl( $sk->editUrlOptions() );
2268 $bodyAttrs['ondblclick'] = "document.location = '" .
2269 Xml
::escapeJsString( $editUrl ) . "'";
2273 $dir = wfUILang()->getDir();
2274 $bodyAttrs['class'] = "mediawiki $dir";
2276 if ( $this->getLang()->capitalizeAllNouns() ) {
2277 # A <body> class is probably not the best way to do this . . .
2278 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2280 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2281 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2283 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2284 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2286 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2292 * Add the default ResourceLoader modules to this object
2294 private function addDefaultModules() {
2295 global $wgIncludeLegacyJavaScript,
2296 $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2298 // Add base resources
2299 $this->addModules( 'mediawiki.util' );
2300 if( $wgIncludeLegacyJavaScript ){
2301 $this->addModules( 'mediawiki.legacy.wikibits' );
2304 // Add various resources if required
2306 $this->addModules( 'mediawiki.legacy.ajax' );
2308 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2310 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2311 $this->addModules( 'mediawiki.action.watch.ajax' );
2314 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2315 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2319 if( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2320 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2325 * Get a ResourceLoader object associated with this OutputPage
2327 * @return ResourceLoader
2329 public function getResourceLoader() {
2330 if ( is_null( $this->mResourceLoader
) ) {
2331 $this->mResourceLoader
= new ResourceLoader();
2333 return $this->mResourceLoader
;
2339 * @param $modules Array/string with the module name
2340 * @param $only String ResourceLoaderModule TYPE_ class constant
2341 * @param $useESI boolean
2342 * @return string html <script> and <style> tags
2344 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2345 global $wgLoadScript, $wgResourceLoaderUseESI,
2346 $wgResourceLoaderInlinePrivateModules;
2347 // Lazy-load ResourceLoader
2348 // TODO: Should this be a static function of ResourceLoader instead?
2349 // TODO: Divide off modules starting with "user", and add the user parameter to them
2351 'lang' => $this->getContext()->getLang()->getCode(),
2352 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2353 'skin' => $skin->getSkinName(),
2356 // Propagate printable and handheld parameters if present
2357 if ( $this->isPrintable() ) {
2358 $baseQuery['printable'] = 1;
2360 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2361 $baseQuery['handheld'] = 1;
2364 if ( !count( $modules ) ) {
2368 if ( count( $modules ) > 1 ) {
2369 // Remove duplicate module requests
2370 $modules = array_unique( (array) $modules );
2371 // Sort module names so requests are more uniform
2374 if ( ResourceLoader
::inDebugMode() ) {
2375 // Recursively call us for every item
2377 foreach ( $modules as $name ) {
2378 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2384 // Create keyed-by-group list of module objects from modules list
2386 $resourceLoader = $this->getResourceLoader();
2387 foreach ( (array) $modules as $name ) {
2388 $module = $resourceLoader->getModule( $name );
2389 # Check that we're allowed to include this module on this page
2390 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2391 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2392 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2393 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2399 $group = $module->getGroup();
2400 if ( !isset( $groups[$group] ) ) {
2401 $groups[$group] = array();
2403 $groups[$group][$name] = $module;
2407 foreach ( $groups as $group => $modules ) {
2408 $query = $baseQuery;
2409 // Special handling for user-specific groups
2410 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2411 $query['user'] = $this->getUser()->getName();
2414 // Create a fake request based on the one we are about to make so modules return
2415 // correct timestamp and emptiness data
2416 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2417 // Drop modules that know they're empty
2418 foreach ( $modules as $key => $module ) {
2419 if ( $module->isKnownEmpty( $context ) ) {
2420 unset( $modules[$key] );
2423 // If there are no modules left, skip this group
2424 if ( $modules === array() ) {
2428 $query['modules'] = implode( '|', array_keys( $modules ) );
2430 // Support inlining of private modules if configured as such
2431 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2432 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2433 $links .= Html
::inlineStyle(
2434 $resourceLoader->makeModuleResponse( $context, $modules )
2437 $links .= Html
::inlineScript(
2438 ResourceLoader
::makeLoaderConditionalScript(
2439 $resourceLoader->makeModuleResponse( $context, $modules )
2445 // Special handling for the user group; because users might change their stuff
2446 // on-wiki like user pages, or user preferences; we need to find the highest
2447 // timestamp of these user-changable modules so we can ensure cache misses on change
2448 // This should NOT be done for the site group (bug 27564) because anons get that too
2449 // and we shouldn't be putting timestamps in Squid-cached HTML
2450 if ( $group === 'user' ) {
2451 // Get the maximum timestamp
2453 foreach ( $modules as $module ) {
2454 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2456 // Add a version parameter so cache will break when things change
2457 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2459 // Make queries uniform in order
2462 $url = wfAppendQuery( $wgLoadScript, $query );
2463 if ( $useESI && $wgResourceLoaderUseESI ) {
2464 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2465 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2466 $link = Html
::inlineStyle( $esi );
2468 $link = Html
::inlineScript( $esi );
2471 // Automatically select style/script elements
2472 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2473 $link = Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) );
2475 $link = Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) );
2479 if( $group == 'noscript' ){
2480 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2482 $links .= $link . "\n";
2489 * JS stuff to put in the <head>. This is the startup module, config
2490 * vars and modules marked with position 'top'
2492 * @param $sk Skin object to use
2493 * @return String: HTML fragment
2495 function getHeadScripts( Skin
$sk ) {
2496 // Startup - this will immediately load jquery and mediawiki modules
2497 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2499 // Load config before anything else
2500 $scripts .= Html
::inlineScript(
2501 ResourceLoader
::makeLoaderConditionalScript(
2502 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2506 // Script and Messages "only" requests marked for top inclusion
2507 // Messages should go first
2508 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2509 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2511 // Modules requests - let the client calculate dependencies and batch requests as it likes
2512 // Only load modules that have marked themselves for loading at the top
2513 $modules = $this->getModules( true, 'top' );
2515 $scripts .= Html
::inlineScript(
2516 ResourceLoader
::makeLoaderConditionalScript(
2517 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) ) .
2518 Xml
::encodeJsCall( 'mw.loader.go', array() )
2527 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2528 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2530 function getBottomScripts( Skin
$sk ) {
2531 global $wgUseSiteJs, $wgAllowUserJs;
2533 // Script and Messages "only" requests marked for bottom inclusion
2534 // Messages should go first
2535 $scripts = $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2536 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2538 // Modules requests - let the client calculate dependencies and batch requests as it likes
2539 // Only load modules that have marked themselves for loading at the bottom
2540 $modules = $this->getModules( true, 'bottom' );
2542 $scripts .= Html
::inlineScript(
2543 ResourceLoader
::makeLoaderConditionalScript(
2544 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) ) .
2545 // the go() call is unnecessary if we inserted top modules, but we don't know for sure that we did
2546 Xml
::encodeJsCall( 'mw.loader.go', array() )
2552 $scripts .= "\n" . $this->mScripts
;
2554 $userScripts = array( 'user.options' );
2556 // Add site JS if enabled
2557 if ( $wgUseSiteJs ) {
2558 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2559 if( $this->getUser()->isLoggedIn() ){
2560 $userScripts[] = 'user.groups';
2564 // Add user JS if enabled
2565 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2566 $action = $this->getRequest()->getVal( 'action', 'view' );
2567 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2568 # XXX: additional security check/prompt?
2569 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2571 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2572 # User:Me/Vector.js, and vice versa (bug26283)
2573 $userScripts[] = 'user';
2576 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule
::TYPE_SCRIPTS
);
2582 * Get an array containing global JS variables
2584 * Do not add things here which can be evaluated in
2585 * ResourceLoaderStartupScript - in other words, without state.
2586 * You will only be adding bloat to the page and causing page caches to
2587 * have to be purged on configuration changes.
2589 protected function getJSVars() {
2590 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2592 $title = $this->getTitle();
2593 $ns = $title->getNamespace();
2594 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2595 if ( $ns == NS_SPECIAL
) {
2596 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2598 $canonicalName = false; # bug 21115
2602 'wgCanonicalNamespace' => $nsname,
2603 'wgCanonicalSpecialPageName' => $canonicalName,
2604 'wgNamespaceNumber' => $title->getNamespace(),
2605 'wgPageName' => $title->getPrefixedDBKey(),
2606 'wgTitle' => $title->getText(),
2607 'wgCurRevisionId' => $title->getLatestRevID(),
2608 'wgArticleId' => $title->getArticleId(),
2609 'wgIsArticle' => $this->isArticle(),
2610 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2611 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2612 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2613 'wgCategories' => $this->getCategories(),
2614 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2616 if ( $wgContLang->hasVariants() ) {
2617 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2619 foreach ( $title->getRestrictionTypes() as $type ) {
2620 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2622 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2623 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2626 // Allow extensions to add their custom variables to the global JS variables
2627 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2633 * @return string HTML tag links to be put in the header.
2635 public function getHeadLinks( Skin
$sk, $addContentType = false ) {
2636 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2637 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType, $wgOutputEncoding,
2638 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2639 $wgEnableDublinCoreRdf, $wgEnableCreativeCommonsRdf,
2640 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2641 $wgRightsPage, $wgRightsUrl;
2645 if ( $addContentType ) {
2647 # More succinct than <meta http-equiv=Content-Type>, has the
2649 $tags[] = Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) );
2651 $tags[] = Html
::element( 'meta', array(
2652 'http-equiv' => 'Content-Type',
2653 'content' => "$wgMimeType; charset=$wgOutputEncoding"
2655 $tags[] = Html
::element( 'meta', array( // bug 15835
2656 'http-equiv' => 'Content-Style-Type',
2657 'content' => 'text/css'
2662 $tags[] = Html
::element( 'meta', array(
2663 'name' => 'generator',
2664 'content' => "MediaWiki $wgVersion",
2667 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2668 if( $p !== 'index,follow' ) {
2669 // http://www.robotstxt.org/wc/meta-user.html
2670 // Only show if it's different from the default robots policy
2671 $tags[] = Html
::element( 'meta', array(
2677 if ( count( $this->mKeywords
) > 0 ) {
2679 "/<.*?" . ">/" => '',
2682 $tags[] = Html
::element( 'meta', array(
2683 'name' => 'keywords',
2684 'content' => preg_replace(
2685 array_keys( $strip ),
2686 array_values( $strip ),
2687 implode( ',', $this->mKeywords
)
2692 foreach ( $this->mMetatags
as $tag ) {
2693 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2695 $tag[0] = substr( $tag[0], 5 );
2699 $tags[] = Html
::element( 'meta',
2702 'content' => $tag[1]
2707 foreach ( $this->mLinktags
as $tag ) {
2708 $tags[] = Html
::element( 'link', $tag );
2711 # Universal edit button
2712 if ( $wgUniversalEditButton ) {
2713 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2714 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2715 // Original UniversalEditButton
2716 $msg = wfMsg( 'edit' );
2717 $tags[] = Html
::element( 'link', array(
2718 'rel' => 'alternate',
2719 'type' => 'application/x-wiki',
2721 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2723 // Alternate edit link
2724 $tags[] = Html
::element( 'link', array(
2727 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2732 # Generally the order of the favicon and apple-touch-icon links
2733 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2734 # uses whichever one appears later in the HTML source. Make sure
2735 # apple-touch-icon is specified first to avoid this.
2736 if ( $wgAppleTouchIcon !== false ) {
2737 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2740 if ( $wgFavicon !== false ) {
2741 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2744 # OpenSearch description link
2745 $tags[] = Html
::element( 'link', array(
2747 'type' => 'application/opensearchdescription+xml',
2748 'href' => wfScript( 'opensearch_desc' ),
2749 'title' => wfMsgForContent( 'opensearch-desc' ),
2752 if ( $wgEnableAPI ) {
2753 # Real Simple Discovery link, provides auto-discovery information
2754 # for the MediaWiki API (and potentially additional custom API
2755 # support such as WordPress or Twitter-compatible APIs for a
2756 # blogging extension, etc)
2757 $tags[] = Html
::element( 'link', array(
2759 'type' => 'application/rsd+xml',
2760 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2765 # - Creative Commons
2766 # See http://wiki.creativecommons.org/Extend_Metadata.
2768 # Use hreflang to specify canonical and alternate links
2769 # See http://www.google.com/support/webmasters/bin/answer.py?answer=189077
2770 if ( $this->isArticleRelated() ) {
2771 # note: buggy CC software only reads first "meta" link
2772 if ( $wgEnableCreativeCommonsRdf ) {
2773 $tags[] = Html
::element( 'link', array(
2774 'rel' => $this->getMetadataAttribute(),
2775 'title' => 'Creative Commons',
2776 'type' => 'application/rdf+xml',
2777 'href' => $this->getTitle()->getLocalURL( 'action=creativecommons' ) )
2781 if ( $wgEnableDublinCoreRdf ) {
2782 $tags[] = Html
::element( 'link', array(
2783 'rel' => $this->getMetadataAttribute(),
2784 'title' => 'Dublin Core',
2785 'type' => 'application/rdf+xml',
2786 'href' => $this->getTitle()->getLocalURL( 'action=dublincore' ) )
2792 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2793 && $wgContLang->hasVariants() ) {
2795 $urlvar = $wgContLang->getURLVariant();
2798 $variants = $wgContLang->getVariants();
2799 foreach ( $variants as $_v ) {
2800 $tags[] = Html
::element( 'link', array(
2801 'rel' => 'alternate',
2803 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2807 $tags[] = Html
::element( 'link', array(
2808 'rel' => 'canonical',
2809 'href' => $this->getTitle()->getFullURL() )
2816 if ( $wgRightsPage ) {
2817 $copy = Title
::newFromText( $wgRightsPage );
2820 $copyright = $copy->getLocalURL();
2824 if ( !$copyright && $wgRightsUrl ) {
2825 $copyright = $wgRightsUrl;
2829 $tags[] = Html
::element( 'link', array(
2830 'rel' => 'copyright',
2831 'href' => $copyright )
2837 foreach( $this->getSyndicationLinks() as $format => $link ) {
2838 # Use the page name for the title (accessed through $wgTitle since
2839 # there's no other way). In principle, this could lead to issues
2840 # with having the same name for different feeds corresponding to
2841 # the same page, but we can't avoid that at this low a level.
2843 $tags[] = $this->feedLink(
2846 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2847 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2851 # Recent changes feed should appear on every page (except recentchanges,
2852 # that would be redundant). Put it after the per-page feed to avoid
2853 # changing existing behavior. It's still available, probably via a
2854 # menu in your browser. Some sites might have a different feed they'd
2855 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2856 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2857 # If so, use it instead.
2859 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2861 if ( $wgOverrideSiteFeed ) {
2862 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2863 $tags[] = $this->feedLink(
2865 htmlspecialchars( $feedUrl ),
2866 wfMsg( "site-{$type}-feed", $wgSitename )
2869 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2870 foreach ( $wgAdvertisedFeedTypes as $format ) {
2871 $tags[] = $this->feedLink(
2873 $rctitle->getLocalURL( "feed={$format}" ),
2874 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2879 return implode( "\n", $tags );
2883 * Generate a <link rel/> for a feed.
2885 * @param $type String: feed type
2886 * @param $url String: URL to the feed
2887 * @param $text String: value of the "title" attribute
2888 * @return String: HTML fragment
2890 private function feedLink( $type, $url, $text ) {
2891 return Html
::element( 'link', array(
2892 'rel' => 'alternate',
2893 'type' => "application/$type+xml",
2900 * Add a local or specified stylesheet, with the given media options.
2901 * Meant primarily for internal use...
2903 * @param $style String: URL to the file
2904 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2905 * @param $condition String: for IE conditional comments, specifying an IE version
2906 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2908 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2910 // Even though we expect the media type to be lowercase, but here we
2911 // force it to lowercase to be safe.
2913 $options['media'] = $media;
2916 $options['condition'] = $condition;
2919 $options['dir'] = $dir;
2921 $this->styles
[$style] = $options;
2925 * Adds inline CSS styles
2926 * @param $style_css Mixed: inline CSS
2928 public function addInlineStyle( $style_css ){
2929 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2933 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2934 * These will be applied to various media & IE conditionals.
2935 * @param $sk Skin object
2937 public function buildCssLinks( $sk ) {
2939 // Add ResourceLoader styles
2940 // Split the styles into four groups
2941 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2942 $resourceLoader = $this->getResourceLoader();
2943 foreach ( $this->getModuleStyles() as $name ) {
2944 $group = $resourceLoader->getModule( $name )->getGroup();
2945 // Modules in groups named "other" or anything different than "user", "site" or "private"
2946 // will be placed in the "other" group
2947 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2950 // We want site, private and user styles to override dynamically added styles from modules, but we want
2951 // dynamically added styles to override statically added styles from other modules. So the order
2952 // has to be other, dynamic, site, private, user
2953 // Add statically added styles for other modules
2954 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
2955 // Add normal styles added through addStyle()/addInlineStyle() here
2956 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2957 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2958 // We use a <meta> tag with a made-up name for this because that's valid HTML
2959 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
2961 // Add site, private and user styles
2962 // 'private' at present only contains user.options, so put that before 'user'
2963 // Any future private modules will likely have a similar user-specific character
2964 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
2965 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
2966 ResourceLoaderModule
::TYPE_STYLES
2972 public function buildCssLinksArray() {
2974 foreach( $this->styles
as $file => $options ) {
2975 $link = $this->styleLink( $file, $options );
2977 $links[$file] = $link;
2984 * Generate \<link\> tags for stylesheets
2986 * @param $style String: URL to the file
2987 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2989 * @return String: HTML fragment
2991 protected function styleLink( $style, $options ) {
2992 if( isset( $options['dir'] ) ) {
2993 $siteDir = wfUILang()->getDir();
2994 if( $siteDir != $options['dir'] ) {
2999 if( isset( $options['media'] ) ) {
3000 $media = self
::transformCssMedia( $options['media'] );
3001 if( is_null( $media ) ) {
3008 if( substr( $style, 0, 1 ) == '/' ||
3009 substr( $style, 0, 5 ) == 'http:' ||
3010 substr( $style, 0, 6 ) == 'https:' ) {
3013 global $wgStylePath, $wgStyleVersion;
3014 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3017 $link = Html
::linkedStyle( $url, $media );
3019 if( isset( $options['condition'] ) ) {
3020 $condition = htmlspecialchars( $options['condition'] );
3021 $link = "<!--[if $condition]>$link<![endif]-->";
3027 * Transform "media" attribute based on request parameters
3029 * @param $media String: current value of the "media" attribute
3030 * @return String: modified value of the "media" attribute
3032 public static function transformCssMedia( $media ) {
3033 global $wgRequest, $wgHandheldForIPhone;
3035 // Switch in on-screen display for media testing
3037 'printable' => 'print',
3038 'handheld' => 'handheld',
3040 foreach( $switches as $switch => $targetMedia ) {
3041 if( $wgRequest->getBool( $switch ) ) {
3042 if( $media == $targetMedia ) {
3044 } elseif( $media == 'screen' ) {
3050 // Expand longer media queries as iPhone doesn't grok 'handheld'
3051 if( $wgHandheldForIPhone ) {
3052 $mediaAliases = array(
3053 'screen' => 'screen and (min-device-width: 481px)',
3054 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3057 if( isset( $mediaAliases[$media] ) ) {
3058 $media = $mediaAliases[$media];
3066 * Add a wikitext-formatted message to the output.
3067 * This is equivalent to:
3069 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3071 public function addWikiMsg( /*...*/ ) {
3072 $args = func_get_args();
3073 $name = array_shift( $args );
3074 $this->addWikiMsgArray( $name, $args );
3078 * Add a wikitext-formatted message to the output.
3079 * Like addWikiMsg() except the parameters are taken as an array
3080 * instead of a variable argument list.
3082 * $options is passed through to wfMsgExt(), see that function for details.
3084 public function addWikiMsgArray( $name, $args, $options = array() ) {
3085 $options[] = 'parse';
3086 $text = wfMsgExt( $name, $options, $args );
3087 $this->addHTML( $text );
3091 * This function takes a number of message/argument specifications, wraps them in
3092 * some overall structure, and then parses the result and adds it to the output.
3094 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3095 * on. The subsequent arguments may either be strings, in which case they are the
3096 * message names, or arrays, in which case the first element is the message name,
3097 * and subsequent elements are the parameters to that message.
3099 * The special named parameter 'options' in a message specification array is passed
3100 * through to the $options parameter of wfMsgExt().
3102 * Don't use this for messages that are not in users interface language.
3106 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3110 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3112 * The newline after opening div is needed in some wikitext. See bug 19226.
3114 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3115 $msgSpecs = func_get_args();
3116 array_shift( $msgSpecs );
3117 $msgSpecs = array_values( $msgSpecs );
3119 foreach ( $msgSpecs as $n => $spec ) {
3121 if ( is_array( $spec ) ) {
3123 $name = array_shift( $args );
3124 if ( isset( $args['options'] ) ) {
3125 $options = $args['options'];
3126 unset( $args['options'] );
3132 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3134 $this->addWikiText( $s );
3138 * Include jQuery core. Use this to avoid loading it multiple times
3139 * before we get a usable script loader.
3141 * @param $modules Array: list of jQuery modules which should be loaded
3142 * @return Array: the list of modules which were not loaded.
3144 * @deprecated since 1.17
3146 public function includeJQuery( $modules = array() ) {