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 * Remove one or more modules recognized by the resource loader.
446 * @param $modules Mixed: module name (string) or array of module names
448 public function removeModules( $modules ) {
449 $this->mModules
= array_diff( $this->mModules
, (array)$modules );
453 * Removes all modules for resource loader.
455 public function resetModules() {
456 $this->mModules
= array();
460 * Get the list of module JS to include on this page
465 * @return array of module names
467 public function getModuleScripts( $filter = false, $position = null ) {
468 return $this->getModules( $filter, $position, 'mModuleScripts' );
472 * Add only JS of one or more modules recognized by the resource loader. Module
473 * scripts added through this function will be loaded by the resource loader when
476 * @param $modules Mixed: module name (string) or array of module names
478 public function addModuleScripts( $modules ) {
479 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
483 * Get the list of module CSS to include on this page
488 * @return Array of module names
490 public function getModuleStyles( $filter = false, $position = null ) {
491 return $this->getModules( $filter, $position, 'mModuleStyles' );
495 * Add only CSS of one or more modules recognized by the resource loader. Module
496 * styles added through this function will be loaded by the resource loader when
499 * @param $modules Mixed: module name (string) or array of module names
501 public function addModuleStyles( $modules ) {
502 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
506 * Get the list of module messages to include on this page
511 * @return Array of module names
513 public function getModuleMessages( $filter = false, $position = null ) {
514 return $this->getModules( $filter, $position, 'mModuleMessages' );
518 * Add only messages of one or more modules recognized by the resource loader.
519 * Module messages added through this function will be loaded by the resource
520 * loader when the page loads.
522 * @param $modules Mixed: module name (string) or array of module names
524 public function addModuleMessages( $modules ) {
525 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
529 * Get all header items in a string
533 function getHeadItems() {
535 foreach ( $this->mHeadItems
as $item ) {
542 * Add or replace an header item to the output
544 * @param $name String: item name
545 * @param $value String: raw HTML
547 public function addHeadItem( $name, $value ) {
548 $this->mHeadItems
[$name] = $value;
552 * Check if the header item $name is already set
554 * @param $name String: item name
557 public function hasHeadItem( $name ) {
558 return isset( $this->mHeadItems
[$name] );
562 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
564 * @param $tag String: value of "ETag" header
566 function setETag( $tag ) {
571 * Set whether the output should only contain the body of the article,
572 * without any skin, sidebar, etc.
573 * Used e.g. when calling with "action=render".
575 * @param $only Boolean: whether to output only the body of the article
577 public function setArticleBodyOnly( $only ) {
578 $this->mArticleBodyOnly
= $only;
582 * Return whether the output will contain only the body of the article
586 public function getArticleBodyOnly() {
587 return $this->mArticleBodyOnly
;
591 * checkLastModified tells the client to use the client-cached page if
592 * possible. If sucessful, the OutputPage is disabled so that
593 * any future call to OutputPage->output() have no effect.
595 * Side effect: sets mLastModified for Last-Modified header
597 * @param $timestamp string
599 * @return Boolean: true iff cache-ok headers was sent.
601 public function checkLastModified( $timestamp ) {
602 global $wgCachePages, $wgCacheEpoch;
604 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
605 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
608 if( !$wgCachePages ) {
609 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
612 if( $this->getUser()->getOption( 'nocache' ) ) {
613 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
617 $timestamp = wfTimestamp( TS_MW
, $timestamp );
618 $modifiedTimes = array(
619 'page' => $timestamp,
620 'user' => $this->getUser()->getTouched(),
621 'epoch' => $wgCacheEpoch
623 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
625 $maxModified = max( $modifiedTimes );
626 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
628 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
629 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
635 foreach ( $modifiedTimes as $name => $value ) {
636 if ( $info !== '' ) {
639 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
642 # IE sends sizes after the date like this:
643 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
644 # this breaks strtotime().
645 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
647 wfSuppressWarnings(); // E_STRICT system time bitching
648 $clientHeaderTime = strtotime( $clientHeader );
650 if ( !$clientHeaderTime ) {
651 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
654 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
656 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
657 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
658 wfDebug( __METHOD__
. ": effective Last-Modified: " .
659 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
660 if( $clientHeaderTime < $maxModified ) {
661 wfDebug( __METHOD__
. ": STALE, $info\n", false );
666 # Give a 304 response code and disable body output
667 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
668 ini_set( 'zlib.output_compression', 0 );
669 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
670 $this->sendCacheControl();
673 // Don't output a compressed blob when using ob_gzhandler;
674 // it's technically against HTTP spec and seems to confuse
675 // Firefox when the response gets split over two packets.
676 wfClearOutputBuffers();
682 * Override the last modified timestamp
684 * @param $timestamp String: new timestamp, in a format readable by
687 public function setLastModified( $timestamp ) {
688 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
692 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
694 * @param $policy String: the literal string to output as the contents of
695 * the meta tag. Will be parsed according to the spec and output in
699 public function setRobotPolicy( $policy ) {
700 $policy = Article
::formatRobotPolicy( $policy );
702 if( isset( $policy['index'] ) ) {
703 $this->setIndexPolicy( $policy['index'] );
705 if( isset( $policy['follow'] ) ) {
706 $this->setFollowPolicy( $policy['follow'] );
711 * Set the index policy for the page, but leave the follow policy un-
714 * @param $policy string Either 'index' or 'noindex'.
717 public function setIndexPolicy( $policy ) {
718 $policy = trim( $policy );
719 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
720 $this->mIndexPolicy
= $policy;
725 * Set the follow policy for the page, but leave the index policy un-
728 * @param $policy String: either 'follow' or 'nofollow'.
731 public function setFollowPolicy( $policy ) {
732 $policy = trim( $policy );
733 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
734 $this->mFollowPolicy
= $policy;
739 * Set the new value of the "action text", this will be added to the
740 * "HTML title", separated from it with " - ".
742 * @param $text String: new value of the "action text"
744 public function setPageTitleActionText( $text ) {
745 $this->mPageTitleActionText
= $text;
749 * Get the value of the "action text"
753 public function getPageTitleActionText() {
754 if ( isset( $this->mPageTitleActionText
) ) {
755 return $this->mPageTitleActionText
;
760 * "HTML title" means the contents of <title>.
761 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
763 * @param $name string
765 public function setHTMLTitle( $name ) {
766 $this->mHTMLtitle
= $name;
770 * Return the "HTML title", i.e. the content of the <title> tag.
774 public function getHTMLTitle() {
775 return $this->mHTMLtitle
;
779 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
780 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
781 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
782 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
784 * @param $name string
786 public function setPageTitle( $name ) {
787 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
788 # but leave "<i>foobar</i>" alone
789 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
790 $this->mPagetitle
= $nameWithTags;
792 # change "<i>foo&bar</i>" to "foo&bar"
793 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
797 * Return the "page title", i.e. the content of the \<h1\> tag.
801 public function getPageTitle() {
802 return $this->mPagetitle
;
806 * Set the Title object to use
808 * @param $t Title object
810 public function setTitle( Title
$t ) {
811 $this->getContext()->setTitle( $t );
816 * Replace the subtile with $str
818 * @param $str String: new value of the subtitle
820 public function setSubtitle( $str ) {
821 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
825 * Add $str to the subtitle
827 * @param $str String to add to the subtitle
829 public function appendSubtitle( $str ) {
830 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
838 public function getSubtitle() {
839 return $this->mSubtitle
;
843 * Set the page as printable, i.e. it'll be displayed with with all
844 * print styles included
846 public function setPrintable() {
847 $this->mPrintable
= true;
851 * Return whether the page is "printable"
855 public function isPrintable() {
856 return $this->mPrintable
;
860 * Disable output completely, i.e. calling output() will have no effect
862 public function disable() {
863 $this->mDoNothing
= true;
867 * Return whether the output will be completely disabled
871 public function isDisabled() {
872 return $this->mDoNothing
;
876 * Show an "add new section" link?
880 public function showNewSectionLink() {
881 return $this->mNewSectionLink
;
885 * Forcibly hide the new section link?
889 public function forceHideNewSectionLink() {
890 return $this->mHideNewSectionLink
;
894 * Add or remove feed links in the page header
895 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
896 * for the new version
899 * @param $show Boolean: true: add default feeds, false: remove all feeds
901 public function setSyndicated( $show = true ) {
903 $this->setFeedAppendQuery( false );
905 $this->mFeedLinks
= array();
910 * Add default feeds to the page header
911 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
912 * for the new version
915 * @param $val String: query to append to feed links or false to output
918 public function setFeedAppendQuery( $val ) {
919 global $wgAdvertisedFeedTypes;
921 $this->mFeedLinks
= array();
923 foreach ( $wgAdvertisedFeedTypes as $type ) {
924 $query = "feed=$type";
925 if ( is_string( $val ) ) {
926 $query .= '&' . $val;
928 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
933 * Add a feed link to the page header
935 * @param $format String: feed type, should be a key of $wgFeedClasses
936 * @param $href String: URL
938 public function addFeedLink( $format, $href ) {
939 global $wgAdvertisedFeedTypes;
941 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
942 $this->mFeedLinks
[$format] = $href;
947 * Should we output feed links for this page?
950 public function isSyndicated() {
951 return count( $this->mFeedLinks
) > 0;
955 * Return URLs for each supported syndication format for this page.
956 * @return array associating format keys with URLs
958 public function getSyndicationLinks() {
959 return $this->mFeedLinks
;
963 * Will currently always return null
967 public function getFeedAppendQuery() {
968 return $this->mFeedLinksAppendQuery
;
972 * Set whether the displayed content is related to the source of the
973 * corresponding article on the wiki
974 * Setting true will cause the change "article related" toggle to true
978 public function setArticleFlag( $v ) {
979 $this->mIsarticle
= $v;
981 $this->mIsArticleRelated
= $v;
986 * Return whether the content displayed page is related to the source of
987 * the corresponding article on the wiki
991 public function isArticle() {
992 return $this->mIsarticle
;
996 * Set whether this page is related an article on the wiki
997 * Setting false will cause the change of "article flag" toggle to false
1001 public function setArticleRelated( $v ) {
1002 $this->mIsArticleRelated
= $v;
1004 $this->mIsarticle
= false;
1009 * Return whether this page is related an article on the wiki
1013 public function isArticleRelated() {
1014 return $this->mIsArticleRelated
;
1018 * Add new language links
1020 * @param $newLinkArray Associative array mapping language code to the page
1023 public function addLanguageLinks( $newLinkArray ) {
1024 $this->mLanguageLinks +
= $newLinkArray;
1028 * Reset the language links and add new language links
1030 * @param $newLinkArray Associative array mapping language code to the page
1033 public function setLanguageLinks( $newLinkArray ) {
1034 $this->mLanguageLinks
= $newLinkArray;
1038 * Get the list of language links
1040 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1042 public function getLanguageLinks() {
1043 return $this->mLanguageLinks
;
1047 * Add an array of categories, with names in the keys
1049 * @param $categories Array mapping category name => sort key
1051 public function addCategoryLinks( $categories ) {
1054 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1058 # Add the links to a LinkBatch
1059 $arr = array( NS_CATEGORY
=> $categories );
1060 $lb = new LinkBatch
;
1061 $lb->setArray( $arr );
1063 # Fetch existence plus the hiddencat property
1064 $dbr = wfGetDB( DB_SLAVE
);
1065 $res = $dbr->select( array( 'page', 'page_props' ),
1066 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1067 $lb->constructSet( 'page', $dbr ),
1070 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1073 # Add the results to the link cache
1074 $lb->addResultToCache( LinkCache
::singleton(), $res );
1076 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1077 $categories = array_combine(
1078 array_keys( $categories ),
1079 array_fill( 0, count( $categories ), 'normal' )
1082 # Mark hidden categories
1083 foreach ( $res as $row ) {
1084 if ( isset( $row->pp_value
) ) {
1085 $categories[$row->page_title
] = 'hidden';
1089 # Add the remaining categories to the skin
1090 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1091 foreach ( $categories as $category => $type ) {
1092 $origcategory = $category;
1093 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1094 $wgContLang->findVariantLink( $category, $title, true );
1095 if ( $category != $origcategory ) {
1096 if ( array_key_exists( $category, $categories ) ) {
1100 $text = $wgContLang->convertHtml( $title->getText() );
1101 $this->mCategories
[] = $title->getText();
1102 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1108 * Reset the category links (but not the category list) and add $categories
1110 * @param $categories Array mapping category name => sort key
1112 public function setCategoryLinks( $categories ) {
1113 $this->mCategoryLinks
= array();
1114 $this->addCategoryLinks( $categories );
1118 * Get the list of category links, in a 2-D array with the following format:
1119 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1120 * hidden categories) and $link a HTML fragment with a link to the category
1125 public function getCategoryLinks() {
1126 return $this->mCategoryLinks
;
1130 * Get the list of category names this page belongs to
1132 * @return Array of strings
1134 public function getCategories() {
1135 return $this->mCategories
;
1139 * Do not allow scripts which can be modified by wiki users to load on this page;
1140 * only allow scripts bundled with, or generated by, the software.
1142 public function disallowUserJs() {
1143 $this->reduceAllowedModules(
1144 ResourceLoaderModule
::TYPE_SCRIPTS
,
1145 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1150 * Return whether user JavaScript is allowed for this page
1151 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1152 * trustworthiness is identified and enforced automagically.
1155 public function isUserJsAllowed() {
1156 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1160 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1161 * @see ResourceLoaderModule::$origin
1162 * @param $type String ResourceLoaderModule TYPE_ constant
1163 * @return Int ResourceLoaderModule ORIGIN_ class constant
1165 public function getAllowedModules( $type ){
1166 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1167 return min( array_values( $this->mAllowedModules
) );
1169 return isset( $this->mAllowedModules
[$type] )
1170 ?
$this->mAllowedModules
[$type]
1171 : ResourceLoaderModule
::ORIGIN_ALL
;
1176 * Set the highest level of CSS/JS untrustworthiness allowed
1177 * @param $type String ResourceLoaderModule TYPE_ constant
1178 * @param $level Int ResourceLoaderModule class constant
1180 public function setAllowedModules( $type, $level ){
1181 $this->mAllowedModules
[$type] = $level;
1185 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1186 * @param $type String
1187 * @param $level Int ResourceLoaderModule class constant
1189 public function reduceAllowedModules( $type, $level ){
1190 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1194 * Prepend $text to the body HTML
1196 * @param $text String: HTML
1198 public function prependHTML( $text ) {
1199 $this->mBodytext
= $text . $this->mBodytext
;
1203 * Append $text to the body HTML
1205 * @param $text String: HTML
1207 public function addHTML( $text ) {
1208 $this->mBodytext
.= $text;
1212 * Clear the body HTML
1214 public function clearHTML() {
1215 $this->mBodytext
= '';
1221 * @return String: HTML
1223 public function getHTML() {
1224 return $this->mBodytext
;
1228 * Add $text to the debug output
1230 * @param $text String: debug text
1232 public function debug( $text ) {
1233 $this->mDebugtext
.= $text;
1237 * Get/set the ParserOptions object to use for wikitext parsing
1239 * @param $options either the ParserOption to use or null to only get the
1240 * current ParserOption object
1241 * @return ParserOptions object
1243 public function parserOptions( $options = null ) {
1244 if ( !$this->mParserOptions
) {
1245 $this->mParserOptions
= new ParserOptions
;
1246 $this->mParserOptions
->setEditSection( false );
1248 return wfSetVar( $this->mParserOptions
, $options );
1252 * Set the revision ID which will be seen by the wiki text parser
1253 * for things such as embedded {{REVISIONID}} variable use.
1255 * @param $revid Mixed: an positive integer, or null
1256 * @return Mixed: previous value
1258 public function setRevisionId( $revid ) {
1259 $val = is_null( $revid ) ?
null : intval( $revid );
1260 return wfSetVar( $this->mRevisionId
, $val );
1264 * Get the displayed revision ID
1268 public function getRevisionId() {
1269 return $this->mRevisionId
;
1273 * Set the displayed file version
1275 * @param $file File|false
1276 * @return Mixed: previous value
1278 public function setFileVersion( $file ) {
1280 if ( $file instanceof File
&& $file->exists() ) {
1281 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1283 return wfSetVar( $this->mFileVersion
, $val, true );
1287 * Get the displayed file version
1289 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1291 public function getFileVersion() {
1292 return $this->mFileVersion
;
1296 * Get the templates used on this page
1298 * @return Array (namespace => dbKey => revId)
1301 public function getTemplateIds() {
1302 return $this->mTemplateIds
;
1306 * Get the files used on this page
1308 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1311 public function getImageTimeKeys() {
1312 return $this->mImageTimeKeys
;
1316 * Convert wikitext to HTML and add it to the buffer
1317 * Default assumes that the current page title will be used.
1319 * @param $text String
1320 * @param $linestart Boolean: is this the start of a line?
1322 public function addWikiText( $text, $linestart = true ) {
1323 $title = $this->getTitle(); // Work arround E_STRICT
1324 $this->addWikiTextTitle( $text, $title, $linestart );
1328 * Add wikitext with a custom Title object
1330 * @param $text String: wikitext
1331 * @param $title Title object
1332 * @param $linestart Boolean: is this the start of a line?
1334 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1335 $this->addWikiTextTitle( $text, $title, $linestart );
1339 * Add wikitext with a custom Title object and
1341 * @param $text String: wikitext
1342 * @param $title Title object
1343 * @param $linestart Boolean: is this the start of a line?
1345 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1346 $this->addWikiTextTitle( $text, $title, $linestart, true );
1350 * Add wikitext with tidy enabled
1352 * @param $text String: wikitext
1353 * @param $linestart Boolean: is this the start of a line?
1355 public function addWikiTextTidy( $text, $linestart = true ) {
1356 $title = $this->getTitle();
1357 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1361 * Add wikitext with a custom Title object
1363 * @param $text String: wikitext
1364 * @param $title Title object
1365 * @param $linestart Boolean: is this the start of a line?
1366 * @param $tidy Boolean: whether to use tidy
1368 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1371 wfProfileIn( __METHOD__
);
1373 wfIncrStats( 'pcache_not_possible' );
1375 $popts = $this->parserOptions();
1376 $oldTidy = $popts->setTidy( $tidy );
1378 $parserOutput = $wgParser->parse(
1379 $text, $title, $popts,
1380 $linestart, true, $this->mRevisionId
1383 $popts->setTidy( $oldTidy );
1385 $this->addParserOutput( $parserOutput );
1387 wfProfileOut( __METHOD__
);
1391 * Add a ParserOutput object, but without Html
1393 * @param $parserOutput ParserOutput object
1395 public function addParserOutputNoText( &$parserOutput ) {
1396 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1397 $this->addCategoryLinks( $parserOutput->getCategories() );
1398 $this->mNewSectionLink
= $parserOutput->getNewSection();
1399 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1401 $this->mParseWarnings
= $parserOutput->getWarnings();
1402 if ( !$parserOutput->isCacheable() ) {
1403 $this->enableClientCache( false );
1405 $this->mNoGallery
= $parserOutput->getNoGallery();
1406 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1407 $this->addModules( $parserOutput->getModules() );
1409 // Template versioning...
1410 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1411 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1412 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1414 $this->mTemplateIds
[$ns] = $dbks;
1417 // File versioning...
1418 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1419 $this->mImageTimeKeys
[$dbk] = $data;
1422 // Hooks registered in the object
1423 global $wgParserOutputHooks;
1424 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1425 list( $hookName, $data ) = $hookInfo;
1426 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1427 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1431 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1435 * Add a ParserOutput object
1437 * @param $parserOutput ParserOutput
1439 function addParserOutput( &$parserOutput ) {
1440 $this->addParserOutputNoText( $parserOutput );
1441 $text = $parserOutput->getText();
1442 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1443 $this->addHTML( $text );
1448 * Add the output of a QuickTemplate to the output buffer
1450 * @param $template QuickTemplate
1452 public function addTemplate( &$template ) {
1454 $template->execute();
1455 $this->addHTML( ob_get_contents() );
1460 * Parse wikitext and return the HTML.
1462 * @param $text String
1463 * @param $linestart Boolean: is this the start of a line?
1464 * @param $interface Boolean: use interface language ($wgLang instead of
1465 * $wgContLang) while parsing language sensitive magic
1466 * words like GRAMMAR and PLURAL
1467 * @param $language Language object: target language object, will override
1469 * @return String: HTML
1471 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1472 // Check one for one common cause for parser state resetting
1473 $callers = wfGetAllCallers( 10 );
1474 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1475 throw new MWException( "wfMsg* function with parsing cannot be used " .
1476 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1481 if( is_null( $this->getTitle() ) ) {
1482 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1485 $popts = $this->parserOptions();
1487 $popts->setInterfaceMessage( true );
1489 if ( $language !== null ) {
1490 $oldLang = $popts->setTargetLanguage( $language );
1493 $parserOutput = $wgParser->parse(
1494 $text, $this->getTitle(), $popts,
1495 $linestart, true, $this->mRevisionId
1499 $popts->setInterfaceMessage( false );
1501 if ( $language !== null ) {
1502 $popts->setTargetLanguage( $oldLang );
1505 return $parserOutput->getText();
1509 * Parse wikitext, strip paragraphs, and return the HTML.
1511 * @param $text String
1512 * @param $linestart Boolean: is this the start of a line?
1513 * @param $interface Boolean: use interface language ($wgLang instead of
1514 * $wgContLang) while parsing language sensitive magic
1515 * words like GRAMMAR and PLURAL
1516 * @return String: HTML
1518 public function parseInline( $text, $linestart = true, $interface = false ) {
1519 $parsed = $this->parse( $text, $linestart, $interface );
1522 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1530 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1532 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1534 public function setSquidMaxage( $maxage ) {
1535 $this->mSquidMaxage
= $maxage;
1539 * Use enableClientCache(false) to force it to send nocache headers
1541 * @param $state bool
1545 public function enableClientCache( $state ) {
1546 return wfSetVar( $this->mEnableClientCache
, $state );
1550 * Get the list of cookies that will influence on the cache
1554 function getCacheVaryCookies() {
1555 global $wgCookiePrefix, $wgCacheVaryCookies;
1557 if ( $cookies === null ) {
1558 $cookies = array_merge(
1560 "{$wgCookiePrefix}Token",
1561 "{$wgCookiePrefix}LoggedOut",
1566 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1572 * Return whether this page is not cacheable because "useskin" or "uselang"
1573 * URL parameters were passed.
1577 function uncacheableBecauseRequestVars() {
1578 $request = $this->getRequest();
1579 return $request->getText( 'useskin', false ) === false
1580 && $request->getText( 'uselang', false ) === false;
1584 * Check if the request has a cache-varying cookie header
1585 * If it does, it's very important that we don't allow public caching
1589 function haveCacheVaryCookies() {
1590 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1591 if ( $cookieHeader === false ) {
1594 $cvCookies = $this->getCacheVaryCookies();
1595 foreach ( $cvCookies as $cookieName ) {
1596 # Check for a simple string match, like the way squid does it
1597 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1598 wfDebug( __METHOD__
. ": found $cookieName\n" );
1602 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1607 * Add an HTTP header that will influence on the cache
1609 * @param $header String: header name
1610 * @param $option Array|null
1611 * @todo FIXME: Document the $option parameter; it appears to be for
1612 * X-Vary-Options but what format is acceptable?
1614 public function addVaryHeader( $header, $option = null ) {
1615 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1616 $this->mVaryHeader
[$header] = (array)$option;
1617 } elseif( is_array( $option ) ) {
1618 if( is_array( $this->mVaryHeader
[$header] ) ) {
1619 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1621 $this->mVaryHeader
[$header] = $option;
1624 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1628 * Get a complete X-Vary-Options header
1632 public function getXVO() {
1633 $cvCookies = $this->getCacheVaryCookies();
1635 $cookiesOption = array();
1636 foreach ( $cvCookies as $cookieName ) {
1637 $cookiesOption[] = 'string-contains=' . $cookieName;
1639 $this->addVaryHeader( 'Cookie', $cookiesOption );
1642 foreach( $this->mVaryHeader
as $header => $option ) {
1643 $newheader = $header;
1644 if( is_array( $option ) ) {
1645 $newheader .= ';' . implode( ';', $option );
1647 $headers[] = $newheader;
1649 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1655 * bug 21672: Add Accept-Language to Vary and XVO headers
1656 * if there's no 'variant' parameter existed in GET.
1659 * /w/index.php?title=Main_page should always be served; but
1660 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1662 function addAcceptLanguage() {
1664 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1665 $variants = $wgContLang->getVariants();
1666 $aloption = array();
1667 foreach ( $variants as $variant ) {
1668 if( $variant === $wgContLang->getCode() ) {
1671 $aloption[] = 'string-contains=' . $variant;
1673 // IE and some other browsers use another form of language code
1674 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1675 // We should handle these too.
1676 $ievariant = explode( '-', $variant );
1677 if ( count( $ievariant ) == 2 ) {
1678 $ievariant[1] = strtoupper( $ievariant[1] );
1679 $ievariant = implode( '-', $ievariant );
1680 $aloption[] = 'string-contains=' . $ievariant;
1684 $this->addVaryHeader( 'Accept-Language', $aloption );
1689 * Set a flag which will cause an X-Frame-Options header appropriate for
1690 * edit pages to be sent. The header value is controlled by
1691 * $wgEditPageFrameOptions.
1693 * This is the default for special pages. If you display a CSRF-protected
1694 * form on an ordinary view page, then you need to call this function.
1696 * @param $enable bool
1698 public function preventClickjacking( $enable = true ) {
1699 $this->mPreventClickjacking
= $enable;
1703 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1704 * This can be called from pages which do not contain any CSRF-protected
1707 public function allowClickjacking() {
1708 $this->mPreventClickjacking
= false;
1712 * Get the X-Frame-Options header value (without the name part), or false
1713 * if there isn't one. This is used by Skin to determine whether to enable
1714 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1718 public function getFrameOptions() {
1719 global $wgBreakFrames, $wgEditPageFrameOptions;
1720 if ( $wgBreakFrames ) {
1722 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1723 return $wgEditPageFrameOptions;
1728 * Send cache control HTTP headers
1730 public function sendCacheControl() {
1731 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1733 $response = $this->getRequest()->response();
1734 if ( $wgUseETag && $this->mETag
) {
1735 $response->header( "ETag: $this->mETag" );
1738 $this->addAcceptLanguage();
1740 # don't serve compressed data to clients who can't handle it
1741 # maintain different caches for logged-in users and non-logged in ones
1742 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1745 # Add an X-Vary-Options header for Squid with Wikimedia patches
1746 $response->header( $this->getXVO() );
1749 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1751 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1752 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1756 # We'll purge the proxy cache explicitly, but require end user agents
1757 # to revalidate against the proxy on each visit.
1758 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1759 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1760 # start with a shorter timeout for initial testing
1761 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1762 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1763 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1765 # We'll purge the proxy cache for anons explicitly, but require end user agents
1766 # to revalidate against the proxy on each visit.
1767 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1768 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1769 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1770 # start with a shorter timeout for initial testing
1771 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1772 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1775 # We do want clients to cache if they can, but they *must* check for updates
1776 # on revisiting the page.
1777 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1778 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1779 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1781 if($this->mLastModified
) {
1782 $response->header( "Last-Modified: {$this->mLastModified}" );
1785 wfDebug( __METHOD__
. ": no caching **\n", false );
1787 # In general, the absence of a last modified header should be enough to prevent
1788 # the client from using its cache. We send a few other things just to make sure.
1789 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1790 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1791 $response->header( 'Pragma: no-cache' );
1796 * Get the message associed with the HTTP response code $code
1798 * @param $code Integer: status code
1799 * @return String or null: message or null if $code is not in the list of
1802 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1804 public static function getStatusMessage( $code ) {
1805 wfDeprecated( __METHOD__
);
1806 return HttpStatus
::getMessage( $code );
1810 * Finally, all the text has been munged and accumulated into
1811 * the object, let's actually output it:
1813 public function output() {
1814 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1816 if( $this->mDoNothing
) {
1820 wfProfileIn( __METHOD__
);
1822 $response = $this->getRequest()->response();
1824 if ( $this->mRedirect
!= '' ) {
1825 # Standards require redirect URLs to be absolute
1826 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1827 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1828 if( !$wgDebugRedirects ) {
1829 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1830 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1832 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1834 $this->sendCacheControl();
1836 $response->header( "Content-Type: text/html; charset=utf-8" );
1837 if( $wgDebugRedirects ) {
1838 $url = htmlspecialchars( $this->mRedirect
);
1839 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1840 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1841 print "</body>\n</html>\n";
1843 $response->header( 'Location: ' . $this->mRedirect
);
1845 wfProfileOut( __METHOD__
);
1847 } elseif ( $this->mStatusCode
) {
1848 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1850 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1854 # Buffer output; final headers may depend on later processing
1857 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1858 $response->header( 'Content-language: ' . $wgLanguageCode );
1860 // Prevent framing, if requested
1861 $frameOptions = $this->getFrameOptions();
1862 if ( $frameOptions ) {
1863 $response->header( "X-Frame-Options: $frameOptions" );
1866 if ( $this->mArticleBodyOnly
) {
1867 $this->out( $this->mBodytext
);
1869 $this->addDefaultModules();
1871 $sk = $this->getSkin();
1873 // Hook that allows last minute changes to the output page, e.g.
1874 // adding of CSS or Javascript by extensions.
1875 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1877 wfProfileIn( 'Output-skin' );
1878 $sk->outputPage( $this );
1879 wfProfileOut( 'Output-skin' );
1882 $this->sendCacheControl();
1884 wfProfileOut( __METHOD__
);
1888 * Actually output something with print().
1890 * @param $ins String: the string to output
1892 public function out( $ins ) {
1897 * Produce a "user is blocked" page.
1898 * @deprecated since 1.18
1900 function blockedPage() {
1901 throw new UserBlockedError( $this->getUser()->mBlock
);
1905 * Output a standard error page
1907 * @param $title String: message key for page title
1908 * @param $msg String: message key for page text
1909 * @param $params Array: message parameters
1911 public function showErrorPage( $title, $msg, $params = array() ) {
1912 if ( $this->getTitle() ) {
1913 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1915 $this->setPageTitle( wfMsg( $title ) );
1916 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1917 $this->setRobotPolicy( 'noindex,nofollow' );
1918 $this->setArticleRelated( false );
1919 $this->enableClientCache( false );
1920 $this->mRedirect
= '';
1921 $this->mBodytext
= '';
1923 $this->addWikiMsgArray( $msg, $params );
1925 $this->returnToMain();
1929 * Output a standard permission error page
1931 * @param $errors Array: error message keys
1932 * @param $action String: action that was denied or null if unknown
1934 public function showPermissionsErrorPage( $errors, $action = null ) {
1935 $this->mDebugtext
.= 'Original title: ' .
1936 $this->getTitle()->getPrefixedText() . "\n";
1937 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1938 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1939 $this->setRobotPolicy( 'noindex,nofollow' );
1940 $this->setArticleRelated( false );
1941 $this->enableClientCache( false );
1942 $this->mRedirect
= '';
1943 $this->mBodytext
= '';
1944 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1948 * Display an error page indicating that a given version of MediaWiki is
1949 * required to use it
1951 * @param $version Mixed: the version of MediaWiki needed to use the page
1953 public function versionRequired( $version ) {
1954 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1955 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1956 $this->setRobotPolicy( 'noindex,nofollow' );
1957 $this->setArticleRelated( false );
1958 $this->mBodytext
= '';
1960 $this->addWikiMsg( 'versionrequiredtext', $version );
1961 $this->returnToMain();
1965 * Display an error page noting that a given permission bit is required.
1966 * @deprecated since 1.18, just throw the exception directly
1967 * @param $permission String: key required
1969 public function permissionRequired( $permission ) {
1970 throw new PermissionsError( $permission );
1974 * Produce the stock "please login to use the wiki" page
1976 public function loginToUse() {
1977 if( $this->getUser()->isLoggedIn() ) {
1978 throw new PermissionsError( 'read' );
1981 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1982 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1983 $this->setRobotPolicy( 'noindex,nofollow' );
1984 $this->setArticleRelated( false );
1986 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1987 $loginLink = Linker
::linkKnown(
1989 wfMsgHtml( 'loginreqlink' ),
1991 array( 'returnto' => $this->getTitle()->getPrefixedText() )
1993 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
1994 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
1996 # Don't return to the main page if the user can't read it
1997 # otherwise we'll end up in a pointless loop
1998 $mainPage = Title
::newMainPage();
1999 if( $mainPage->userCanRead() ) {
2000 $this->returnToMain( null, $mainPage );
2005 * Format a list of error messages
2007 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2008 * @param $action String: action that was denied or null if unknown
2009 * @return String: the wikitext error-messages, formatted into a list.
2011 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2012 if ( $action == null ) {
2013 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2015 $action_desc = wfMsgNoTrans( "action-$action" );
2016 $text = wfMsgNoTrans(
2017 'permissionserrorstext-withaction',
2023 if ( count( $errors ) > 1 ) {
2024 $text .= '<ul class="permissions-errors">' . "\n";
2026 foreach( $errors as $error ) {
2028 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2033 $text .= "<div class=\"permissions-errors\">\n" .
2034 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2042 * Display a page stating that the Wiki is in read-only mode,
2043 * and optionally show the source of the page that the user
2044 * was trying to edit. Should only be called (for this
2045 * purpose) after wfReadOnly() has returned true.
2047 * For historical reasons, this function is _also_ used to
2048 * show the error message when a user tries to edit a page
2049 * they are not allowed to edit. (Unless it's because they're
2050 * blocked, then we show blockedPage() instead.) In this
2051 * case, the second parameter should be set to true and a list
2052 * of reasons supplied as the third parameter.
2054 * @todo Needs to be split into multiple functions.
2056 * @param $source String: source code to show (or null).
2057 * @param $protected Boolean: is this a permissions error?
2058 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2059 * @param $action String: action that was denied or null if unknown
2061 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2062 $this->setRobotPolicy( 'noindex,nofollow' );
2063 $this->setArticleRelated( false );
2065 // If no reason is given, just supply a default "I can't let you do
2066 // that, Dave" message. Should only occur if called by legacy code.
2067 if ( $protected && empty( $reasons ) ) {
2068 $reasons[] = array( 'badaccess-group0' );
2071 if ( !empty( $reasons ) ) {
2072 // Permissions error
2074 $this->setPageTitle( wfMsg( 'viewsource' ) );
2076 wfMsg( 'viewsourcefor', Linker
::linkKnown( $this->getTitle() ) )
2079 $this->setPageTitle( wfMsg( 'badaccess' ) );
2081 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2083 // Wiki is read only
2084 throw new ReadOnlyError
;
2087 // Show source, if supplied
2088 if( is_string( $source ) ) {
2089 $this->addWikiMsg( 'viewsourcetext' );
2092 'id' => 'wpTextbox1',
2093 'name' => 'wpTextbox1',
2094 'cols' => $this->getUser()->getOption( 'cols' ),
2095 'rows' => $this->getUser()->getOption( 'rows' ),
2096 'readonly' => 'readonly'
2098 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2100 // Show templates used by this article
2101 $article = new Article( $this->getTitle() );
2102 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2103 $this->addHTML( "<div class='templatesUsed'>
2109 # If the title doesn't exist, it's fairly pointless to print a return
2110 # link to it. After all, you just tried editing it and couldn't, so
2111 # what's there to do there?
2112 if( $this->getTitle()->exists() ) {
2113 $this->returnToMain( null, $this->getTitle() );
2118 * Turn off regular page output and return an error reponse
2119 * for when rate limiting has triggered.
2121 public function rateLimited() {
2122 throw new ThrottledError
;
2126 * Show a warning about slave lag
2128 * If the lag is higher than $wgSlaveLagCritical seconds,
2129 * then the warning is a bit more obvious. If the lag is
2130 * lower than $wgSlaveLagWarning, then no warning is shown.
2132 * @param $lag Integer: slave lag
2134 public function showLagWarning( $lag ) {
2135 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2136 if( $lag >= $wgSlaveLagWarning ) {
2137 $message = $lag < $wgSlaveLagCritical
2140 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2141 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2145 public function showFatalError( $message ) {
2146 $this->setPageTitle( wfMsg( 'internalerror' ) );
2147 $this->setRobotPolicy( 'noindex,nofollow' );
2148 $this->setArticleRelated( false );
2149 $this->enableClientCache( false );
2150 $this->mRedirect
= '';
2151 $this->mBodytext
= $message;
2154 public function showUnexpectedValueError( $name, $val ) {
2155 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2158 public function showFileCopyError( $old, $new ) {
2159 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2162 public function showFileRenameError( $old, $new ) {
2163 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2166 public function showFileDeleteError( $name ) {
2167 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2170 public function showFileNotFoundError( $name ) {
2171 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2175 * Add a "return to" link pointing to a specified title
2177 * @param $title Title to link
2178 * @param $query String query string
2179 * @param $text String text of the link (input is not escaped)
2181 public function addReturnTo( $title, $query = array(), $text = null ) {
2182 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2185 Linker
::link( $title, $text, array(), $query )
2187 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2191 * Add a "return to" link pointing to a specified title,
2192 * or the title indicated in the request, or else the main page
2194 * @param $unused No longer used
2195 * @param $returnto Title or String to return to
2196 * @param $returntoquery String: query string for the return to link
2198 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2199 if ( $returnto == null ) {
2200 $returnto = $this->getRequest()->getText( 'returnto' );
2203 if ( $returntoquery == null ) {
2204 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2207 if ( $returnto === '' ) {
2208 $returnto = Title
::newMainPage();
2211 if ( is_object( $returnto ) ) {
2212 $titleObj = $returnto;
2214 $titleObj = Title
::newFromText( $returnto );
2216 if ( !is_object( $titleObj ) ) {
2217 $titleObj = Title
::newMainPage();
2220 $this->addReturnTo( $titleObj, $returntoquery );
2224 * @param $sk Skin The given Skin
2225 * @param $includeStyle Boolean: unused
2226 * @return String: The doctype, opening <html>, and head element.
2228 public function headElement( Skin
$sk, $includeStyle = true ) {
2229 global $wgContLang, $wgUseTrackbacks;
2230 $userdir = $this->getLang()->getDir();
2231 $sitedir = $wgContLang->getDir();
2233 if ( $sk->commonPrintStylesheet() ) {
2234 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2237 $ret = Html
::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir ) );
2239 if ( $this->getHTMLTitle() == '' ) {
2240 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2243 $openHead = Html
::openElement( 'head' );
2245 # Don't bother with the newline if $head == ''
2246 $ret .= "$openHead\n";
2249 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2251 $ret .= implode( "\n", array(
2252 $this->getHeadLinks( null, true ),
2253 $this->buildCssLinks(),
2254 $this->getHeadScripts(),
2255 $this->getHeadItems()
2258 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2259 $ret .= $this->getTitle()->trackbackRDF();
2262 $closeHead = Html
::closeElement( 'head' );
2264 $ret .= "$closeHead\n";
2267 $bodyAttrs = array();
2269 # Classes for LTR/RTL directionality support
2270 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2272 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2273 # A <body> class is probably not the best way to do this . . .
2274 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2276 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2277 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2279 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2280 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2282 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2288 * Add the default ResourceLoader modules to this object
2290 private function addDefaultModules() {
2291 global $wgIncludeLegacyJavaScript, $wgUseAjax,
2292 $wgAjaxWatch, $wgEnableMWSuggest, $wgUseAJAXCategories;
2294 // Add base resources
2295 $this->addModules( array(
2298 'mediawiki.page.startup',
2299 'mediawiki.page.ready',
2301 if ( $wgIncludeLegacyJavaScript ){
2302 $this->addModules( 'mediawiki.legacy.wikibits' );
2305 // Add various resources if required
2307 $this->addModules( 'mediawiki.legacy.ajax' );
2309 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2311 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2312 $this->addModules( 'mediawiki.action.watch.ajax' );
2315 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2316 $this->addModules( 'mediawiki.page.mwsuggest' );
2320 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2321 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2324 # Crazy edit-on-double-click stuff
2325 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2326 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2329 if ( $wgUseAJAXCategories ) {
2330 global $wgAJAXCategoriesNamespaces;
2332 $title = $this->getTitle();
2334 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
2335 $this->addModules( 'mediawiki.page.ajaxCategories.init' );
2341 * Get a ResourceLoader object associated with this OutputPage
2343 * @return ResourceLoader
2345 public function getResourceLoader() {
2346 if ( is_null( $this->mResourceLoader
) ) {
2347 $this->mResourceLoader
= new ResourceLoader();
2349 return $this->mResourceLoader
;
2354 * @param $modules Array/string with the module name
2355 * @param $only String ResourceLoaderModule TYPE_ class constant
2356 * @param $useESI boolean
2357 * @return string html <script> and <style> tags
2359 protected function makeResourceLoaderLink( $modules, $only, $useESI = false ) {
2360 global $wgLoadScript, $wgResourceLoaderUseESI,
2361 $wgResourceLoaderInlinePrivateModules;
2362 // Lazy-load ResourceLoader
2363 // TODO: Should this be a static function of ResourceLoader instead?
2365 'lang' => $this->getContext()->getLang()->getCode(),
2366 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2367 'skin' => $this->getSkin()->getSkinName(),
2369 if ( $only !== ResourceLoaderModule
::TYPE_COMBINED
) {
2370 $baseQuery['only'] = $only;
2372 // Propagate printable and handheld parameters if present
2373 if ( $this->isPrintable() ) {
2374 $baseQuery['printable'] = 1;
2376 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2377 $baseQuery['handheld'] = 1;
2380 if ( !count( $modules ) ) {
2384 if ( count( $modules ) > 1 ) {
2385 // Remove duplicate module requests
2386 $modules = array_unique( (array) $modules );
2387 // Sort module names so requests are more uniform
2390 if ( ResourceLoader
::inDebugMode() ) {
2391 // Recursively call us for every item
2393 foreach ( $modules as $name ) {
2394 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2400 // Create keyed-by-group list of module objects from modules list
2402 $resourceLoader = $this->getResourceLoader();
2403 foreach ( (array) $modules as $name ) {
2404 $module = $resourceLoader->getModule( $name );
2405 # Check that we're allowed to include this module on this page
2406 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2407 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2408 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2409 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2415 $group = $module->getGroup();
2416 if ( !isset( $groups[$group] ) ) {
2417 $groups[$group] = array();
2419 $groups[$group][$name] = $module;
2423 foreach ( $groups as $group => $modules ) {
2424 $query = $baseQuery;
2425 // Special handling for user-specific groups
2426 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2427 $query['user'] = $this->getUser()->getName();
2430 // Create a fake request based on the one we are about to make so modules return
2431 // correct timestamp and emptiness data
2432 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2433 // Drop modules that know they're empty
2434 foreach ( $modules as $key => $module ) {
2435 if ( $module->isKnownEmpty( $context ) ) {
2436 unset( $modules[$key] );
2439 // If there are no modules left, skip this group
2440 if ( $modules === array() ) {
2444 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $modules ) );
2446 // Support inlining of private modules if configured as such
2447 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2448 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2449 $links .= Html
::inlineStyle(
2450 $resourceLoader->makeModuleResponse( $context, $modules )
2453 $links .= Html
::inlineScript(
2454 ResourceLoader
::makeLoaderConditionalScript(
2455 $resourceLoader->makeModuleResponse( $context, $modules )
2462 // Special handling for the user group; because users might change their stuff
2463 // on-wiki like user pages, or user preferences; we need to find the highest
2464 // timestamp of these user-changable modules so we can ensure cache misses on change
2465 // This should NOT be done for the site group (bug 27564) because anons get that too
2466 // and we shouldn't be putting timestamps in Squid-cached HTML
2467 if ( $group === 'user' ) {
2468 // Get the maximum timestamp
2470 foreach ( $modules as $module ) {
2471 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2473 // Add a version parameter so cache will break when things change
2474 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2476 // Make queries uniform in order
2479 $url = wfAppendQuery( $wgLoadScript, $query );
2480 // Prevent the IE6 extension check from being triggered (bug 28840)
2481 // by appending a character that's invalid in Windows extensions ('*')
2483 if ( $useESI && $wgResourceLoaderUseESI ) {
2484 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2485 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2486 $link = Html
::inlineStyle( $esi );
2488 $link = Html
::inlineScript( $esi );
2491 // Automatically select style/script elements
2492 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2493 $link = Html
::linkedStyle( $url );
2495 $link = Html
::linkedScript( $url );
2499 if( $group == 'noscript' ){
2500 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2502 $links .= $link . "\n";
2509 * JS stuff to put in the <head>. This is the startup module, config
2510 * vars and modules marked with position 'top'
2512 * @return String: HTML fragment
2514 function getHeadScripts() {
2515 // Startup - this will immediately load jquery and mediawiki modules
2516 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2518 // Load config before anything else
2519 $scripts .= Html
::inlineScript(
2520 ResourceLoader
::makeLoaderConditionalScript(
2521 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2525 // Script and Messages "only" requests marked for top inclusion
2526 // Messages should go first
2527 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2528 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2530 // Modules requests - let the client calculate dependencies and batch requests as it likes
2531 // Only load modules that have marked themselves for loading at the top
2532 $modules = $this->getModules( true, 'top' );
2534 $scripts .= Html
::inlineScript(
2535 ResourceLoader
::makeLoaderConditionalScript(
2536 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2545 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2546 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2550 function getBottomScripts() {
2551 global $wgUseSiteJs, $wgAllowUserJs;
2553 // Script and Messages "only" requests marked for bottom inclusion
2554 // Messages should go first
2555 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2556 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2558 // Modules requests - let the client calculate dependencies and batch requests as it likes
2559 // Only load modules that have marked themselves for loading at the bottom
2560 $modules = $this->getModules( true, 'bottom' );
2562 $scripts .= Html
::inlineScript(
2563 ResourceLoader
::makeLoaderConditionalScript(
2564 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2570 $scripts .= "\n" . $this->mScripts
;
2572 $userScripts = array( 'user.options', 'user.tokens' );
2574 // Add site JS if enabled
2575 if ( $wgUseSiteJs ) {
2576 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2577 if( $this->getUser()->isLoggedIn() ){
2578 $userScripts[] = 'user.groups';
2582 // Add user JS if enabled
2583 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2584 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2585 # XXX: additional security check/prompt?
2586 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2588 # @todo FIXME: This means that User:Me/Common.js doesn't load when previewing
2589 # User:Me/Vector.js, and vice versa (bug 26283)
2591 // We can't do $userScripts[] = 'user'; because the user module would end up
2592 // being wrapped in a closure, so load it raw like 'site'
2593 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2596 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2602 * Get an array containing global JS variables
2604 * Do not add things here which can be evaluated in
2605 * ResourceLoaderStartupScript - in other words, without state.
2606 * You will only be adding bloat to the page and causing page caches to
2607 * have to be purged on configuration changes.
2609 protected function getJSVars() {
2610 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2612 $title = $this->getTitle();
2613 $ns = $title->getNamespace();
2614 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2615 if ( $ns == NS_SPECIAL
) {
2616 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2618 $canonicalName = false; # bug 21115
2622 'wgCanonicalNamespace' => $nsname,
2623 'wgCanonicalSpecialPageName' => $canonicalName,
2624 'wgNamespaceNumber' => $title->getNamespace(),
2625 'wgPageName' => $title->getPrefixedDBKey(),
2626 'wgTitle' => $title->getText(),
2627 'wgCurRevisionId' => $title->getLatestRevID(),
2628 'wgArticleId' => $title->getArticleId(),
2629 'wgIsArticle' => $this->isArticle(),
2630 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2631 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2632 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2633 'wgCategories' => $this->getCategories(),
2634 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2636 if ( $wgContLang->hasVariants() ) {
2637 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2639 foreach ( $title->getRestrictionTypes() as $type ) {
2640 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2642 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2643 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2645 if ( $title->isMainPage() ) {
2646 $vars['wgIsMainPage'] = true;
2649 // Allow extensions to add their custom variables to the global JS variables
2650 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2656 * To make it harder for someone to slip a user a fake
2657 * user-JavaScript or user-CSS preview, a random token
2658 * is associated with the login session. If it's not
2659 * passed back with the preview request, we won't render
2664 public function userCanPreview() {
2665 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2666 ||
!$this->getRequest()->wasPosted()
2667 ||
!$this->getUser()->matchEditToken(
2668 $this->getRequest()->getVal( 'wpEditToken' ) )
2672 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2676 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2680 * @param $unused Unused
2681 * @param $addContentType bool
2683 * @return string HTML tag links to be put in the header.
2685 public function getHeadLinks( $unused = null, $addContentType = false ) {
2686 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2687 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2688 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2689 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2690 $wgRightsPage, $wgRightsUrl;
2694 if ( $addContentType ) {
2696 # More succinct than <meta http-equiv=Content-Type>, has the
2698 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2700 $tags[] = Html
::element( 'meta', array(
2701 'http-equiv' => 'Content-Type',
2702 'content' => "$wgMimeType; charset=UTF-8"
2704 $tags[] = Html
::element( 'meta', array( // bug 15835
2705 'http-equiv' => 'Content-Style-Type',
2706 'content' => 'text/css'
2711 $tags[] = Html
::element( 'meta', array(
2712 'name' => 'generator',
2713 'content' => "MediaWiki $wgVersion",
2716 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2717 if( $p !== 'index,follow' ) {
2718 // http://www.robotstxt.org/wc/meta-user.html
2719 // Only show if it's different from the default robots policy
2720 $tags[] = Html
::element( 'meta', array(
2726 if ( count( $this->mKeywords
) > 0 ) {
2728 "/<.*?" . ">/" => '',
2731 $tags[] = Html
::element( 'meta', array(
2732 'name' => 'keywords',
2733 'content' => preg_replace(
2734 array_keys( $strip ),
2735 array_values( $strip ),
2736 implode( ',', $this->mKeywords
)
2741 foreach ( $this->mMetatags
as $tag ) {
2742 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2744 $tag[0] = substr( $tag[0], 5 );
2748 $tags[] = Html
::element( 'meta',
2751 'content' => $tag[1]
2756 foreach ( $this->mLinktags
as $tag ) {
2757 $tags[] = Html
::element( 'link', $tag );
2760 # Universal edit button
2761 if ( $wgUniversalEditButton ) {
2762 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2763 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2764 // Original UniversalEditButton
2765 $msg = wfMsg( 'edit' );
2766 $tags[] = Html
::element( 'link', array(
2767 'rel' => 'alternate',
2768 'type' => 'application/x-wiki',
2770 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2772 // Alternate edit link
2773 $tags[] = Html
::element( 'link', array(
2776 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2781 # Generally the order of the favicon and apple-touch-icon links
2782 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2783 # uses whichever one appears later in the HTML source. Make sure
2784 # apple-touch-icon is specified first to avoid this.
2785 if ( $wgAppleTouchIcon !== false ) {
2786 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2789 if ( $wgFavicon !== false ) {
2790 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2793 # OpenSearch description link
2794 $tags[] = Html
::element( 'link', array(
2796 'type' => 'application/opensearchdescription+xml',
2797 'href' => wfScript( 'opensearch_desc' ),
2798 'title' => wfMsgForContent( 'opensearch-desc' ),
2801 if ( $wgEnableAPI ) {
2802 # Real Simple Discovery link, provides auto-discovery information
2803 # for the MediaWiki API (and potentially additional custom API
2804 # support such as WordPress or Twitter-compatible APIs for a
2805 # blogging extension, etc)
2806 $tags[] = Html
::element( 'link', array(
2808 'type' => 'application/rsd+xml',
2809 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ) ),
2814 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2815 && $wgContLang->hasVariants() ) {
2817 $urlvar = $wgContLang->getURLVariant();
2820 $variants = $wgContLang->getVariants();
2821 foreach ( $variants as $_v ) {
2822 $tags[] = Html
::element( 'link', array(
2823 'rel' => 'alternate',
2825 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2829 $tags[] = Html
::element( 'link', array(
2830 'rel' => 'canonical',
2831 'href' => $this->getTitle()->getFullURL() )
2838 if ( $wgRightsPage ) {
2839 $copy = Title
::newFromText( $wgRightsPage );
2842 $copyright = $copy->getLocalURL();
2846 if ( !$copyright && $wgRightsUrl ) {
2847 $copyright = $wgRightsUrl;
2851 $tags[] = Html
::element( 'link', array(
2852 'rel' => 'copyright',
2853 'href' => $copyright )
2859 foreach( $this->getSyndicationLinks() as $format => $link ) {
2860 # Use the page name for the title. In principle, this could
2861 # lead to issues with having the same name for different feeds
2862 # corresponding to the same page, but we can't avoid that at
2865 $tags[] = $this->feedLink(
2868 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2869 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2873 # Recent changes feed should appear on every page (except recentchanges,
2874 # that would be redundant). Put it after the per-page feed to avoid
2875 # changing existing behavior. It's still available, probably via a
2876 # menu in your browser. Some sites might have a different feed they'd
2877 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2878 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2879 # If so, use it instead.
2881 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2883 if ( $wgOverrideSiteFeed ) {
2884 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2885 $tags[] = $this->feedLink(
2887 htmlspecialchars( $feedUrl ),
2888 wfMsg( "site-{$type}-feed", $wgSitename )
2891 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2892 foreach ( $wgAdvertisedFeedTypes as $format ) {
2893 $tags[] = $this->feedLink(
2895 $rctitle->getLocalURL( "feed={$format}" ),
2896 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2901 return implode( "\n", $tags );
2905 * Generate a <link rel/> for a feed.
2907 * @param $type String: feed type
2908 * @param $url String: URL to the feed
2909 * @param $text String: value of the "title" attribute
2910 * @return String: HTML fragment
2912 private function feedLink( $type, $url, $text ) {
2913 return Html
::element( 'link', array(
2914 'rel' => 'alternate',
2915 'type' => "application/$type+xml",
2922 * Add a local or specified stylesheet, with the given media options.
2923 * Meant primarily for internal use...
2925 * @param $style String: URL to the file
2926 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2927 * @param $condition String: for IE conditional comments, specifying an IE version
2928 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2930 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2932 // Even though we expect the media type to be lowercase, but here we
2933 // force it to lowercase to be safe.
2935 $options['media'] = $media;
2938 $options['condition'] = $condition;
2941 $options['dir'] = $dir;
2943 $this->styles
[$style] = $options;
2947 * Adds inline CSS styles
2948 * @param $style_css Mixed: inline CSS
2950 public function addInlineStyle( $style_css ){
2951 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2955 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2956 * These will be applied to various media & IE conditionals.
2960 public function buildCssLinks() {
2961 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
2963 $this->getSkin()->setupSkinUserCss( $this );
2965 // Add ResourceLoader styles
2966 // Split the styles into four groups
2967 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2968 $resourceLoader = $this->getResourceLoader();
2970 $moduleStyles = $this->getModuleStyles();
2972 // Per-site custom styles
2973 if ( $wgUseSiteCss ) {
2974 $moduleStyles[] = 'site';
2975 $moduleStyles[] = 'noscript';
2976 if( $this->getUser()->isLoggedIn() ){
2977 $moduleStyles[] = 'user.groups';
2981 // Per-user custom styles
2982 if ( $wgAllowUserCss ) {
2983 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
2984 // @todo FIXME: Properly escape the cdata!
2985 $this->addInlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
2987 $moduleStyles[] = 'user';
2991 // Per-user preference styles
2992 if ( $wgAllowUserCssPrefs ) {
2993 $moduleStyles[] = 'user.options';
2996 foreach ( $moduleStyles as $name ) {
2997 $group = $resourceLoader->getModule( $name )->getGroup();
2998 // Modules in groups named "other" or anything different than "user", "site" or "private"
2999 // will be placed in the "other" group
3000 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3003 // We want site, private and user styles to override dynamically added styles from modules, but we want
3004 // dynamically added styles to override statically added styles from other modules. So the order
3005 // has to be other, dynamic, site, private, user
3006 // Add statically added styles for other modules
3007 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3008 // Add normal styles added through addStyle()/addInlineStyle() here
3009 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3010 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3011 // We use a <meta> tag with a made-up name for this because that's valid HTML
3012 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3014 // Add site, private and user styles
3015 // 'private' at present only contains user.options, so put that before 'user'
3016 // Any future private modules will likely have a similar user-specific character
3017 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3018 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3019 ResourceLoaderModule
::TYPE_STYLES
3025 public function buildCssLinksArray() {
3028 // Add any extension CSS
3029 foreach ( $this->mExtStyles
as $url ) {
3030 $this->addStyle( $url );
3032 $this->mExtStyles
= array();
3034 foreach( $this->styles
as $file => $options ) {
3035 $link = $this->styleLink( $file, $options );
3037 $links[$file] = $link;
3044 * Generate \<link\> tags for stylesheets
3046 * @param $style String: URL to the file
3047 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3049 * @return String: HTML fragment
3051 protected function styleLink( $style, $options ) {
3052 if( isset( $options['dir'] ) ) {
3053 if( $this->getLang()->getDir() != $options['dir'] ) {
3058 if( isset( $options['media'] ) ) {
3059 $media = self
::transformCssMedia( $options['media'] );
3060 if( is_null( $media ) ) {
3067 if( substr( $style, 0, 1 ) == '/' ||
3068 substr( $style, 0, 5 ) == 'http:' ||
3069 substr( $style, 0, 6 ) == 'https:' ) {
3072 global $wgStylePath, $wgStyleVersion;
3073 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3076 $link = Html
::linkedStyle( $url, $media );
3078 if( isset( $options['condition'] ) ) {
3079 $condition = htmlspecialchars( $options['condition'] );
3080 $link = "<!--[if $condition]>$link<![endif]-->";
3086 * Transform "media" attribute based on request parameters
3088 * @param $media String: current value of the "media" attribute
3089 * @return String: modified value of the "media" attribute
3091 public static function transformCssMedia( $media ) {
3092 global $wgRequest, $wgHandheldForIPhone;
3094 // Switch in on-screen display for media testing
3096 'printable' => 'print',
3097 'handheld' => 'handheld',
3099 foreach( $switches as $switch => $targetMedia ) {
3100 if( $wgRequest->getBool( $switch ) ) {
3101 if( $media == $targetMedia ) {
3103 } elseif( $media == 'screen' ) {
3109 // Expand longer media queries as iPhone doesn't grok 'handheld'
3110 if( $wgHandheldForIPhone ) {
3111 $mediaAliases = array(
3112 'screen' => 'screen and (min-device-width: 481px)',
3113 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3116 if( isset( $mediaAliases[$media] ) ) {
3117 $media = $mediaAliases[$media];
3125 * Add a wikitext-formatted message to the output.
3126 * This is equivalent to:
3128 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3130 public function addWikiMsg( /*...*/ ) {
3131 $args = func_get_args();
3132 $name = array_shift( $args );
3133 $this->addWikiMsgArray( $name, $args );
3137 * Add a wikitext-formatted message to the output.
3138 * Like addWikiMsg() except the parameters are taken as an array
3139 * instead of a variable argument list.
3141 * $options is passed through to wfMsgExt(), see that function for details.
3143 * @param $name string
3144 * @param $args array
3145 * @param $options array
3147 public function addWikiMsgArray( $name, $args, $options = array() ) {
3148 $options[] = 'parse';
3149 $text = wfMsgExt( $name, $options, $args );
3150 $this->addHTML( $text );
3154 * This function takes a number of message/argument specifications, wraps them in
3155 * some overall structure, and then parses the result and adds it to the output.
3157 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3158 * on. The subsequent arguments may either be strings, in which case they are the
3159 * message names, or arrays, in which case the first element is the message name,
3160 * and subsequent elements are the parameters to that message.
3162 * The special named parameter 'options' in a message specification array is passed
3163 * through to the $options parameter of wfMsgExt().
3165 * Don't use this for messages that are not in users interface language.
3169 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3173 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3175 * The newline after opening div is needed in some wikitext. See bug 19226.
3177 * @param $wrap string
3179 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3180 $msgSpecs = func_get_args();
3181 array_shift( $msgSpecs );
3182 $msgSpecs = array_values( $msgSpecs );
3184 foreach ( $msgSpecs as $n => $spec ) {
3186 if ( is_array( $spec ) ) {
3188 $name = array_shift( $args );
3189 if ( isset( $args['options'] ) ) {
3190 $options = $args['options'];
3191 unset( $args['options'] );
3197 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3199 $this->addWikiText( $s );
3203 * Include jQuery core. Use this to avoid loading it multiple times
3204 * before we get a usable script loader.
3206 * @param $modules Array: list of jQuery modules which should be loaded
3207 * @return Array: the list of modules which were not loaded.
3209 * @deprecated since 1.17
3211 public function includeJQuery( $modules = array() ) {