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 an array of head items
533 function getHeadItemsArray() {
534 return $this->mHeadItems
;
538 * Get all header items in a string
542 function getHeadItems() {
544 foreach ( $this->mHeadItems
as $item ) {
551 * Add or replace an header item to the output
553 * @param $name String: item name
554 * @param $value String: raw HTML
556 public function addHeadItem( $name, $value ) {
557 $this->mHeadItems
[$name] = $value;
561 * Check if the header item $name is already set
563 * @param $name String: item name
566 public function hasHeadItem( $name ) {
567 return isset( $this->mHeadItems
[$name] );
571 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
573 * @param $tag String: value of "ETag" header
575 function setETag( $tag ) {
580 * Set whether the output should only contain the body of the article,
581 * without any skin, sidebar, etc.
582 * Used e.g. when calling with "action=render".
584 * @param $only Boolean: whether to output only the body of the article
586 public function setArticleBodyOnly( $only ) {
587 $this->mArticleBodyOnly
= $only;
591 * Return whether the output will contain only the body of the article
595 public function getArticleBodyOnly() {
596 return $this->mArticleBodyOnly
;
600 * checkLastModified tells the client to use the client-cached page if
601 * possible. If sucessful, the OutputPage is disabled so that
602 * any future call to OutputPage->output() have no effect.
604 * Side effect: sets mLastModified for Last-Modified header
606 * @param $timestamp string
608 * @return Boolean: true iff cache-ok headers was sent.
610 public function checkLastModified( $timestamp ) {
611 global $wgCachePages, $wgCacheEpoch;
613 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
614 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
617 if( !$wgCachePages ) {
618 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
621 if( $this->getUser()->getOption( 'nocache' ) ) {
622 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
626 $timestamp = wfTimestamp( TS_MW
, $timestamp );
627 $modifiedTimes = array(
628 'page' => $timestamp,
629 'user' => $this->getUser()->getTouched(),
630 'epoch' => $wgCacheEpoch
632 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
634 $maxModified = max( $modifiedTimes );
635 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
637 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
638 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
644 foreach ( $modifiedTimes as $name => $value ) {
645 if ( $info !== '' ) {
648 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
651 # IE sends sizes after the date like this:
652 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
653 # this breaks strtotime().
654 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
656 wfSuppressWarnings(); // E_STRICT system time bitching
657 $clientHeaderTime = strtotime( $clientHeader );
659 if ( !$clientHeaderTime ) {
660 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
663 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
665 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
666 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
667 wfDebug( __METHOD__
. ": effective Last-Modified: " .
668 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
669 if( $clientHeaderTime < $maxModified ) {
670 wfDebug( __METHOD__
. ": STALE, $info\n", false );
675 # Give a 304 response code and disable body output
676 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
677 ini_set( 'zlib.output_compression', 0 );
678 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
679 $this->sendCacheControl();
682 // Don't output a compressed blob when using ob_gzhandler;
683 // it's technically against HTTP spec and seems to confuse
684 // Firefox when the response gets split over two packets.
685 wfClearOutputBuffers();
691 * Override the last modified timestamp
693 * @param $timestamp String: new timestamp, in a format readable by
696 public function setLastModified( $timestamp ) {
697 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
701 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
703 * @param $policy String: the literal string to output as the contents of
704 * the meta tag. Will be parsed according to the spec and output in
708 public function setRobotPolicy( $policy ) {
709 $policy = Article
::formatRobotPolicy( $policy );
711 if( isset( $policy['index'] ) ) {
712 $this->setIndexPolicy( $policy['index'] );
714 if( isset( $policy['follow'] ) ) {
715 $this->setFollowPolicy( $policy['follow'] );
720 * Set the index policy for the page, but leave the follow policy un-
723 * @param $policy string Either 'index' or 'noindex'.
726 public function setIndexPolicy( $policy ) {
727 $policy = trim( $policy );
728 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
729 $this->mIndexPolicy
= $policy;
734 * Set the follow policy for the page, but leave the index policy un-
737 * @param $policy String: either 'follow' or 'nofollow'.
740 public function setFollowPolicy( $policy ) {
741 $policy = trim( $policy );
742 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
743 $this->mFollowPolicy
= $policy;
748 * Set the new value of the "action text", this will be added to the
749 * "HTML title", separated from it with " - ".
751 * @param $text String: new value of the "action text"
753 public function setPageTitleActionText( $text ) {
754 $this->mPageTitleActionText
= $text;
758 * Get the value of the "action text"
762 public function getPageTitleActionText() {
763 if ( isset( $this->mPageTitleActionText
) ) {
764 return $this->mPageTitleActionText
;
769 * "HTML title" means the contents of <title>.
770 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
772 * @param $name string
774 public function setHTMLTitle( $name ) {
775 $this->mHTMLtitle
= $name;
779 * Return the "HTML title", i.e. the content of the <title> tag.
783 public function getHTMLTitle() {
784 return $this->mHTMLtitle
;
788 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
789 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
790 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
791 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
793 * @param $name string
795 public function setPageTitle( $name ) {
796 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
797 # but leave "<i>foobar</i>" alone
798 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
799 $this->mPagetitle
= $nameWithTags;
801 # change "<i>foo&bar</i>" to "foo&bar"
802 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
806 * Return the "page title", i.e. the content of the \<h1\> tag.
810 public function getPageTitle() {
811 return $this->mPagetitle
;
815 * Set the Title object to use
817 * @param $t Title object
819 public function setTitle( Title
$t ) {
820 $this->getContext()->setTitle( $t );
825 * Replace the subtile with $str
827 * @param $str String: new value of the subtitle
829 public function setSubtitle( $str ) {
830 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
834 * Add $str to the subtitle
836 * @param $str String to add to the subtitle
838 public function appendSubtitle( $str ) {
839 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
847 public function getSubtitle() {
848 return $this->mSubtitle
;
852 * Set the page as printable, i.e. it'll be displayed with with all
853 * print styles included
855 public function setPrintable() {
856 $this->mPrintable
= true;
860 * Return whether the page is "printable"
864 public function isPrintable() {
865 return $this->mPrintable
;
869 * Disable output completely, i.e. calling output() will have no effect
871 public function disable() {
872 $this->mDoNothing
= true;
876 * Return whether the output will be completely disabled
880 public function isDisabled() {
881 return $this->mDoNothing
;
885 * Show an "add new section" link?
889 public function showNewSectionLink() {
890 return $this->mNewSectionLink
;
894 * Forcibly hide the new section link?
898 public function forceHideNewSectionLink() {
899 return $this->mHideNewSectionLink
;
903 * Add or remove feed links in the page header
904 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
905 * for the new version
908 * @param $show Boolean: true: add default feeds, false: remove all feeds
910 public function setSyndicated( $show = true ) {
912 $this->setFeedAppendQuery( false );
914 $this->mFeedLinks
= array();
919 * Add default feeds to the page header
920 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
921 * for the new version
924 * @param $val String: query to append to feed links or false to output
927 public function setFeedAppendQuery( $val ) {
928 global $wgAdvertisedFeedTypes;
930 $this->mFeedLinks
= array();
932 foreach ( $wgAdvertisedFeedTypes as $type ) {
933 $query = "feed=$type";
934 if ( is_string( $val ) ) {
935 $query .= '&' . $val;
937 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
942 * Add a feed link to the page header
944 * @param $format String: feed type, should be a key of $wgFeedClasses
945 * @param $href String: URL
947 public function addFeedLink( $format, $href ) {
948 global $wgAdvertisedFeedTypes;
950 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
951 $this->mFeedLinks
[$format] = $href;
956 * Should we output feed links for this page?
959 public function isSyndicated() {
960 return count( $this->mFeedLinks
) > 0;
964 * Return URLs for each supported syndication format for this page.
965 * @return array associating format keys with URLs
967 public function getSyndicationLinks() {
968 return $this->mFeedLinks
;
972 * Will currently always return null
976 public function getFeedAppendQuery() {
977 return $this->mFeedLinksAppendQuery
;
981 * Set whether the displayed content is related to the source of the
982 * corresponding article on the wiki
983 * Setting true will cause the change "article related" toggle to true
987 public function setArticleFlag( $v ) {
988 $this->mIsarticle
= $v;
990 $this->mIsArticleRelated
= $v;
995 * Return whether the content displayed page is related to the source of
996 * the corresponding article on the wiki
1000 public function isArticle() {
1001 return $this->mIsarticle
;
1005 * Set whether this page is related an article on the wiki
1006 * Setting false will cause the change of "article flag" toggle to false
1010 public function setArticleRelated( $v ) {
1011 $this->mIsArticleRelated
= $v;
1013 $this->mIsarticle
= false;
1018 * Return whether this page is related an article on the wiki
1022 public function isArticleRelated() {
1023 return $this->mIsArticleRelated
;
1027 * Add new language links
1029 * @param $newLinkArray Associative array mapping language code to the page
1032 public function addLanguageLinks( $newLinkArray ) {
1033 $this->mLanguageLinks +
= $newLinkArray;
1037 * Reset the language links and add new language links
1039 * @param $newLinkArray Associative array mapping language code to the page
1042 public function setLanguageLinks( $newLinkArray ) {
1043 $this->mLanguageLinks
= $newLinkArray;
1047 * Get the list of language links
1049 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1051 public function getLanguageLinks() {
1052 return $this->mLanguageLinks
;
1056 * Add an array of categories, with names in the keys
1058 * @param $categories Array mapping category name => sort key
1060 public function addCategoryLinks( $categories ) {
1063 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1067 # Add the links to a LinkBatch
1068 $arr = array( NS_CATEGORY
=> $categories );
1069 $lb = new LinkBatch
;
1070 $lb->setArray( $arr );
1072 # Fetch existence plus the hiddencat property
1073 $dbr = wfGetDB( DB_SLAVE
);
1074 $res = $dbr->select( array( 'page', 'page_props' ),
1075 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1076 $lb->constructSet( 'page', $dbr ),
1079 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1082 # Add the results to the link cache
1083 $lb->addResultToCache( LinkCache
::singleton(), $res );
1085 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1086 $categories = array_combine(
1087 array_keys( $categories ),
1088 array_fill( 0, count( $categories ), 'normal' )
1091 # Mark hidden categories
1092 foreach ( $res as $row ) {
1093 if ( isset( $row->pp_value
) ) {
1094 $categories[$row->page_title
] = 'hidden';
1098 # Add the remaining categories to the skin
1099 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1100 foreach ( $categories as $category => $type ) {
1101 $origcategory = $category;
1102 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1103 $wgContLang->findVariantLink( $category, $title, true );
1104 if ( $category != $origcategory ) {
1105 if ( array_key_exists( $category, $categories ) ) {
1109 $text = $wgContLang->convertHtml( $title->getText() );
1110 $this->mCategories
[] = $title->getText();
1111 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1117 * Reset the category links (but not the category list) and add $categories
1119 * @param $categories Array mapping category name => sort key
1121 public function setCategoryLinks( $categories ) {
1122 $this->mCategoryLinks
= array();
1123 $this->addCategoryLinks( $categories );
1127 * Get the list of category links, in a 2-D array with the following format:
1128 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1129 * hidden categories) and $link a HTML fragment with a link to the category
1134 public function getCategoryLinks() {
1135 return $this->mCategoryLinks
;
1139 * Get the list of category names this page belongs to
1141 * @return Array of strings
1143 public function getCategories() {
1144 return $this->mCategories
;
1148 * Do not allow scripts which can be modified by wiki users to load on this page;
1149 * only allow scripts bundled with, or generated by, the software.
1151 public function disallowUserJs() {
1152 $this->reduceAllowedModules(
1153 ResourceLoaderModule
::TYPE_SCRIPTS
,
1154 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1159 * Return whether user JavaScript is allowed for this page
1160 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1161 * trustworthiness is identified and enforced automagically.
1164 public function isUserJsAllowed() {
1165 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1169 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1170 * @see ResourceLoaderModule::$origin
1171 * @param $type String ResourceLoaderModule TYPE_ constant
1172 * @return Int ResourceLoaderModule ORIGIN_ class constant
1174 public function getAllowedModules( $type ){
1175 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1176 return min( array_values( $this->mAllowedModules
) );
1178 return isset( $this->mAllowedModules
[$type] )
1179 ?
$this->mAllowedModules
[$type]
1180 : ResourceLoaderModule
::ORIGIN_ALL
;
1185 * Set the highest level of CSS/JS untrustworthiness allowed
1186 * @param $type String ResourceLoaderModule TYPE_ constant
1187 * @param $level Int ResourceLoaderModule class constant
1189 public function setAllowedModules( $type, $level ){
1190 $this->mAllowedModules
[$type] = $level;
1194 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1195 * @param $type String
1196 * @param $level Int ResourceLoaderModule class constant
1198 public function reduceAllowedModules( $type, $level ){
1199 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1203 * Prepend $text to the body HTML
1205 * @param $text String: HTML
1207 public function prependHTML( $text ) {
1208 $this->mBodytext
= $text . $this->mBodytext
;
1212 * Append $text to the body HTML
1214 * @param $text String: HTML
1216 public function addHTML( $text ) {
1217 $this->mBodytext
.= $text;
1221 * Clear the body HTML
1223 public function clearHTML() {
1224 $this->mBodytext
= '';
1230 * @return String: HTML
1232 public function getHTML() {
1233 return $this->mBodytext
;
1237 * Add $text to the debug output
1239 * @param $text String: debug text
1241 public function debug( $text ) {
1242 $this->mDebugtext
.= $text;
1246 * Get/set the ParserOptions object to use for wikitext parsing
1248 * @param $options either the ParserOption to use or null to only get the
1249 * current ParserOption object
1250 * @return ParserOptions object
1252 public function parserOptions( $options = null ) {
1253 if ( !$this->mParserOptions
) {
1254 $this->mParserOptions
= new ParserOptions
;
1255 $this->mParserOptions
->setEditSection( false );
1257 return wfSetVar( $this->mParserOptions
, $options );
1261 * Set the revision ID which will be seen by the wiki text parser
1262 * for things such as embedded {{REVISIONID}} variable use.
1264 * @param $revid Mixed: an positive integer, or null
1265 * @return Mixed: previous value
1267 public function setRevisionId( $revid ) {
1268 $val = is_null( $revid ) ?
null : intval( $revid );
1269 return wfSetVar( $this->mRevisionId
, $val );
1273 * Get the displayed revision ID
1277 public function getRevisionId() {
1278 return $this->mRevisionId
;
1282 * Set the displayed file version
1284 * @param $file File|false
1285 * @return Mixed: previous value
1287 public function setFileVersion( $file ) {
1289 if ( $file instanceof File
&& $file->exists() ) {
1290 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1292 return wfSetVar( $this->mFileVersion
, $val, true );
1296 * Get the displayed file version
1298 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1300 public function getFileVersion() {
1301 return $this->mFileVersion
;
1305 * Get the templates used on this page
1307 * @return Array (namespace => dbKey => revId)
1310 public function getTemplateIds() {
1311 return $this->mTemplateIds
;
1315 * Get the files used on this page
1317 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1320 public function getImageTimeKeys() {
1321 return $this->mImageTimeKeys
;
1325 * Convert wikitext to HTML and add it to the buffer
1326 * Default assumes that the current page title will be used.
1328 * @param $text String
1329 * @param $linestart Boolean: is this the start of a line?
1331 public function addWikiText( $text, $linestart = true ) {
1332 $title = $this->getTitle(); // Work arround E_STRICT
1333 $this->addWikiTextTitle( $text, $title, $linestart );
1337 * Add wikitext with a custom Title object
1339 * @param $text String: wikitext
1340 * @param $title Title object
1341 * @param $linestart Boolean: is this the start of a line?
1343 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1344 $this->addWikiTextTitle( $text, $title, $linestart );
1348 * Add wikitext with a custom Title object and
1350 * @param $text String: wikitext
1351 * @param $title Title object
1352 * @param $linestart Boolean: is this the start of a line?
1354 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1355 $this->addWikiTextTitle( $text, $title, $linestart, true );
1359 * Add wikitext with tidy enabled
1361 * @param $text String: wikitext
1362 * @param $linestart Boolean: is this the start of a line?
1364 public function addWikiTextTidy( $text, $linestart = true ) {
1365 $title = $this->getTitle();
1366 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1370 * Add wikitext with a custom Title object
1372 * @param $text String: wikitext
1373 * @param $title Title object
1374 * @param $linestart Boolean: is this the start of a line?
1375 * @param $tidy Boolean: whether to use tidy
1377 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1380 wfProfileIn( __METHOD__
);
1382 wfIncrStats( 'pcache_not_possible' );
1384 $popts = $this->parserOptions();
1385 $oldTidy = $popts->setTidy( $tidy );
1387 $parserOutput = $wgParser->parse(
1388 $text, $title, $popts,
1389 $linestart, true, $this->mRevisionId
1392 $popts->setTidy( $oldTidy );
1394 $this->addParserOutput( $parserOutput );
1396 wfProfileOut( __METHOD__
);
1400 * Add a ParserOutput object, but without Html
1402 * @param $parserOutput ParserOutput object
1404 public function addParserOutputNoText( &$parserOutput ) {
1405 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1406 $this->addCategoryLinks( $parserOutput->getCategories() );
1407 $this->mNewSectionLink
= $parserOutput->getNewSection();
1408 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1410 $this->mParseWarnings
= $parserOutput->getWarnings();
1411 if ( !$parserOutput->isCacheable() ) {
1412 $this->enableClientCache( false );
1414 $this->mNoGallery
= $parserOutput->getNoGallery();
1415 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1416 $this->addModules( $parserOutput->getModules() );
1417 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1418 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1419 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1421 // Template versioning...
1422 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1423 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1424 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1426 $this->mTemplateIds
[$ns] = $dbks;
1429 // File versioning...
1430 foreach ( (array)$parserOutput->getImageTimeKeys() as $dbk => $data ) {
1431 $this->mImageTimeKeys
[$dbk] = $data;
1434 // Hooks registered in the object
1435 global $wgParserOutputHooks;
1436 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1437 list( $hookName, $data ) = $hookInfo;
1438 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1439 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1443 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1447 * Add a ParserOutput object
1449 * @param $parserOutput ParserOutput
1451 function addParserOutput( &$parserOutput ) {
1452 $this->addParserOutputNoText( $parserOutput );
1453 $text = $parserOutput->getText();
1454 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1455 $this->addHTML( $text );
1460 * Add the output of a QuickTemplate to the output buffer
1462 * @param $template QuickTemplate
1464 public function addTemplate( &$template ) {
1466 $template->execute();
1467 $this->addHTML( ob_get_contents() );
1472 * Parse wikitext and return the HTML.
1474 * @param $text String
1475 * @param $linestart Boolean: is this the start of a line?
1476 * @param $interface Boolean: use interface language ($wgLang instead of
1477 * $wgContLang) while parsing language sensitive magic
1478 * words like GRAMMAR and PLURAL
1479 * @param $language Language object: target language object, will override
1481 * @return String: HTML
1483 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1484 // Check one for one common cause for parser state resetting
1485 $callers = wfGetAllCallers( 10 );
1486 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1487 throw new MWException( "wfMsg* function with parsing cannot be used " .
1488 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1493 if( is_null( $this->getTitle() ) ) {
1494 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1497 $popts = $this->parserOptions();
1499 $popts->setInterfaceMessage( true );
1501 if ( $language !== null ) {
1502 $oldLang = $popts->setTargetLanguage( $language );
1505 $parserOutput = $wgParser->parse(
1506 $text, $this->getTitle(), $popts,
1507 $linestart, true, $this->mRevisionId
1511 $popts->setInterfaceMessage( false );
1513 if ( $language !== null ) {
1514 $popts->setTargetLanguage( $oldLang );
1517 return $parserOutput->getText();
1521 * Parse wikitext, strip paragraphs, and return the HTML.
1523 * @param $text String
1524 * @param $linestart Boolean: is this the start of a line?
1525 * @param $interface Boolean: use interface language ($wgLang instead of
1526 * $wgContLang) while parsing language sensitive magic
1527 * words like GRAMMAR and PLURAL
1528 * @return String: HTML
1530 public function parseInline( $text, $linestart = true, $interface = false ) {
1531 $parsed = $this->parse( $text, $linestart, $interface );
1534 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1542 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1544 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1546 public function setSquidMaxage( $maxage ) {
1547 $this->mSquidMaxage
= $maxage;
1551 * Use enableClientCache(false) to force it to send nocache headers
1553 * @param $state bool
1557 public function enableClientCache( $state ) {
1558 return wfSetVar( $this->mEnableClientCache
, $state );
1562 * Get the list of cookies that will influence on the cache
1566 function getCacheVaryCookies() {
1567 global $wgCookiePrefix, $wgCacheVaryCookies;
1569 if ( $cookies === null ) {
1570 $cookies = array_merge(
1572 "{$wgCookiePrefix}Token",
1573 "{$wgCookiePrefix}LoggedOut",
1578 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1584 * Return whether this page is not cacheable because "useskin" or "uselang"
1585 * URL parameters were passed.
1589 function uncacheableBecauseRequestVars() {
1590 $request = $this->getRequest();
1591 return $request->getText( 'useskin', false ) === false
1592 && $request->getText( 'uselang', false ) === false;
1596 * Check if the request has a cache-varying cookie header
1597 * If it does, it's very important that we don't allow public caching
1601 function haveCacheVaryCookies() {
1602 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1603 if ( $cookieHeader === false ) {
1606 $cvCookies = $this->getCacheVaryCookies();
1607 foreach ( $cvCookies as $cookieName ) {
1608 # Check for a simple string match, like the way squid does it
1609 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1610 wfDebug( __METHOD__
. ": found $cookieName\n" );
1614 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1619 * Add an HTTP header that will influence on the cache
1621 * @param $header String: header name
1622 * @param $option Array|null
1623 * @todo FIXME: Document the $option parameter; it appears to be for
1624 * X-Vary-Options but what format is acceptable?
1626 public function addVaryHeader( $header, $option = null ) {
1627 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1628 $this->mVaryHeader
[$header] = (array)$option;
1629 } elseif( is_array( $option ) ) {
1630 if( is_array( $this->mVaryHeader
[$header] ) ) {
1631 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1633 $this->mVaryHeader
[$header] = $option;
1636 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1640 * Get a complete X-Vary-Options header
1644 public function getXVO() {
1645 $cvCookies = $this->getCacheVaryCookies();
1647 $cookiesOption = array();
1648 foreach ( $cvCookies as $cookieName ) {
1649 $cookiesOption[] = 'string-contains=' . $cookieName;
1651 $this->addVaryHeader( 'Cookie', $cookiesOption );
1654 foreach( $this->mVaryHeader
as $header => $option ) {
1655 $newheader = $header;
1656 if( is_array( $option ) ) {
1657 $newheader .= ';' . implode( ';', $option );
1659 $headers[] = $newheader;
1661 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1667 * bug 21672: Add Accept-Language to Vary and XVO headers
1668 * if there's no 'variant' parameter existed in GET.
1671 * /w/index.php?title=Main_page should always be served; but
1672 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1674 function addAcceptLanguage() {
1676 if( !$this->getRequest()->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1677 $variants = $wgContLang->getVariants();
1678 $aloption = array();
1679 foreach ( $variants as $variant ) {
1680 if( $variant === $wgContLang->getCode() ) {
1683 $aloption[] = 'string-contains=' . $variant;
1685 // IE and some other browsers use another form of language code
1686 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1687 // We should handle these too.
1688 $ievariant = explode( '-', $variant );
1689 if ( count( $ievariant ) == 2 ) {
1690 $ievariant[1] = strtoupper( $ievariant[1] );
1691 $ievariant = implode( '-', $ievariant );
1692 $aloption[] = 'string-contains=' . $ievariant;
1696 $this->addVaryHeader( 'Accept-Language', $aloption );
1701 * Set a flag which will cause an X-Frame-Options header appropriate for
1702 * edit pages to be sent. The header value is controlled by
1703 * $wgEditPageFrameOptions.
1705 * This is the default for special pages. If you display a CSRF-protected
1706 * form on an ordinary view page, then you need to call this function.
1708 * @param $enable bool
1710 public function preventClickjacking( $enable = true ) {
1711 $this->mPreventClickjacking
= $enable;
1715 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1716 * This can be called from pages which do not contain any CSRF-protected
1719 public function allowClickjacking() {
1720 $this->mPreventClickjacking
= false;
1724 * Get the X-Frame-Options header value (without the name part), or false
1725 * if there isn't one. This is used by Skin to determine whether to enable
1726 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1730 public function getFrameOptions() {
1731 global $wgBreakFrames, $wgEditPageFrameOptions;
1732 if ( $wgBreakFrames ) {
1734 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1735 return $wgEditPageFrameOptions;
1740 * Send cache control HTTP headers
1742 public function sendCacheControl() {
1743 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1745 $response = $this->getRequest()->response();
1746 if ( $wgUseETag && $this->mETag
) {
1747 $response->header( "ETag: $this->mETag" );
1750 $this->addAcceptLanguage();
1752 # don't serve compressed data to clients who can't handle it
1753 # maintain different caches for logged-in users and non-logged in ones
1754 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1757 # Add an X-Vary-Options header for Squid with Wikimedia patches
1758 $response->header( $this->getXVO() );
1761 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1763 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1764 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1768 # We'll purge the proxy cache explicitly, but require end user agents
1769 # to revalidate against the proxy on each visit.
1770 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1771 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1772 # start with a shorter timeout for initial testing
1773 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1774 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1775 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1777 # We'll purge the proxy cache for anons explicitly, but require end user agents
1778 # to revalidate against the proxy on each visit.
1779 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1780 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1781 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1782 # start with a shorter timeout for initial testing
1783 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1784 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1787 # We do want clients to cache if they can, but they *must* check for updates
1788 # on revisiting the page.
1789 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1790 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1791 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1793 if($this->mLastModified
) {
1794 $response->header( "Last-Modified: {$this->mLastModified}" );
1797 wfDebug( __METHOD__
. ": no caching **\n", false );
1799 # In general, the absence of a last modified header should be enough to prevent
1800 # the client from using its cache. We send a few other things just to make sure.
1801 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1802 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1803 $response->header( 'Pragma: no-cache' );
1808 * Get the message associed with the HTTP response code $code
1810 * @param $code Integer: status code
1811 * @return String or null: message or null if $code is not in the list of
1814 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1816 public static function getStatusMessage( $code ) {
1817 wfDeprecated( __METHOD__
);
1818 return HttpStatus
::getMessage( $code );
1822 * Finally, all the text has been munged and accumulated into
1823 * the object, let's actually output it:
1825 public function output() {
1826 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1828 if( $this->mDoNothing
) {
1832 wfProfileIn( __METHOD__
);
1834 $response = $this->getRequest()->response();
1836 if ( $this->mRedirect
!= '' ) {
1837 # Standards require redirect URLs to be absolute
1838 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1839 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1840 if( !$wgDebugRedirects ) {
1841 $message = HttpStatus
::getMessage( $this->mRedirectCode
);
1842 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1844 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1846 $this->sendCacheControl();
1848 $response->header( "Content-Type: text/html; charset=utf-8" );
1849 if( $wgDebugRedirects ) {
1850 $url = htmlspecialchars( $this->mRedirect
);
1851 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1852 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1853 print "</body>\n</html>\n";
1855 $response->header( 'Location: ' . $this->mRedirect
);
1857 wfProfileOut( __METHOD__
);
1859 } elseif ( $this->mStatusCode
) {
1860 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1862 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1866 # Buffer output; final headers may depend on later processing
1869 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1870 $response->header( 'Content-language: ' . $wgLanguageCode );
1872 // Prevent framing, if requested
1873 $frameOptions = $this->getFrameOptions();
1874 if ( $frameOptions ) {
1875 $response->header( "X-Frame-Options: $frameOptions" );
1878 if ( $this->mArticleBodyOnly
) {
1879 $this->out( $this->mBodytext
);
1881 $this->addDefaultModules();
1883 $sk = $this->getSkin();
1885 // Hook that allows last minute changes to the output page, e.g.
1886 // adding of CSS or Javascript by extensions.
1887 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1889 wfProfileIn( 'Output-skin' );
1890 $sk->outputPage( $this );
1891 wfProfileOut( 'Output-skin' );
1894 $this->sendCacheControl();
1896 wfProfileOut( __METHOD__
);
1900 * Actually output something with print().
1902 * @param $ins String: the string to output
1904 public function out( $ins ) {
1909 * Produce a "user is blocked" page.
1910 * @deprecated since 1.18
1912 function blockedPage() {
1913 throw new UserBlockedError( $this->getUser()->mBlock
);
1917 * Output a standard error page
1919 * @param $title String: message key for page title
1920 * @param $msg String: message key for page text
1921 * @param $params Array: message parameters
1923 public function showErrorPage( $title, $msg, $params = array() ) {
1924 if ( $this->getTitle() ) {
1925 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1927 $this->setPageTitle( wfMsg( $title ) );
1928 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1929 $this->setRobotPolicy( 'noindex,nofollow' );
1930 $this->setArticleRelated( false );
1931 $this->enableClientCache( false );
1932 $this->mRedirect
= '';
1933 $this->mBodytext
= '';
1935 $this->addWikiMsgArray( $msg, $params );
1937 $this->returnToMain();
1941 * Output a standard permission error page
1943 * @param $errors Array: error message keys
1944 * @param $action String: action that was denied or null if unknown
1946 public function showPermissionsErrorPage( $errors, $action = null ) {
1947 $this->mDebugtext
.= 'Original title: ' .
1948 $this->getTitle()->getPrefixedText() . "\n";
1949 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1950 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1951 $this->setRobotPolicy( 'noindex,nofollow' );
1952 $this->setArticleRelated( false );
1953 $this->enableClientCache( false );
1954 $this->mRedirect
= '';
1955 $this->mBodytext
= '';
1956 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1960 * Display an error page indicating that a given version of MediaWiki is
1961 * required to use it
1963 * @param $version Mixed: the version of MediaWiki needed to use the page
1965 public function versionRequired( $version ) {
1966 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1967 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1968 $this->setRobotPolicy( 'noindex,nofollow' );
1969 $this->setArticleRelated( false );
1970 $this->mBodytext
= '';
1972 $this->addWikiMsg( 'versionrequiredtext', $version );
1973 $this->returnToMain();
1977 * Display an error page noting that a given permission bit is required.
1978 * @deprecated since 1.18, just throw the exception directly
1979 * @param $permission String: key required
1981 public function permissionRequired( $permission ) {
1982 throw new PermissionsError( $permission );
1986 * Produce the stock "please login to use the wiki" page
1988 public function loginToUse() {
1989 if( $this->getUser()->isLoggedIn() ) {
1990 throw new PermissionsError( 'read' );
1993 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1994 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1995 $this->setRobotPolicy( 'noindex,nofollow' );
1996 $this->setArticleRelated( false );
1998 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1999 $loginLink = Linker
::linkKnown(
2001 wfMsgHtml( 'loginreqlink' ),
2003 array( 'returnto' => $this->getTitle()->getPrefixedText() )
2005 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
2006 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2008 # Don't return to the main page if the user can't read it
2009 # otherwise we'll end up in a pointless loop
2010 $mainPage = Title
::newMainPage();
2011 if( $mainPage->userCanRead() ) {
2012 $this->returnToMain( null, $mainPage );
2017 * Format a list of error messages
2019 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2020 * @param $action String: action that was denied or null if unknown
2021 * @return String: the wikitext error-messages, formatted into a list.
2023 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2024 if ( $action == null ) {
2025 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2027 $action_desc = wfMsgNoTrans( "action-$action" );
2028 $text = wfMsgNoTrans(
2029 'permissionserrorstext-withaction',
2035 if ( count( $errors ) > 1 ) {
2036 $text .= '<ul class="permissions-errors">' . "\n";
2038 foreach( $errors as $error ) {
2040 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2045 $text .= "<div class=\"permissions-errors\">\n" .
2046 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2054 * Display a page stating that the Wiki is in read-only mode,
2055 * and optionally show the source of the page that the user
2056 * was trying to edit. Should only be called (for this
2057 * purpose) after wfReadOnly() has returned true.
2059 * For historical reasons, this function is _also_ used to
2060 * show the error message when a user tries to edit a page
2061 * they are not allowed to edit. (Unless it's because they're
2062 * blocked, then we show blockedPage() instead.) In this
2063 * case, the second parameter should be set to true and a list
2064 * of reasons supplied as the third parameter.
2066 * @todo Needs to be split into multiple functions.
2068 * @param $source String: source code to show (or null).
2069 * @param $protected Boolean: is this a permissions error?
2070 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2071 * @param $action String: action that was denied or null if unknown
2073 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2074 $this->setRobotPolicy( 'noindex,nofollow' );
2075 $this->setArticleRelated( false );
2077 // If no reason is given, just supply a default "I can't let you do
2078 // that, Dave" message. Should only occur if called by legacy code.
2079 if ( $protected && empty( $reasons ) ) {
2080 $reasons[] = array( 'badaccess-group0' );
2083 if ( !empty( $reasons ) ) {
2084 // Permissions error
2086 $this->setPageTitle( wfMsg( 'viewsource' ) );
2088 wfMsg( 'viewsourcefor', Linker
::linkKnown( $this->getTitle() ) )
2091 $this->setPageTitle( wfMsg( 'badaccess' ) );
2093 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2095 // Wiki is read only
2096 throw new ReadOnlyError
;
2099 // Show source, if supplied
2100 if( is_string( $source ) ) {
2101 $this->addWikiMsg( 'viewsourcetext' );
2104 'id' => 'wpTextbox1',
2105 'name' => 'wpTextbox1',
2106 'cols' => $this->getUser()->getOption( 'cols' ),
2107 'rows' => $this->getUser()->getOption( 'rows' ),
2108 'readonly' => 'readonly'
2110 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2112 // Show templates used by this article
2113 $article = new Article( $this->getTitle() );
2114 $templates = Linker
::formatTemplates( $article->getUsedTemplates() );
2115 $this->addHTML( "<div class='templatesUsed'>
2121 # If the title doesn't exist, it's fairly pointless to print a return
2122 # link to it. After all, you just tried editing it and couldn't, so
2123 # what's there to do there?
2124 if( $this->getTitle()->exists() ) {
2125 $this->returnToMain( null, $this->getTitle() );
2130 * Turn off regular page output and return an error reponse
2131 * for when rate limiting has triggered.
2133 public function rateLimited() {
2134 throw new ThrottledError
;
2138 * Show a warning about slave lag
2140 * If the lag is higher than $wgSlaveLagCritical seconds,
2141 * then the warning is a bit more obvious. If the lag is
2142 * lower than $wgSlaveLagWarning, then no warning is shown.
2144 * @param $lag Integer: slave lag
2146 public function showLagWarning( $lag ) {
2147 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2148 if( $lag >= $wgSlaveLagWarning ) {
2149 $message = $lag < $wgSlaveLagCritical
2152 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2153 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2157 public function showFatalError( $message ) {
2158 $this->setPageTitle( wfMsg( 'internalerror' ) );
2159 $this->setRobotPolicy( 'noindex,nofollow' );
2160 $this->setArticleRelated( false );
2161 $this->enableClientCache( false );
2162 $this->mRedirect
= '';
2163 $this->mBodytext
= $message;
2166 public function showUnexpectedValueError( $name, $val ) {
2167 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2170 public function showFileCopyError( $old, $new ) {
2171 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2174 public function showFileRenameError( $old, $new ) {
2175 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2178 public function showFileDeleteError( $name ) {
2179 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2182 public function showFileNotFoundError( $name ) {
2183 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2187 * Add a "return to" link pointing to a specified title
2189 * @param $title Title to link
2190 * @param $query String query string
2191 * @param $text String text of the link (input is not escaped)
2193 public function addReturnTo( $title, $query = array(), $text = null ) {
2194 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2197 Linker
::link( $title, $text, array(), $query )
2199 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2203 * Add a "return to" link pointing to a specified title,
2204 * or the title indicated in the request, or else the main page
2206 * @param $unused No longer used
2207 * @param $returnto Title or String to return to
2208 * @param $returntoquery String: query string for the return to link
2210 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2211 if ( $returnto == null ) {
2212 $returnto = $this->getRequest()->getText( 'returnto' );
2215 if ( $returntoquery == null ) {
2216 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2219 if ( $returnto === '' ) {
2220 $returnto = Title
::newMainPage();
2223 if ( is_object( $returnto ) ) {
2224 $titleObj = $returnto;
2226 $titleObj = Title
::newFromText( $returnto );
2228 if ( !is_object( $titleObj ) ) {
2229 $titleObj = Title
::newMainPage();
2232 $this->addReturnTo( $titleObj, $returntoquery );
2236 * @param $sk Skin The given Skin
2237 * @param $includeStyle Boolean: unused
2238 * @return String: The doctype, opening <html>, and head element.
2240 public function headElement( Skin
$sk, $includeStyle = true ) {
2241 global $wgContLang, $wgUseTrackbacks;
2242 $userdir = $this->getLang()->getDir();
2243 $sitedir = $wgContLang->getDir();
2245 if ( $sk->commonPrintStylesheet() ) {
2246 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2249 $ret = Html
::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir ) );
2251 if ( $this->getHTMLTitle() == '' ) {
2252 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2255 $openHead = Html
::openElement( 'head' );
2257 # Don't bother with the newline if $head == ''
2258 $ret .= "$openHead\n";
2261 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2263 $ret .= implode( "\n", array(
2264 $this->getHeadLinks( null, true ),
2265 $this->buildCssLinks(),
2266 $this->getHeadScripts(),
2267 $this->getHeadItems()
2270 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2271 $ret .= $this->getTitle()->trackbackRDF();
2274 $closeHead = Html
::closeElement( 'head' );
2276 $ret .= "$closeHead\n";
2279 $bodyAttrs = array();
2281 # Classes for LTR/RTL directionality support
2282 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2284 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2285 # A <body> class is probably not the best way to do this . . .
2286 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2288 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2289 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2291 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2292 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2294 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2300 * Add the default ResourceLoader modules to this object
2302 private function addDefaultModules() {
2303 global $wgIncludeLegacyJavaScript, $wgUseAjax,
2304 $wgAjaxWatch, $wgEnableMWSuggest, $wgUseAJAXCategories;
2306 // Add base resources
2307 $this->addModules( array(
2310 'mediawiki.page.startup',
2311 'mediawiki.page.ready',
2313 if ( $wgIncludeLegacyJavaScript ){
2314 $this->addModules( 'mediawiki.legacy.wikibits' );
2317 // Add various resources if required
2319 $this->addModules( 'mediawiki.legacy.ajax' );
2321 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2323 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2324 $this->addModules( 'mediawiki.action.watch.ajax' );
2327 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2328 $this->addModules( 'mediawiki.page.mwsuggest' );
2332 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2333 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2336 # Crazy edit-on-double-click stuff
2337 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2338 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2341 if ( $wgUseAJAXCategories ) {
2342 global $wgAJAXCategoriesNamespaces;
2344 $title = $this->getTitle();
2346 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
2347 $this->addModules( 'mediawiki.page.ajaxCategories.init' );
2353 * Get a ResourceLoader object associated with this OutputPage
2355 * @return ResourceLoader
2357 public function getResourceLoader() {
2358 if ( is_null( $this->mResourceLoader
) ) {
2359 $this->mResourceLoader
= new ResourceLoader();
2361 return $this->mResourceLoader
;
2366 * @param $modules Array/string with the module name
2367 * @param $only String ResourceLoaderModule TYPE_ class constant
2368 * @param $useESI boolean
2369 * @return string html <script> and <style> tags
2371 protected function makeResourceLoaderLink( $modules, $only, $useESI = false ) {
2372 global $wgLoadScript, $wgResourceLoaderUseESI,
2373 $wgResourceLoaderInlinePrivateModules;
2374 // Lazy-load ResourceLoader
2375 // TODO: Should this be a static function of ResourceLoader instead?
2377 'lang' => $this->getContext()->getLang()->getCode(),
2378 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2379 'skin' => $this->getSkin()->getSkinName(),
2381 if ( $only !== ResourceLoaderModule
::TYPE_COMBINED
) {
2382 $baseQuery['only'] = $only;
2384 // Propagate printable and handheld parameters if present
2385 if ( $this->isPrintable() ) {
2386 $baseQuery['printable'] = 1;
2388 if ( $this->getRequest()->getBool( 'handheld' ) ) {
2389 $baseQuery['handheld'] = 1;
2392 if ( !count( $modules ) ) {
2396 if ( count( $modules ) > 1 ) {
2397 // Remove duplicate module requests
2398 $modules = array_unique( (array) $modules );
2399 // Sort module names so requests are more uniform
2402 if ( ResourceLoader
::inDebugMode() ) {
2403 // Recursively call us for every item
2405 foreach ( $modules as $name ) {
2406 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2412 // Create keyed-by-group list of module objects from modules list
2414 $resourceLoader = $this->getResourceLoader();
2415 foreach ( (array) $modules as $name ) {
2416 $module = $resourceLoader->getModule( $name );
2417 # Check that we're allowed to include this module on this page
2418 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2419 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2420 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2421 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2427 $group = $module->getGroup();
2428 if ( !isset( $groups[$group] ) ) {
2429 $groups[$group] = array();
2431 $groups[$group][$name] = $module;
2435 foreach ( $groups as $group => $modules ) {
2436 $query = $baseQuery;
2437 // Special handling for user-specific groups
2438 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2439 $query['user'] = $this->getUser()->getName();
2442 // Create a fake request based on the one we are about to make so modules return
2443 // correct timestamp and emptiness data
2444 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2445 // Drop modules that know they're empty
2446 foreach ( $modules as $key => $module ) {
2447 if ( $module->isKnownEmpty( $context ) ) {
2448 unset( $modules[$key] );
2451 // If there are no modules left, skip this group
2452 if ( $modules === array() ) {
2456 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $modules ) );
2458 // Support inlining of private modules if configured as such
2459 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2460 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2461 $links .= Html
::inlineStyle(
2462 $resourceLoader->makeModuleResponse( $context, $modules )
2465 $links .= Html
::inlineScript(
2466 ResourceLoader
::makeLoaderConditionalScript(
2467 $resourceLoader->makeModuleResponse( $context, $modules )
2474 // Special handling for the user group; because users might change their stuff
2475 // on-wiki like user pages, or user preferences; we need to find the highest
2476 // timestamp of these user-changable modules so we can ensure cache misses on change
2477 // This should NOT be done for the site group (bug 27564) because anons get that too
2478 // and we shouldn't be putting timestamps in Squid-cached HTML
2479 if ( $group === 'user' ) {
2480 // Get the maximum timestamp
2482 foreach ( $modules as $module ) {
2483 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2485 // Add a version parameter so cache will break when things change
2486 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2488 // Make queries uniform in order
2491 $url = wfAppendQuery( $wgLoadScript, $query );
2492 // Prevent the IE6 extension check from being triggered (bug 28840)
2493 // by appending a character that's invalid in Windows extensions ('*')
2495 if ( $useESI && $wgResourceLoaderUseESI ) {
2496 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2497 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2498 $link = Html
::inlineStyle( $esi );
2500 $link = Html
::inlineScript( $esi );
2503 // Automatically select style/script elements
2504 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2505 $link = Html
::linkedStyle( $url );
2507 $link = Html
::linkedScript( $url );
2511 if( $group == 'noscript' ){
2512 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2514 $links .= $link . "\n";
2521 * JS stuff to put in the <head>. This is the startup module, config
2522 * vars and modules marked with position 'top'
2524 * @return String: HTML fragment
2526 function getHeadScripts() {
2527 // Startup - this will immediately load jquery and mediawiki modules
2528 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2530 // Load config before anything else
2531 $scripts .= Html
::inlineScript(
2532 ResourceLoader
::makeLoaderConditionalScript(
2533 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2537 // Script and Messages "only" requests marked for top inclusion
2538 // Messages should go first
2539 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2540 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2542 // Modules requests - let the client calculate dependencies and batch requests as it likes
2543 // Only load modules that have marked themselves for loading at the top
2544 $modules = $this->getModules( true, 'top' );
2546 $scripts .= Html
::inlineScript(
2547 ResourceLoader
::makeLoaderConditionalScript(
2548 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2557 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2558 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2562 function getBottomScripts() {
2563 global $wgUseSiteJs, $wgAllowUserJs;
2565 // Script and Messages "only" requests marked for bottom inclusion
2566 // Messages should go first
2567 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2568 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2570 // Modules requests - let the client calculate dependencies and batch requests as it likes
2571 // Only load modules that have marked themselves for loading at the bottom
2572 $modules = $this->getModules( true, 'bottom' );
2574 $scripts .= Html
::inlineScript(
2575 ResourceLoader
::makeLoaderConditionalScript(
2576 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2582 $scripts .= "\n" . $this->mScripts
;
2584 $userScripts = array( 'user.options', 'user.tokens' );
2586 // Add site JS if enabled
2587 if ( $wgUseSiteJs ) {
2588 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
);
2589 if( $this->getUser()->isLoggedIn() ){
2590 $userScripts[] = 'user.groups';
2594 // Add user JS if enabled
2595 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2596 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2597 # XXX: additional security check/prompt?
2598 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2600 # @todo FIXME: This means that User:Me/Common.js doesn't load when previewing
2601 # User:Me/Vector.js, and vice versa (bug 26283)
2603 // We can't do $userScripts[] = 'user'; because the user module would end up
2604 // being wrapped in a closure, so load it raw like 'site'
2605 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
);
2608 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2614 * Get an array containing global JS variables
2616 * Do not add things here which can be evaluated in
2617 * ResourceLoaderStartupScript - in other words, without state.
2618 * You will only be adding bloat to the page and causing page caches to
2619 * have to be purged on configuration changes.
2621 protected function getJSVars() {
2622 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2624 $title = $this->getTitle();
2625 $ns = $title->getNamespace();
2626 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2627 if ( $ns == NS_SPECIAL
) {
2628 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2630 $canonicalName = false; # bug 21115
2634 'wgCanonicalNamespace' => $nsname,
2635 'wgCanonicalSpecialPageName' => $canonicalName,
2636 'wgNamespaceNumber' => $title->getNamespace(),
2637 'wgPageName' => $title->getPrefixedDBKey(),
2638 'wgTitle' => $title->getText(),
2639 'wgCurRevisionId' => $title->getLatestRevID(),
2640 'wgArticleId' => $title->getArticleId(),
2641 'wgIsArticle' => $this->isArticle(),
2642 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2643 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2644 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2645 'wgCategories' => $this->getCategories(),
2646 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2648 if ( $wgContLang->hasVariants() ) {
2649 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2651 foreach ( $title->getRestrictionTypes() as $type ) {
2652 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2654 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2655 $vars['wgSearchNamespaces'] = SearchEngine
::userNamespaces( $this->getUser() );
2657 if ( $title->isMainPage() ) {
2658 $vars['wgIsMainPage'] = true;
2661 // Allow extensions to add their custom variables to the global JS variables
2662 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2668 * To make it harder for someone to slip a user a fake
2669 * user-JavaScript or user-CSS preview, a random token
2670 * is associated with the login session. If it's not
2671 * passed back with the preview request, we won't render
2676 public function userCanPreview() {
2677 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2678 ||
!$this->getRequest()->wasPosted()
2679 ||
!$this->getUser()->matchEditToken(
2680 $this->getRequest()->getVal( 'wpEditToken' ) )
2684 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2688 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2692 * @param $unused Unused
2693 * @param $addContentType bool
2695 * @return string HTML tag links to be put in the header.
2697 public function getHeadLinks( $unused = null, $addContentType = false ) {
2698 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2699 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2700 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2701 $wgDisableLangConversion, $wgCanonicalLanguageLinks, $wgContLang,
2702 $wgRightsPage, $wgRightsUrl;
2706 if ( $addContentType ) {
2708 # More succinct than <meta http-equiv=Content-Type>, has the
2710 $tags[] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
2712 $tags[] = Html
::element( 'meta', array(
2713 'http-equiv' => 'Content-Type',
2714 'content' => "$wgMimeType; charset=UTF-8"
2716 $tags[] = Html
::element( 'meta', array( // bug 15835
2717 'http-equiv' => 'Content-Style-Type',
2718 'content' => 'text/css'
2723 $tags[] = Html
::element( 'meta', array(
2724 'name' => 'generator',
2725 'content' => "MediaWiki $wgVersion",
2728 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2729 if( $p !== 'index,follow' ) {
2730 // http://www.robotstxt.org/wc/meta-user.html
2731 // Only show if it's different from the default robots policy
2732 $tags[] = Html
::element( 'meta', array(
2738 if ( count( $this->mKeywords
) > 0 ) {
2740 "/<.*?" . ">/" => '',
2743 $tags[] = Html
::element( 'meta', array(
2744 'name' => 'keywords',
2745 'content' => preg_replace(
2746 array_keys( $strip ),
2747 array_values( $strip ),
2748 implode( ',', $this->mKeywords
)
2753 foreach ( $this->mMetatags
as $tag ) {
2754 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2756 $tag[0] = substr( $tag[0], 5 );
2760 $tags[] = Html
::element( 'meta',
2763 'content' => $tag[1]
2768 foreach ( $this->mLinktags
as $tag ) {
2769 $tags[] = Html
::element( 'link', $tag );
2772 # Universal edit button
2773 if ( $wgUniversalEditButton ) {
2774 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2775 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
2776 // Original UniversalEditButton
2777 $msg = wfMsg( 'edit' );
2778 $tags[] = Html
::element( 'link', array(
2779 'rel' => 'alternate',
2780 'type' => 'application/x-wiki',
2782 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2784 // Alternate edit link
2785 $tags[] = Html
::element( 'link', array(
2788 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2793 # Generally the order of the favicon and apple-touch-icon links
2794 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2795 # uses whichever one appears later in the HTML source. Make sure
2796 # apple-touch-icon is specified first to avoid this.
2797 if ( $wgAppleTouchIcon !== false ) {
2798 $tags[] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2801 if ( $wgFavicon !== false ) {
2802 $tags[] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2805 # OpenSearch description link
2806 $tags[] = Html
::element( 'link', array(
2808 'type' => 'application/opensearchdescription+xml',
2809 'href' => wfScript( 'opensearch_desc' ),
2810 'title' => wfMsgForContent( 'opensearch-desc' ),
2813 if ( $wgEnableAPI ) {
2814 # Real Simple Discovery link, provides auto-discovery information
2815 # for the MediaWiki API (and potentially additional custom API
2816 # support such as WordPress or Twitter-compatible APIs for a
2817 # blogging extension, etc)
2818 $tags[] = Html
::element( 'link', array(
2820 'type' => 'application/rsd+xml',
2821 // Output a protocol-relative URL here if $wgServer is protocol-relative
2822 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2823 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROT_RELATIVE
),
2828 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2829 && $wgContLang->hasVariants() ) {
2831 $urlvar = $wgContLang->getURLVariant();
2834 $variants = $wgContLang->getVariants();
2835 foreach ( $variants as $_v ) {
2836 $tags[] = Html
::element( 'link', array(
2837 'rel' => 'alternate',
2839 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2843 $tags[] = Html
::element( 'link', array(
2844 'rel' => 'canonical',
2845 'href' => wfExpandUrl( $this->getTitle()->getFullURL(), PROTO_HTTP
) )
2852 if ( $wgRightsPage ) {
2853 $copy = Title
::newFromText( $wgRightsPage );
2856 $copyright = $copy->getLocalURL();
2860 if ( !$copyright && $wgRightsUrl ) {
2861 $copyright = $wgRightsUrl;
2865 $tags[] = Html
::element( 'link', array(
2866 'rel' => 'copyright',
2867 'href' => $copyright )
2873 foreach( $this->getSyndicationLinks() as $format => $link ) {
2874 # Use the page name for the title. In principle, this could
2875 # lead to issues with having the same name for different feeds
2876 # corresponding to the same page, but we can't avoid that at
2879 $tags[] = $this->feedLink(
2882 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2883 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2887 # Recent changes feed should appear on every page (except recentchanges,
2888 # that would be redundant). Put it after the per-page feed to avoid
2889 # changing existing behavior. It's still available, probably via a
2890 # menu in your browser. Some sites might have a different feed they'd
2891 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2892 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2893 # If so, use it instead.
2895 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2897 if ( $wgOverrideSiteFeed ) {
2898 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2899 $tags[] = $this->feedLink(
2901 htmlspecialchars( $feedUrl ),
2902 wfMsg( "site-{$type}-feed", $wgSitename )
2905 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2906 foreach ( $wgAdvertisedFeedTypes as $format ) {
2907 $tags[] = $this->feedLink(
2909 $rctitle->getLocalURL( "feed={$format}" ),
2910 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2915 return implode( "\n", $tags );
2919 * Generate a <link rel/> for a feed.
2921 * @param $type String: feed type
2922 * @param $url String: URL to the feed
2923 * @param $text String: value of the "title" attribute
2924 * @return String: HTML fragment
2926 private function feedLink( $type, $url, $text ) {
2927 return Html
::element( 'link', array(
2928 'rel' => 'alternate',
2929 'type' => "application/$type+xml",
2936 * Add a local or specified stylesheet, with the given media options.
2937 * Meant primarily for internal use...
2939 * @param $style String: URL to the file
2940 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2941 * @param $condition String: for IE conditional comments, specifying an IE version
2942 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2944 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2946 // Even though we expect the media type to be lowercase, but here we
2947 // force it to lowercase to be safe.
2949 $options['media'] = $media;
2952 $options['condition'] = $condition;
2955 $options['dir'] = $dir;
2957 $this->styles
[$style] = $options;
2961 * Adds inline CSS styles
2962 * @param $style_css Mixed: inline CSS
2964 public function addInlineStyle( $style_css ){
2965 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2969 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2970 * These will be applied to various media & IE conditionals.
2974 public function buildCssLinks() {
2975 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
2977 $this->getSkin()->setupSkinUserCss( $this );
2979 // Add ResourceLoader styles
2980 // Split the styles into four groups
2981 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
2982 $resourceLoader = $this->getResourceLoader();
2984 $moduleStyles = $this->getModuleStyles();
2986 // Per-site custom styles
2987 if ( $wgUseSiteCss ) {
2988 $moduleStyles[] = 'site';
2989 $moduleStyles[] = 'noscript';
2990 if( $this->getUser()->isLoggedIn() ){
2991 $moduleStyles[] = 'user.groups';
2995 // Per-user custom styles
2996 if ( $wgAllowUserCss ) {
2997 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
2998 // @todo FIXME: Properly escape the cdata!
2999 $this->addInlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3001 $moduleStyles[] = 'user';
3005 // Per-user preference styles
3006 if ( $wgAllowUserCssPrefs ) {
3007 $moduleStyles[] = 'user.options';
3010 foreach ( $moduleStyles as $name ) {
3011 $group = $resourceLoader->getModule( $name )->getGroup();
3012 // Modules in groups named "other" or anything different than "user", "site" or "private"
3013 // will be placed in the "other" group
3014 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3017 // We want site, private and user styles to override dynamically added styles from modules, but we want
3018 // dynamically added styles to override statically added styles from other modules. So the order
3019 // has to be other, dynamic, site, private, user
3020 // Add statically added styles for other modules
3021 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3022 // Add normal styles added through addStyle()/addInlineStyle() here
3023 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3024 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3025 // We use a <meta> tag with a made-up name for this because that's valid HTML
3026 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3028 // Add site, private and user styles
3029 // 'private' at present only contains user.options, so put that before 'user'
3030 // Any future private modules will likely have a similar user-specific character
3031 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3032 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3033 ResourceLoaderModule
::TYPE_STYLES
3039 public function buildCssLinksArray() {
3042 // Add any extension CSS
3043 foreach ( $this->mExtStyles
as $url ) {
3044 $this->addStyle( $url );
3046 $this->mExtStyles
= array();
3048 foreach( $this->styles
as $file => $options ) {
3049 $link = $this->styleLink( $file, $options );
3051 $links[$file] = $link;
3058 * Generate \<link\> tags for stylesheets
3060 * @param $style String: URL to the file
3061 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3063 * @return String: HTML fragment
3065 protected function styleLink( $style, $options ) {
3066 if( isset( $options['dir'] ) ) {
3067 if( $this->getLang()->getDir() != $options['dir'] ) {
3072 if( isset( $options['media'] ) ) {
3073 $media = self
::transformCssMedia( $options['media'] );
3074 if( is_null( $media ) ) {
3081 if( substr( $style, 0, 1 ) == '/' ||
3082 substr( $style, 0, 5 ) == 'http:' ||
3083 substr( $style, 0, 6 ) == 'https:' ) {
3086 global $wgStylePath, $wgStyleVersion;
3087 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3090 $link = Html
::linkedStyle( $url, $media );
3092 if( isset( $options['condition'] ) ) {
3093 $condition = htmlspecialchars( $options['condition'] );
3094 $link = "<!--[if $condition]>$link<![endif]-->";
3100 * Transform "media" attribute based on request parameters
3102 * @param $media String: current value of the "media" attribute
3103 * @return String: modified value of the "media" attribute
3105 public static function transformCssMedia( $media ) {
3106 global $wgRequest, $wgHandheldForIPhone;
3108 // Switch in on-screen display for media testing
3110 'printable' => 'print',
3111 'handheld' => 'handheld',
3113 foreach( $switches as $switch => $targetMedia ) {
3114 if( $wgRequest->getBool( $switch ) ) {
3115 if( $media == $targetMedia ) {
3117 } elseif( $media == 'screen' ) {
3123 // Expand longer media queries as iPhone doesn't grok 'handheld'
3124 if( $wgHandheldForIPhone ) {
3125 $mediaAliases = array(
3126 'screen' => 'screen and (min-device-width: 481px)',
3127 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3130 if( isset( $mediaAliases[$media] ) ) {
3131 $media = $mediaAliases[$media];
3139 * Add a wikitext-formatted message to the output.
3140 * This is equivalent to:
3142 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3144 public function addWikiMsg( /*...*/ ) {
3145 $args = func_get_args();
3146 $name = array_shift( $args );
3147 $this->addWikiMsgArray( $name, $args );
3151 * Add a wikitext-formatted message to the output.
3152 * Like addWikiMsg() except the parameters are taken as an array
3153 * instead of a variable argument list.
3155 * $options is passed through to wfMsgExt(), see that function for details.
3157 * @param $name string
3158 * @param $args array
3159 * @param $options array
3161 public function addWikiMsgArray( $name, $args, $options = array() ) {
3162 $options[] = 'parse';
3163 $text = wfMsgExt( $name, $options, $args );
3164 $this->addHTML( $text );
3168 * This function takes a number of message/argument specifications, wraps them in
3169 * some overall structure, and then parses the result and adds it to the output.
3171 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3172 * on. The subsequent arguments may either be strings, in which case they are the
3173 * message names, or arrays, in which case the first element is the message name,
3174 * and subsequent elements are the parameters to that message.
3176 * The special named parameter 'options' in a message specification array is passed
3177 * through to the $options parameter of wfMsgExt().
3179 * Don't use this for messages that are not in users interface language.
3183 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3187 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3189 * The newline after opening div is needed in some wikitext. See bug 19226.
3191 * @param $wrap string
3193 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3194 $msgSpecs = func_get_args();
3195 array_shift( $msgSpecs );
3196 $msgSpecs = array_values( $msgSpecs );
3198 foreach ( $msgSpecs as $n => $spec ) {
3200 if ( is_array( $spec ) ) {
3202 $name = array_shift( $args );
3203 if ( isset( $args['options'] ) ) {
3204 $options = $args['options'];
3205 unset( $args['options'] );
3211 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
3213 $this->addWikiText( $s );
3217 * Include jQuery core. Use this to avoid loading it multiple times
3218 * before we get a usable script loader.
3220 * @param $modules Array: list of jQuery modules which should be loaded
3221 * @return Array: the list of modules which were not loaded.
3223 * @deprecated since 1.17
3225 public function includeJQuery( $modules = array() ) {