3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /// Should be private. Used with addMeta() which adds "<meta>"
40 var $mMetatags = array();
42 /// "<meta keywords='stuff'>" most of the time the first 10 links to an article
43 var $mKeywords = array();
45 var $mLinktags = array();
47 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
48 var $mExtStyles = array();
50 /// Should be private - has getter and setter. Contains the HTML title
53 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
57 * Holds the debug lines that will be output as comments in page source if
58 * $wgDebugComments is enabled. See also $wgShowDebug.
59 * @deprecated since 1.20; use MWDebug class instead.
61 public $mDebugtext = '';
63 /// Should be private. Stores contents of "<title>" tag
66 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
67 var $mIsarticle = false;
70 * Should be private. Has get/set methods properly documented.
71 * Stores "article flag" toggle.
73 var $mIsArticleRelated = true;
76 * Should be private. We have to set isPrintable(). Some pages should
77 * never be printed (ex: redirections).
79 var $mPrintable = false;
82 * Should be private. We have set/get/append methods.
84 * Contains the page subtitle. Special pages usually have some links here.
85 * Don't confuse with site subtitle added by skins.
87 private $mSubtitle = array();
93 * mLastModified and mEtag are used for sending cache control.
94 * The whole caching system should probably be moved into its own class.
96 var $mLastModified = '';
99 * Should be private. No getter but used in sendCacheControl();
100 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
101 * as a unique identifier for the content. It is later used by the client
102 * to compare its cached version with the server version. Client sends
103 * headers If-Match and If-None-Match containing its locally cached ETAG value.
105 * To get more information, you will have to look at HTTP/1.1 protocol which
106 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
110 var $mCategoryLinks = array();
111 var $mCategories = array();
113 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
114 var $mLanguageLinks = array();
117 * Should be private. Used for JavaScript (pre resource loader)
118 * We should split js / css.
119 * mScripts content is inserted as is in "<head>" by Skin. This might
120 * contains either a link to a stylesheet or inline css.
125 * Inline CSS styles. Use addInlineStyle() sparsingly
127 var $mInlineStyles = '';
133 * Used by skin template.
134 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 var $mPageLinkTitle = '';
138 /// Array of elements in "<head>". Parser might add its own headers!
139 var $mHeadItems = array();
141 // @todo FIXME: Next variables probably comes from the resource loader
142 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
143 var $mResourceLoader;
144 var $mJsConfigVars = array();
146 /** @todo FIXME: Is this still used ?*/
147 var $mInlineMsg = array();
149 var $mTemplateIds = array();
150 var $mImageTimeKeys = array();
152 var $mRedirectCode = '';
154 var $mFeedLinksAppendQuery = null;
156 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
157 # @see ResourceLoaderModule::$origin
158 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
159 protected $mAllowedModules = array(
160 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
164 * @EasterEgg I just love the name for this self documenting variable.
167 var $mDoNothing = false;
170 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
173 * lazy initialised, use parserOptions()
176 protected $mParserOptions = null;
179 * Handles the atom / rss links.
180 * We probably only support atom in 2011.
181 * Looks like a private variable.
182 * @see $wgAdvertisedFeedTypes
184 var $mFeedLinks = array();
186 // Gwicke work on squid caching? Roughly from 2003.
187 var $mEnableClientCache = true;
190 * Flag if output should only contain the body of the article.
193 var $mArticleBodyOnly = false;
195 var $mNewSectionLink = false;
196 var $mHideNewSectionLink = false;
199 * Comes from the parser. This was probably made to load CSS/JS only
200 * if we had "<gallery>". Used directly in CategoryPage.php
201 * Looks like resource loader can replace this.
203 var $mNoGallery = false;
205 // should be private.
206 var $mPageTitleActionText = '';
207 var $mParseWarnings = array();
209 // Cache stuff. Looks like mEnableClientCache
210 var $mSquidMaxage = 0;
213 var $mPreventClickjacking = true;
215 /// should be private. To include the variable {{REVISIONID}}
216 var $mRevisionId = null;
217 private $mRevisionTimestamp = null;
219 var $mFileVersion = null;
222 * An array of stylesheet filenames (relative from skins path), with options
223 * for CSS media, IE conditions, and RTL/LTR direction.
224 * For internal use; add settings in the skin via $this->addStyle()
226 * Style again! This seems like a code duplication since we already have
227 * mStyles. This is what makes OpenSource amazing.
229 var $styles = array();
232 * Whether jQuery is already handled.
234 protected $mJQueryDone = false;
236 private $mIndexPolicy = 'index';
237 private $mFollowPolicy = 'follow';
238 private $mVaryHeader = array(
239 'Accept-Encoding' => array( 'list-contains=gzip' ),
243 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
248 private $mRedirectedFrom = null;
251 * Constructor for OutputPage. This should not be called directly.
252 * Instead a new RequestContext should be created and it will implicitly create
253 * a OutputPage tied to that context.
255 function __construct( IContextSource
$context = null ) {
256 if ( $context === null ) {
257 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
258 wfDeprecated( __METHOD__
, '1.18' );
260 $this->setContext( $context );
265 * Redirect to $url rather than displaying the normal page
267 * @param $url String: URL
268 * @param $responsecode String: HTTP status code
270 public function redirect( $url, $responsecode = '302' ) {
271 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
272 $this->mRedirect
= str_replace( "\n", '', $url );
273 $this->mRedirectCode
= $responsecode;
277 * Get the URL to redirect to, or an empty string if not redirect URL set
281 public function getRedirect() {
282 return $this->mRedirect
;
286 * Set the HTTP status code to send with the output.
288 * @param $statusCode Integer
290 public function setStatusCode( $statusCode ) {
291 $this->mStatusCode
= $statusCode;
295 * Add a new "<meta>" tag
296 * To add an http-equiv meta tag, precede the name with "http:"
298 * @param $name String tag name
299 * @param $val String tag value
301 function addMeta( $name, $val ) {
302 array_push( $this->mMetatags
, array( $name, $val ) );
306 * Add a keyword or a list of keywords in the page header
308 * @param $text String or array of strings
310 function addKeyword( $text ) {
311 if( is_array( $text ) ) {
312 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
314 array_push( $this->mKeywords
, $text );
319 * Add a new \<link\> tag to the page header
321 * @param $linkarr Array: associative array of attributes.
323 function addLink( $linkarr ) {
324 array_push( $this->mLinktags
, $linkarr );
328 * Add a new \<link\> with "rel" attribute set to "meta"
330 * @param $linkarr Array: associative array mapping attribute names to their
331 * values, both keys and values will be escaped, and the
332 * "rel" attribute will be automatically added
334 function addMetadataLink( $linkarr ) {
335 $linkarr['rel'] = $this->getMetadataAttribute();
336 $this->addLink( $linkarr );
340 * Get the value of the "rel" attribute for metadata links
344 public function getMetadataAttribute() {
345 # note: buggy CC software only reads first "meta" link
346 static $haveMeta = false;
348 return 'alternate meta';
356 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
358 * @param $script String: raw HTML
360 function addScript( $script ) {
361 $this->mScripts
.= $script . "\n";
365 * Register and add a stylesheet from an extension directory.
367 * @param $url String path to sheet. Provide either a full url (beginning
368 * with 'http', etc) or a relative path from the document root
369 * (beginning with '/'). Otherwise it behaves identically to
370 * addStyle() and draws from the /skins folder.
372 public function addExtensionStyle( $url ) {
373 array_push( $this->mExtStyles
, $url );
377 * Get all styles added by extensions
381 function getExtStyle() {
382 return $this->mExtStyles
;
386 * Add a JavaScript file out of skins/common, or a given relative path.
388 * @param $file String: filename in skins/common or complete on-server path
390 * @param $version String: style version of the file. Defaults to $wgStyleVersion
392 public function addScriptFile( $file, $version = null ) {
393 global $wgStylePath, $wgStyleVersion;
394 // See if $file parameter is an absolute URL or begins with a slash
395 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
398 $path = "{$wgStylePath}/common/{$file}";
400 if ( is_null( $version ) )
401 $version = $wgStyleVersion;
402 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
406 * Add a self-contained script tag with the given contents
408 * @param $script String: JavaScript text, no "<script>" tags
410 public function addInlineScript( $script ) {
411 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
415 * Get all registered JS and CSS tags for the header.
419 function getScript() {
420 return $this->mScripts
. $this->getHeadItems();
424 * Filter an array of modules to remove insufficiently trustworthy members, and modules
425 * which are no longer registered (eg a page is cached before an extension is disabled)
426 * @param $modules Array
427 * @param $position String if not null, only return modules with this position
428 * @param $type string
431 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
){
432 $resourceLoader = $this->getResourceLoader();
433 $filteredModules = array();
434 foreach( $modules as $val ){
435 $module = $resourceLoader->getModule( $val );
436 if( $module instanceof ResourceLoaderModule
437 && $module->getOrigin() <= $this->getAllowedModules( $type )
438 && ( is_null( $position ) ||
$module->getPosition() == $position ) )
440 $filteredModules[] = $val;
443 return $filteredModules;
447 * Get the list of modules to include on this page
449 * @param $filter Bool whether to filter out insufficiently trustworthy modules
450 * @param $position String if not null, only return modules with this position
451 * @param $param string
452 * @return Array of module names
454 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
455 $modules = array_values( array_unique( $this->$param ) );
457 ?
$this->filterModules( $modules, $position )
462 * Add one or more modules recognized by the resource loader. Modules added
463 * through this function will be loaded by the resource loader when the
466 * @param $modules Mixed: module name (string) or array of module names
468 public function addModules( $modules ) {
469 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
473 * Get the list of module JS to include on this page
478 * @return array of module names
480 public function getModuleScripts( $filter = false, $position = null ) {
481 return $this->getModules( $filter, $position, 'mModuleScripts' );
485 * Add only JS of one or more modules recognized by the resource loader. Module
486 * scripts added through this function will be loaded by the resource loader when
489 * @param $modules Mixed: module name (string) or array of module names
491 public function addModuleScripts( $modules ) {
492 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
496 * Get the list of module CSS to include on this page
501 * @return Array of module names
503 public function getModuleStyles( $filter = false, $position = null ) {
504 return $this->getModules( $filter, $position, 'mModuleStyles' );
508 * Add only CSS of one or more modules recognized by the resource loader. Module
509 * styles added through this function will be loaded by the resource loader when
512 * @param $modules Mixed: module name (string) or array of module names
514 public function addModuleStyles( $modules ) {
515 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
519 * Get the list of module messages to include on this page
524 * @return Array of module names
526 public function getModuleMessages( $filter = false, $position = null ) {
527 return $this->getModules( $filter, $position, 'mModuleMessages' );
531 * Add only messages of one or more modules recognized by the resource loader.
532 * Module messages added through this function will be loaded by the resource
533 * loader when the page loads.
535 * @param $modules Mixed: module name (string) or array of module names
537 public function addModuleMessages( $modules ) {
538 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
542 * Get an array of head items
546 function getHeadItemsArray() {
547 return $this->mHeadItems
;
551 * Get all header items in a string
555 function getHeadItems() {
557 foreach ( $this->mHeadItems
as $item ) {
564 * Add or replace an header item to the output
566 * @param $name String: item name
567 * @param $value String: raw HTML
569 public function addHeadItem( $name, $value ) {
570 $this->mHeadItems
[$name] = $value;
574 * Check if the header item $name is already set
576 * @param $name String: item name
579 public function hasHeadItem( $name ) {
580 return isset( $this->mHeadItems
[$name] );
584 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
586 * @param $tag String: value of "ETag" header
588 function setETag( $tag ) {
593 * Set whether the output should only contain the body of the article,
594 * without any skin, sidebar, etc.
595 * Used e.g. when calling with "action=render".
597 * @param $only Boolean: whether to output only the body of the article
599 public function setArticleBodyOnly( $only ) {
600 $this->mArticleBodyOnly
= $only;
604 * Return whether the output will contain only the body of the article
608 public function getArticleBodyOnly() {
609 return $this->mArticleBodyOnly
;
613 * checkLastModified tells the client to use the client-cached page if
614 * possible. If successful, the OutputPage is disabled so that
615 * any future call to OutputPage->output() have no effect.
617 * Side effect: sets mLastModified for Last-Modified header
619 * @param $timestamp string
621 * @return Boolean: true iff cache-ok headers was sent.
623 public function checkLastModified( $timestamp ) {
624 global $wgCachePages, $wgCacheEpoch;
626 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
627 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
630 if( !$wgCachePages ) {
631 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
634 if( $this->getUser()->getOption( 'nocache' ) ) {
635 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
639 $timestamp = wfTimestamp( TS_MW
, $timestamp );
640 $modifiedTimes = array(
641 'page' => $timestamp,
642 'user' => $this->getUser()->getTouched(),
643 'epoch' => $wgCacheEpoch
645 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
647 $maxModified = max( $modifiedTimes );
648 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
650 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
651 if ( $clientHeader === false ) {
652 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
656 # IE sends sizes after the date like this:
657 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
658 # this breaks strtotime().
659 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
661 wfSuppressWarnings(); // E_STRICT system time bitching
662 $clientHeaderTime = strtotime( $clientHeader );
664 if ( !$clientHeaderTime ) {
665 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
668 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
672 foreach ( $modifiedTimes as $name => $value ) {
673 if ( $info !== '' ) {
676 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
679 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
680 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
681 wfDebug( __METHOD__
. ": effective Last-Modified: " .
682 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
683 if( $clientHeaderTime < $maxModified ) {
684 wfDebug( __METHOD__
. ": STALE, $info\n", false );
689 # Give a 304 response code and disable body output
690 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
691 ini_set( 'zlib.output_compression', 0 );
692 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
693 $this->sendCacheControl();
696 // Don't output a compressed blob when using ob_gzhandler;
697 // it's technically against HTTP spec and seems to confuse
698 // Firefox when the response gets split over two packets.
699 wfClearOutputBuffers();
705 * Override the last modified timestamp
707 * @param $timestamp String: new timestamp, in a format readable by
710 public function setLastModified( $timestamp ) {
711 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
715 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
717 * @param $policy String: the literal string to output as the contents of
718 * the meta tag. Will be parsed according to the spec and output in
722 public function setRobotPolicy( $policy ) {
723 $policy = Article
::formatRobotPolicy( $policy );
725 if( isset( $policy['index'] ) ) {
726 $this->setIndexPolicy( $policy['index'] );
728 if( isset( $policy['follow'] ) ) {
729 $this->setFollowPolicy( $policy['follow'] );
734 * Set the index policy for the page, but leave the follow policy un-
737 * @param $policy string Either 'index' or 'noindex'.
740 public function setIndexPolicy( $policy ) {
741 $policy = trim( $policy );
742 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
743 $this->mIndexPolicy
= $policy;
748 * Set the follow policy for the page, but leave the index policy un-
751 * @param $policy String: either 'follow' or 'nofollow'.
754 public function setFollowPolicy( $policy ) {
755 $policy = trim( $policy );
756 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
757 $this->mFollowPolicy
= $policy;
762 * Set the new value of the "action text", this will be added to the
763 * "HTML title", separated from it with " - ".
765 * @param $text String: new value of the "action text"
767 public function setPageTitleActionText( $text ) {
768 $this->mPageTitleActionText
= $text;
772 * Get the value of the "action text"
776 public function getPageTitleActionText() {
777 if ( isset( $this->mPageTitleActionText
) ) {
778 return $this->mPageTitleActionText
;
783 * "HTML title" means the contents of "<title>".
784 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
786 * @param $name string
788 public function setHTMLTitle( $name ) {
789 if ( $name instanceof Message
) {
790 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
792 $this->mHTMLtitle
= $name;
797 * Return the "HTML title", i.e. the content of the "<title>" tag.
801 public function getHTMLTitle() {
802 return $this->mHTMLtitle
;
806 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
810 public function setRedirectedFrom( $t ) {
811 $this->mRedirectedFrom
= $t;
815 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
816 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
817 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
818 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
820 * @param $name string|Message
822 public function setPageTitle( $name ) {
823 if ( $name instanceof Message
) {
824 $name = $name->setContext( $this->getContext() )->text();
827 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
828 # but leave "<i>foobar</i>" alone
829 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
830 $this->mPagetitle
= $nameWithTags;
832 # change "<i>foo&bar</i>" to "foo&bar"
833 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
837 * Return the "page title", i.e. the content of the \<h1\> tag.
841 public function getPageTitle() {
842 return $this->mPagetitle
;
846 * Set the Title object to use
848 * @param $t Title object
850 public function setTitle( Title
$t ) {
851 $this->getContext()->setTitle( $t );
855 * Replace the subtile with $str
857 * @param $str String|Message: new value of the subtitle. String should be safe HTML.
859 public function setSubtitle( $str ) {
860 $this->clearSubtitle();
861 $this->addSubtitle( $str );
865 * Add $str to the subtitle
867 * @deprecated in 1.19; use addSubtitle() instead
868 * @param $str String|Message to add to the subtitle
870 public function appendSubtitle( $str ) {
871 $this->addSubtitle( $str );
875 * Add $str to the subtitle
877 * @param $str String|Message to add to the subtitle. String should be safe HTML.
879 public function addSubtitle( $str ) {
880 if ( $str instanceof Message
) {
881 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
883 $this->mSubtitle
[] = $str;
888 * Add a subtitle containing a backlink to a page
890 * @param $title Title to link to
892 public function addBacklinkSubtitle( Title
$title ) {
894 if ( $title->isRedirect() ) {
895 $query['redirect'] = 'no';
897 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
901 * Clear the subtitles
903 public function clearSubtitle() {
904 $this->mSubtitle
= array();
912 public function getSubtitle() {
913 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
917 * Set the page as printable, i.e. it'll be displayed with with all
918 * print styles included
920 public function setPrintable() {
921 $this->mPrintable
= true;
925 * Return whether the page is "printable"
929 public function isPrintable() {
930 return $this->mPrintable
;
934 * Disable output completely, i.e. calling output() will have no effect
936 public function disable() {
937 $this->mDoNothing
= true;
941 * Return whether the output will be completely disabled
945 public function isDisabled() {
946 return $this->mDoNothing
;
950 * Show an "add new section" link?
954 public function showNewSectionLink() {
955 return $this->mNewSectionLink
;
959 * Forcibly hide the new section link?
963 public function forceHideNewSectionLink() {
964 return $this->mHideNewSectionLink
;
968 * Add or remove feed links in the page header
969 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
970 * for the new version
973 * @param $show Boolean: true: add default feeds, false: remove all feeds
975 public function setSyndicated( $show = true ) {
977 $this->setFeedAppendQuery( false );
979 $this->mFeedLinks
= array();
984 * Add default feeds to the page header
985 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
986 * for the new version
989 * @param $val String: query to append to feed links or false to output
992 public function setFeedAppendQuery( $val ) {
993 global $wgAdvertisedFeedTypes;
995 $this->mFeedLinks
= array();
997 foreach ( $wgAdvertisedFeedTypes as $type ) {
998 $query = "feed=$type";
999 if ( is_string( $val ) ) {
1000 $query .= '&' . $val;
1002 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1007 * Add a feed link to the page header
1009 * @param $format String: feed type, should be a key of $wgFeedClasses
1010 * @param $href String: URL
1012 public function addFeedLink( $format, $href ) {
1013 global $wgAdvertisedFeedTypes;
1015 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1016 $this->mFeedLinks
[$format] = $href;
1021 * Should we output feed links for this page?
1024 public function isSyndicated() {
1025 return count( $this->mFeedLinks
) > 0;
1029 * Return URLs for each supported syndication format for this page.
1030 * @return array associating format keys with URLs
1032 public function getSyndicationLinks() {
1033 return $this->mFeedLinks
;
1037 * Will currently always return null
1041 public function getFeedAppendQuery() {
1042 return $this->mFeedLinksAppendQuery
;
1046 * Set whether the displayed content is related to the source of the
1047 * corresponding article on the wiki
1048 * Setting true will cause the change "article related" toggle to true
1052 public function setArticleFlag( $v ) {
1053 $this->mIsarticle
= $v;
1055 $this->mIsArticleRelated
= $v;
1060 * Return whether the content displayed page is related to the source of
1061 * the corresponding article on the wiki
1065 public function isArticle() {
1066 return $this->mIsarticle
;
1070 * Set whether this page is related an article on the wiki
1071 * Setting false will cause the change of "article flag" toggle to false
1075 public function setArticleRelated( $v ) {
1076 $this->mIsArticleRelated
= $v;
1078 $this->mIsarticle
= false;
1083 * Return whether this page is related an article on the wiki
1087 public function isArticleRelated() {
1088 return $this->mIsArticleRelated
;
1092 * Add new language links
1094 * @param $newLinkArray array Associative array mapping language code to the page
1097 public function addLanguageLinks( $newLinkArray ) {
1098 $this->mLanguageLinks +
= $newLinkArray;
1102 * Reset the language links and add new language links
1104 * @param $newLinkArray array Associative array mapping language code to the page
1107 public function setLanguageLinks( $newLinkArray ) {
1108 $this->mLanguageLinks
= $newLinkArray;
1112 * Get the list of language links
1114 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1116 public function getLanguageLinks() {
1117 return $this->mLanguageLinks
;
1121 * Add an array of categories, with names in the keys
1123 * @param $categories Array mapping category name => sort key
1125 public function addCategoryLinks( $categories ) {
1128 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1132 # Add the links to a LinkBatch
1133 $arr = array( NS_CATEGORY
=> $categories );
1134 $lb = new LinkBatch
;
1135 $lb->setArray( $arr );
1137 # Fetch existence plus the hiddencat property
1138 $dbr = wfGetDB( DB_SLAVE
);
1139 $res = $dbr->select( array( 'page', 'page_props' ),
1140 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1141 $lb->constructSet( 'page', $dbr ),
1144 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1147 # Add the results to the link cache
1148 $lb->addResultToCache( LinkCache
::singleton(), $res );
1150 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1151 $categories = array_combine(
1152 array_keys( $categories ),
1153 array_fill( 0, count( $categories ), 'normal' )
1156 # Mark hidden categories
1157 foreach ( $res as $row ) {
1158 if ( isset( $row->pp_value
) ) {
1159 $categories[$row->page_title
] = 'hidden';
1163 # Add the remaining categories to the skin
1164 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1165 foreach ( $categories as $category => $type ) {
1166 $origcategory = $category;
1167 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1168 $wgContLang->findVariantLink( $category, $title, true );
1169 if ( $category != $origcategory ) {
1170 if ( array_key_exists( $category, $categories ) ) {
1174 $text = $wgContLang->convertHtml( $title->getText() );
1175 $this->mCategories
[] = $title->getText();
1176 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1182 * Reset the category links (but not the category list) and add $categories
1184 * @param $categories Array mapping category name => sort key
1186 public function setCategoryLinks( $categories ) {
1187 $this->mCategoryLinks
= array();
1188 $this->addCategoryLinks( $categories );
1192 * Get the list of category links, in a 2-D array with the following format:
1193 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1194 * hidden categories) and $link a HTML fragment with a link to the category
1199 public function getCategoryLinks() {
1200 return $this->mCategoryLinks
;
1204 * Get the list of category names this page belongs to
1206 * @return Array of strings
1208 public function getCategories() {
1209 return $this->mCategories
;
1213 * Do not allow scripts which can be modified by wiki users to load on this page;
1214 * only allow scripts bundled with, or generated by, the software.
1216 public function disallowUserJs() {
1217 $this->reduceAllowedModules(
1218 ResourceLoaderModule
::TYPE_SCRIPTS
,
1219 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1224 * Return whether user JavaScript is allowed for this page
1225 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1226 * trustworthiness is identified and enforced automagically.
1227 * Will be removed in 1.20.
1230 public function isUserJsAllowed() {
1231 wfDeprecated( __METHOD__
, '1.18' );
1232 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1236 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1237 * @see ResourceLoaderModule::$origin
1238 * @param $type String ResourceLoaderModule TYPE_ constant
1239 * @return Int ResourceLoaderModule ORIGIN_ class constant
1241 public function getAllowedModules( $type ){
1242 if( $type == ResourceLoaderModule
::TYPE_COMBINED
){
1243 return min( array_values( $this->mAllowedModules
) );
1245 return isset( $this->mAllowedModules
[$type] )
1246 ?
$this->mAllowedModules
[$type]
1247 : ResourceLoaderModule
::ORIGIN_ALL
;
1252 * Set the highest level of CSS/JS untrustworthiness allowed
1253 * @param $type String ResourceLoaderModule TYPE_ constant
1254 * @param $level Int ResourceLoaderModule class constant
1256 public function setAllowedModules( $type, $level ){
1257 $this->mAllowedModules
[$type] = $level;
1261 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1262 * @param $type String
1263 * @param $level Int ResourceLoaderModule class constant
1265 public function reduceAllowedModules( $type, $level ){
1266 $this->mAllowedModules
[$type] = min( $this->getAllowedModules($type), $level );
1270 * Prepend $text to the body HTML
1272 * @param $text String: HTML
1274 public function prependHTML( $text ) {
1275 $this->mBodytext
= $text . $this->mBodytext
;
1279 * Append $text to the body HTML
1281 * @param $text String: HTML
1283 public function addHTML( $text ) {
1284 $this->mBodytext
.= $text;
1288 * Shortcut for adding an Html::element via addHTML.
1292 * @param $element string
1293 * @param $attribs array
1294 * @param $contents string
1296 public function addElement( $element, $attribs = array(), $contents = '' ) {
1297 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1301 * Clear the body HTML
1303 public function clearHTML() {
1304 $this->mBodytext
= '';
1310 * @return String: HTML
1312 public function getHTML() {
1313 return $this->mBodytext
;
1317 * Get/set the ParserOptions object to use for wikitext parsing
1319 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1320 * current ParserOption object
1321 * @return ParserOptions object
1323 public function parserOptions( $options = null ) {
1324 if ( !$this->mParserOptions
) {
1325 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1326 $this->mParserOptions
->setEditSection( false );
1328 return wfSetVar( $this->mParserOptions
, $options );
1332 * Set the revision ID which will be seen by the wiki text parser
1333 * for things such as embedded {{REVISIONID}} variable use.
1335 * @param $revid Mixed: an positive integer, or null
1336 * @return Mixed: previous value
1338 public function setRevisionId( $revid ) {
1339 $val = is_null( $revid ) ?
null : intval( $revid );
1340 return wfSetVar( $this->mRevisionId
, $val );
1344 * Get the displayed revision ID
1348 public function getRevisionId() {
1349 return $this->mRevisionId
;
1353 * Set the timestamp of the revision which will be displayed. This is used
1354 * to avoid a extra DB call in Skin::lastModified().
1356 * @param $timestamp Mixed: string, or null
1357 * @return Mixed: previous value
1359 public function setRevisionTimestamp( $timestamp) {
1360 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1364 * Get the timestamp of displayed revision.
1365 * This will be null if not filled by setRevisionTimestamp().
1367 * @return String or null
1369 public function getRevisionTimestamp() {
1370 return $this->mRevisionTimestamp
;
1374 * Set the displayed file version
1376 * @param $file File|bool
1377 * @return Mixed: previous value
1379 public function setFileVersion( $file ) {
1381 if ( $file instanceof File
&& $file->exists() ) {
1382 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1384 return wfSetVar( $this->mFileVersion
, $val, true );
1388 * Get the displayed file version
1390 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1392 public function getFileVersion() {
1393 return $this->mFileVersion
;
1397 * Get the templates used on this page
1399 * @return Array (namespace => dbKey => revId)
1402 public function getTemplateIds() {
1403 return $this->mTemplateIds
;
1407 * Get the files used on this page
1409 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1412 public function getFileSearchOptions() {
1413 return $this->mImageTimeKeys
;
1417 * Convert wikitext to HTML and add it to the buffer
1418 * Default assumes that the current page title will be used.
1420 * @param $text String
1421 * @param $linestart Boolean: is this the start of a line?
1422 * @param $interface Boolean: is this text in the user interface language?
1424 public function addWikiText( $text, $linestart = true, $interface = true ) {
1425 $title = $this->getTitle(); // Work arround E_STRICT
1426 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1430 * Add wikitext with a custom Title object
1432 * @param $text String: wikitext
1433 * @param $title Title object
1434 * @param $linestart Boolean: is this the start of a line?
1436 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1437 $this->addWikiTextTitle( $text, $title, $linestart );
1441 * Add wikitext with a custom Title object and tidy enabled.
1443 * @param $text String: wikitext
1444 * @param $title Title object
1445 * @param $linestart Boolean: is this the start of a line?
1447 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1448 $this->addWikiTextTitle( $text, $title, $linestart, true );
1452 * Add wikitext with tidy enabled
1454 * @param $text String: wikitext
1455 * @param $linestart Boolean: is this the start of a line?
1457 public function addWikiTextTidy( $text, $linestart = true ) {
1458 $title = $this->getTitle();
1459 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1463 * Add wikitext with a custom Title object
1465 * @param $text String: wikitext
1466 * @param $title Title object
1467 * @param $linestart Boolean: is this the start of a line?
1468 * @param $tidy Boolean: whether to use tidy
1469 * @param $interface Boolean: whether it is an interface message
1470 * (for example disables conversion)
1472 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1475 wfProfileIn( __METHOD__
);
1477 $popts = $this->parserOptions();
1478 $oldTidy = $popts->setTidy( $tidy );
1479 $popts->setInterfaceMessage( (bool) $interface );
1481 $parserOutput = $wgParser->parse(
1482 $text, $title, $popts,
1483 $linestart, true, $this->mRevisionId
1486 $popts->setTidy( $oldTidy );
1488 $this->addParserOutput( $parserOutput );
1490 wfProfileOut( __METHOD__
);
1494 * Add a ParserOutput object, but without Html
1496 * @param $parserOutput ParserOutput object
1498 public function addParserOutputNoText( &$parserOutput ) {
1499 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1500 $this->addCategoryLinks( $parserOutput->getCategories() );
1501 $this->mNewSectionLink
= $parserOutput->getNewSection();
1502 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1504 $this->mParseWarnings
= $parserOutput->getWarnings();
1505 if ( !$parserOutput->isCacheable() ) {
1506 $this->enableClientCache( false );
1508 $this->mNoGallery
= $parserOutput->getNoGallery();
1509 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1510 $this->addModules( $parserOutput->getModules() );
1511 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1512 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1513 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1515 // Template versioning...
1516 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1517 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1518 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1520 $this->mTemplateIds
[$ns] = $dbks;
1523 // File versioning...
1524 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1525 $this->mImageTimeKeys
[$dbk] = $data;
1528 // Hooks registered in the object
1529 global $wgParserOutputHooks;
1530 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1531 list( $hookName, $data ) = $hookInfo;
1532 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1533 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1537 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1541 * Add a ParserOutput object
1543 * @param $parserOutput ParserOutput
1545 function addParserOutput( &$parserOutput ) {
1546 $this->addParserOutputNoText( $parserOutput );
1547 $text = $parserOutput->getText();
1548 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1549 $this->addHTML( $text );
1554 * Add the output of a QuickTemplate to the output buffer
1556 * @param $template QuickTemplate
1558 public function addTemplate( &$template ) {
1560 $template->execute();
1561 $this->addHTML( ob_get_contents() );
1566 * Parse wikitext and return the HTML.
1568 * @param $text String
1569 * @param $linestart Boolean: is this the start of a line?
1570 * @param $interface Boolean: use interface language ($wgLang instead of
1571 * $wgContLang) while parsing language sensitive magic
1572 * words like GRAMMAR and PLURAL. This also disables
1573 * LanguageConverter.
1574 * @param $language Language object: target language object, will override
1576 * @throws MWException
1577 * @return String: HTML
1579 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1582 if( is_null( $this->getTitle() ) ) {
1583 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1586 $popts = $this->parserOptions();
1588 $popts->setInterfaceMessage( true );
1590 if ( $language !== null ) {
1591 $oldLang = $popts->setTargetLanguage( $language );
1594 $parserOutput = $wgParser->parse(
1595 $text, $this->getTitle(), $popts,
1596 $linestart, true, $this->mRevisionId
1600 $popts->setInterfaceMessage( false );
1602 if ( $language !== null ) {
1603 $popts->setTargetLanguage( $oldLang );
1606 return $parserOutput->getText();
1610 * Parse wikitext, strip paragraphs, and return the HTML.
1612 * @param $text String
1613 * @param $linestart Boolean: is this the start of a line?
1614 * @param $interface Boolean: use interface language ($wgLang instead of
1615 * $wgContLang) while parsing language sensitive magic
1616 * words like GRAMMAR and PLURAL
1617 * @return String: HTML
1619 public function parseInline( $text, $linestart = true, $interface = false ) {
1620 $parsed = $this->parse( $text, $linestart, $interface );
1623 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1631 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1633 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1635 public function setSquidMaxage( $maxage ) {
1636 $this->mSquidMaxage
= $maxage;
1640 * Use enableClientCache(false) to force it to send nocache headers
1642 * @param $state bool
1646 public function enableClientCache( $state ) {
1647 return wfSetVar( $this->mEnableClientCache
, $state );
1651 * Get the list of cookies that will influence on the cache
1655 function getCacheVaryCookies() {
1656 global $wgCookiePrefix, $wgCacheVaryCookies;
1658 if ( $cookies === null ) {
1659 $cookies = array_merge(
1661 "{$wgCookiePrefix}Token",
1662 "{$wgCookiePrefix}LoggedOut",
1667 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1673 * Check if the request has a cache-varying cookie header
1674 * If it does, it's very important that we don't allow public caching
1678 function haveCacheVaryCookies() {
1679 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1680 if ( $cookieHeader === false ) {
1683 $cvCookies = $this->getCacheVaryCookies();
1684 foreach ( $cvCookies as $cookieName ) {
1685 # Check for a simple string match, like the way squid does it
1686 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1687 wfDebug( __METHOD__
. ": found $cookieName\n" );
1691 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1696 * Add an HTTP header that will influence on the cache
1698 * @param $header String: header name
1699 * @param $option Array|null
1700 * @todo FIXME: Document the $option parameter; it appears to be for
1701 * X-Vary-Options but what format is acceptable?
1703 public function addVaryHeader( $header, $option = null ) {
1704 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1705 $this->mVaryHeader
[$header] = (array)$option;
1706 } elseif( is_array( $option ) ) {
1707 if( is_array( $this->mVaryHeader
[$header] ) ) {
1708 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1710 $this->mVaryHeader
[$header] = $option;
1713 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1717 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1718 * such as Accept-Encoding or Cookie
1722 public function getVaryHeader() {
1723 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1727 * Get a complete X-Vary-Options header
1731 public function getXVO() {
1732 $cvCookies = $this->getCacheVaryCookies();
1734 $cookiesOption = array();
1735 foreach ( $cvCookies as $cookieName ) {
1736 $cookiesOption[] = 'string-contains=' . $cookieName;
1738 $this->addVaryHeader( 'Cookie', $cookiesOption );
1741 foreach( $this->mVaryHeader
as $header => $option ) {
1742 $newheader = $header;
1743 if ( is_array( $option ) && count( $option ) > 0 ) {
1744 $newheader .= ';' . implode( ';', $option );
1746 $headers[] = $newheader;
1748 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1754 * bug 21672: Add Accept-Language to Vary and XVO headers
1755 * if there's no 'variant' parameter existed in GET.
1758 * /w/index.php?title=Main_page should always be served; but
1759 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1761 function addAcceptLanguage() {
1762 $lang = $this->getTitle()->getPageLanguage();
1763 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1764 $variants = $lang->getVariants();
1765 $aloption = array();
1766 foreach ( $variants as $variant ) {
1767 if( $variant === $lang->getCode() ) {
1770 $aloption[] = 'string-contains=' . $variant;
1772 // IE and some other browsers use BCP 47 standards in
1773 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1774 // We should handle these too.
1775 $variantBCP47 = wfBCP47( $variant );
1776 if ( $variantBCP47 !== $variant ) {
1777 $aloption[] = 'string-contains=' . $variantBCP47;
1781 $this->addVaryHeader( 'Accept-Language', $aloption );
1786 * Set a flag which will cause an X-Frame-Options header appropriate for
1787 * edit pages to be sent. The header value is controlled by
1788 * $wgEditPageFrameOptions.
1790 * This is the default for special pages. If you display a CSRF-protected
1791 * form on an ordinary view page, then you need to call this function.
1793 * @param $enable bool
1795 public function preventClickjacking( $enable = true ) {
1796 $this->mPreventClickjacking
= $enable;
1800 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1801 * This can be called from pages which do not contain any CSRF-protected
1804 public function allowClickjacking() {
1805 $this->mPreventClickjacking
= false;
1809 * Get the X-Frame-Options header value (without the name part), or false
1810 * if there isn't one. This is used by Skin to determine whether to enable
1811 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1815 public function getFrameOptions() {
1816 global $wgBreakFrames, $wgEditPageFrameOptions;
1817 if ( $wgBreakFrames ) {
1819 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1820 return $wgEditPageFrameOptions;
1826 * Send cache control HTTP headers
1828 public function sendCacheControl() {
1829 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1831 $response = $this->getRequest()->response();
1832 if ( $wgUseETag && $this->mETag
) {
1833 $response->header( "ETag: $this->mETag" );
1836 $this->addVaryHeader( 'Cookie' );
1837 $this->addAcceptLanguage();
1839 # don't serve compressed data to clients who can't handle it
1840 # maintain different caches for logged-in users and non-logged in ones
1841 $response->header( $this->getVaryHeader() );
1844 # Add an X-Vary-Options header for Squid with Wikimedia patches
1845 $response->header( $this->getXVO() );
1848 if( $this->mEnableClientCache
) {
1850 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1851 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1855 # We'll purge the proxy cache explicitly, but require end user agents
1856 # to revalidate against the proxy on each visit.
1857 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1858 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1859 # start with a shorter timeout for initial testing
1860 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1861 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1862 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1864 # We'll purge the proxy cache for anons explicitly, but require end user agents
1865 # to revalidate against the proxy on each visit.
1866 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1867 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1868 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1869 # start with a shorter timeout for initial testing
1870 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1871 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1874 # We do want clients to cache if they can, but they *must* check for updates
1875 # on revisiting the page.
1876 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1877 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1878 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1880 if($this->mLastModified
) {
1881 $response->header( "Last-Modified: {$this->mLastModified}" );
1884 wfDebug( __METHOD__
. ": no caching **\n", false );
1886 # In general, the absence of a last modified header should be enough to prevent
1887 # the client from using its cache. We send a few other things just to make sure.
1888 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1889 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1890 $response->header( 'Pragma: no-cache' );
1895 * Get the message associed with the HTTP response code $code
1897 * @param $code Integer: status code
1898 * @return String or null: message or null if $code is not in the list of
1901 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1903 public static function getStatusMessage( $code ) {
1904 wfDeprecated( __METHOD__
, '1.18' );
1905 return HttpStatus
::getMessage( $code );
1909 * Finally, all the text has been munged and accumulated into
1910 * the object, let's actually output it:
1912 public function output() {
1913 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1915 if( $this->mDoNothing
) {
1919 wfProfileIn( __METHOD__
);
1921 $response = $this->getRequest()->response();
1923 if ( $this->mRedirect
!= '' ) {
1924 # Standards require redirect URLs to be absolute
1925 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1927 $redirect = $this->mRedirect
;
1928 $code = $this->mRedirectCode
;
1930 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1931 if( $code == '301' ||
$code == '303' ) {
1932 if( !$wgDebugRedirects ) {
1933 $message = HttpStatus
::getMessage( $code );
1934 $response->header( "HTTP/1.1 $code $message" );
1936 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1938 if ( $wgVaryOnXFP ) {
1939 $this->addVaryHeader( 'X-Forwarded-Proto' );
1941 $this->sendCacheControl();
1943 $response->header( "Content-Type: text/html; charset=utf-8" );
1944 if( $wgDebugRedirects ) {
1945 $url = htmlspecialchars( $redirect );
1946 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1947 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1948 print "</body>\n</html>\n";
1950 $response->header( 'Location: ' . $redirect );
1954 wfProfileOut( __METHOD__
);
1956 } elseif ( $this->mStatusCode
) {
1957 $message = HttpStatus
::getMessage( $this->mStatusCode
);
1959 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1963 # Buffer output; final headers may depend on later processing
1966 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1967 $response->header( 'Content-language: ' . $wgLanguageCode );
1969 // Prevent framing, if requested
1970 $frameOptions = $this->getFrameOptions();
1971 if ( $frameOptions ) {
1972 $response->header( "X-Frame-Options: $frameOptions" );
1975 if ( $this->mArticleBodyOnly
) {
1976 $this->out( $this->mBodytext
);
1978 $this->addDefaultModules();
1980 $sk = $this->getSkin();
1982 // Hook that allows last minute changes to the output page, e.g.
1983 // adding of CSS or Javascript by extensions.
1984 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1986 wfProfileIn( 'Output-skin' );
1988 wfProfileOut( 'Output-skin' );
1991 // This hook allows last minute changes to final overall output by modifying output buffer
1992 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
1994 $this->sendCacheControl();
1998 wfProfileOut( __METHOD__
);
2002 * Actually output something with print().
2004 * @param $ins String: the string to output
2006 public function out( $ins ) {
2011 * Produce a "user is blocked" page.
2012 * @deprecated since 1.18
2014 function blockedPage() {
2015 throw new UserBlockedError( $this->getUser()->mBlock
);
2019 * Prepare this object to display an error page; disable caching and
2020 * indexing, clear the current text and redirect, set the page's title
2021 * and optionally an custom HTML title (content of the "<title>" tag).
2023 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2024 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2025 * optional, if not passed the "<title>" attribute will be
2026 * based on $pageTitle
2028 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2029 $this->setPageTitle( $pageTitle );
2030 if ( $htmlTitle !== false ) {
2031 $this->setHTMLTitle( $htmlTitle );
2033 $this->setRobotPolicy( 'noindex,nofollow' );
2034 $this->setArticleRelated( false );
2035 $this->enableClientCache( false );
2036 $this->mRedirect
= '';
2037 $this->clearSubtitle();
2042 * Output a standard error page
2044 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2045 * showErrorPage( 'titlemsg', $messageObject );
2046 * showErrorPage( $titleMessageObj, $messageObject );
2048 * @param $title Mixed: message key (string) for page title, or a Message object
2049 * @param $msg Mixed: message key (string) for page text, or a Message object
2050 * @param $params Array: message parameters; ignored if $msg is a Message object
2052 public function showErrorPage( $title, $msg, $params = array() ) {
2053 if( !$title instanceof Message
) {
2054 $title = $this->msg( $title );
2057 $this->prepareErrorPage( $title );
2059 if ( $msg instanceof Message
){
2060 $this->addHTML( $msg->parseAsBlock() );
2062 $this->addWikiMsgArray( $msg, $params );
2065 $this->returnToMain();
2069 * Output a standard permission error page
2071 * @param $errors Array: error message keys
2072 * @param $action String: action that was denied or null if unknown
2074 public function showPermissionsErrorPage( $errors, $action = null ) {
2075 // For some action (read, edit, create and upload), display a "login to do this action"
2076 // error if all of the following conditions are met:
2077 // 1. the user is not logged in
2078 // 2. the only error is insufficient permissions (i.e. no block or something else)
2079 // 3. the error can be avoided simply by logging in
2080 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2081 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2082 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2083 && ( User
::groupHasPermission( 'user', $action )
2084 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2086 $displayReturnto = null;
2088 # Due to bug 32276, if a user does not have read permissions,
2089 # $this->getTitle() will just give Special:Badtitle, which is
2090 # not especially useful as a returnto parameter. Use the title
2091 # from the request instead, if there was one.
2092 $request = $this->getRequest();
2093 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2094 if ( $action == 'edit' ) {
2095 $msg = 'whitelistedittext';
2096 $displayReturnto = $returnto;
2097 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2098 $msg = 'nocreatetext';
2099 } elseif ( $action == 'upload' ) {
2100 $msg = 'uploadnologintext';
2102 $msg = 'loginreqpagetext';
2103 $displayReturnto = Title
::newMainPage();
2109 $query['returnto'] = $returnto->getPrefixedText();
2111 if ( !$request->wasPosted() ) {
2112 $returntoquery = $request->getValues();
2113 unset( $returntoquery['title'] );
2114 unset( $returntoquery['returnto'] );
2115 unset( $returntoquery['returntoquery'] );
2116 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2119 $loginLink = Linker
::linkKnown(
2120 SpecialPage
::getTitleFor( 'Userlogin' ),
2121 $this->msg( 'loginreqlink' )->escaped(),
2126 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2127 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2129 # Don't return to a page the user can't read otherwise
2130 # we'll end up in a pointless loop
2131 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2132 $this->returnToMain( null, $displayReturnto );
2135 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2136 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2141 * Display an error page indicating that a given version of MediaWiki is
2142 * required to use it
2144 * @param $version Mixed: the version of MediaWiki needed to use the page
2146 public function versionRequired( $version ) {
2147 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2149 $this->addWikiMsg( 'versionrequiredtext', $version );
2150 $this->returnToMain();
2154 * Display an error page noting that a given permission bit is required.
2155 * @deprecated since 1.18, just throw the exception directly
2156 * @param $permission String: key required
2157 * @throws PermissionsError
2159 public function permissionRequired( $permission ) {
2160 throw new PermissionsError( $permission );
2164 * Produce the stock "please login to use the wiki" page
2166 * @deprecated in 1.19; throw the exception directly
2168 public function loginToUse() {
2169 throw new PermissionsError( 'read' );
2173 * Format a list of error messages
2175 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2176 * @param $action String: action that was denied or null if unknown
2177 * @return String: the wikitext error-messages, formatted into a list.
2179 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2180 if ( $action == null ) {
2181 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2183 $action_desc = $this->msg( "action-$action" )->plain();
2185 'permissionserrorstext-withaction',
2188 )->plain() . "\n\n";
2191 if ( count( $errors ) > 1 ) {
2192 $text .= '<ul class="permissions-errors">' . "\n";
2194 foreach( $errors as $error ) {
2196 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2201 $text .= "<div class=\"permissions-errors\">\n" .
2202 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2210 * Display a page stating that the Wiki is in read-only mode,
2211 * and optionally show the source of the page that the user
2212 * was trying to edit. Should only be called (for this
2213 * purpose) after wfReadOnly() has returned true.
2215 * For historical reasons, this function is _also_ used to
2216 * show the error message when a user tries to edit a page
2217 * they are not allowed to edit. (Unless it's because they're
2218 * blocked, then we show blockedPage() instead.) In this
2219 * case, the second parameter should be set to true and a list
2220 * of reasons supplied as the third parameter.
2222 * @todo Needs to be split into multiple functions.
2224 * @param $source String: source code to show (or null).
2225 * @param $protected Boolean: is this a permissions error?
2226 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2227 * @param $action String: action that was denied or null if unknown
2228 * @throws ReadOnlyError
2230 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2231 $this->setRobotPolicy( 'noindex,nofollow' );
2232 $this->setArticleRelated( false );
2234 // If no reason is given, just supply a default "I can't let you do
2235 // that, Dave" message. Should only occur if called by legacy code.
2236 if ( $protected && empty( $reasons ) ) {
2237 $reasons[] = array( 'badaccess-group0' );
2240 if ( !empty( $reasons ) ) {
2241 // Permissions error
2243 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2244 $this->addBacklinkSubtitle( $this->getTitle() );
2246 $this->setPageTitle( $this->msg( 'badaccess' ) );
2248 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2250 // Wiki is read only
2251 throw new ReadOnlyError
;
2254 // Show source, if supplied
2255 if( is_string( $source ) ) {
2256 $this->addWikiMsg( 'viewsourcetext' );
2258 $pageLang = $this->getTitle()->getPageLanguage();
2260 'id' => 'wpTextbox1',
2261 'name' => 'wpTextbox1',
2262 'cols' => $this->getUser()->getOption( 'cols' ),
2263 'rows' => $this->getUser()->getOption( 'rows' ),
2264 'readonly' => 'readonly',
2265 'lang' => $pageLang->getHtmlCode(),
2266 'dir' => $pageLang->getDir(),
2268 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2270 // Show templates used by this article
2271 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2272 $this->addHTML( "<div class='templatesUsed'>
2278 # If the title doesn't exist, it's fairly pointless to print a return
2279 # link to it. After all, you just tried editing it and couldn't, so
2280 # what's there to do there?
2281 if( $this->getTitle()->exists() ) {
2282 $this->returnToMain( null, $this->getTitle() );
2287 * Turn off regular page output and return an error reponse
2288 * for when rate limiting has triggered.
2290 public function rateLimited() {
2291 throw new ThrottledError
;
2295 * Show a warning about slave lag
2297 * If the lag is higher than $wgSlaveLagCritical seconds,
2298 * then the warning is a bit more obvious. If the lag is
2299 * lower than $wgSlaveLagWarning, then no warning is shown.
2301 * @param $lag Integer: slave lag
2303 public function showLagWarning( $lag ) {
2304 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2305 if( $lag >= $wgSlaveLagWarning ) {
2306 $message = $lag < $wgSlaveLagCritical
2309 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2310 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2314 public function showFatalError( $message ) {
2315 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2317 $this->addHTML( $message );
2320 public function showUnexpectedValueError( $name, $val ) {
2321 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2324 public function showFileCopyError( $old, $new ) {
2325 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2328 public function showFileRenameError( $old, $new ) {
2329 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2332 public function showFileDeleteError( $name ) {
2333 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2336 public function showFileNotFoundError( $name ) {
2337 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2341 * Add a "return to" link pointing to a specified title
2343 * @param $title Title to link
2344 * @param $query Array query string parameters
2345 * @param $text String text of the link (input is not escaped)
2346 * @param $options Options array to pass to Linker
2348 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2349 if( in_array( 'http', $options ) ) {
2350 $proto = PROTO_HTTP
;
2351 } elseif( in_array( 'https', $options ) ) {
2352 $proto = PROTO_HTTPS
;
2354 $proto = PROTO_RELATIVE
;
2357 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2358 $link = $this->msg( 'returnto' )->rawParams(
2359 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2360 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2364 * Add a "return to" link pointing to a specified title,
2365 * or the title indicated in the request, or else the main page
2368 * @param $returnto Title or String to return to
2369 * @param $returntoquery String: query string for the return to link
2371 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2372 if ( $returnto == null ) {
2373 $returnto = $this->getRequest()->getText( 'returnto' );
2376 if ( $returntoquery == null ) {
2377 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2380 if ( $returnto === '' ) {
2381 $returnto = Title
::newMainPage();
2384 if ( is_object( $returnto ) ) {
2385 $titleObj = $returnto;
2387 $titleObj = Title
::newFromText( $returnto );
2389 if ( !is_object( $titleObj ) ) {
2390 $titleObj = Title
::newMainPage();
2393 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2397 * @param $sk Skin The given Skin
2398 * @param $includeStyle Boolean: unused
2399 * @return String: The doctype, opening "<html>", and head element.
2401 public function headElement( Skin
$sk, $includeStyle = true ) {
2404 $userdir = $this->getLanguage()->getDir();
2405 $sitedir = $wgContLang->getDir();
2407 if ( $sk->commonPrintStylesheet() ) {
2408 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2411 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2413 if ( $this->getHTMLTitle() == '' ) {
2414 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2417 $openHead = Html
::openElement( 'head' );
2419 # Don't bother with the newline if $head == ''
2420 $ret .= "$openHead\n";
2423 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2425 $ret .= implode( "\n", array(
2426 $this->getHeadLinks( null, true ),
2427 $this->buildCssLinks(),
2428 $this->getHeadScripts(),
2429 $this->getHeadItems()
2432 $closeHead = Html
::closeElement( 'head' );
2434 $ret .= "$closeHead\n";
2437 $bodyAttrs = array();
2439 # Classes for LTR/RTL directionality support
2440 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2442 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2443 # A <body> class is probably not the best way to do this . . .
2444 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2446 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2447 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2448 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2450 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2451 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2453 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2459 * Add the default ResourceLoader modules to this object
2461 private function addDefaultModules() {
2462 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2463 $wgAjaxWatch, $wgResponsiveImages;
2465 // Add base resources
2466 $this->addModules( array(
2468 'mediawiki.page.startup',
2469 'mediawiki.page.ready',
2471 if ( $wgIncludeLegacyJavaScript ){
2472 $this->addModules( 'mediawiki.legacy.wikibits' );
2475 if ( $wgPreloadJavaScriptMwUtil ) {
2476 $this->addModules( 'mediawiki.util' );
2479 MWDebug
::addModules( $this );
2481 // Add various resources if required
2483 $this->addModules( 'mediawiki.legacy.ajax' );
2485 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2487 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2488 $this->addModules( 'mediawiki.page.watch.ajax' );
2491 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2492 $this->addModules( 'mediawiki.searchSuggest' );
2496 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2497 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2500 # Crazy edit-on-double-click stuff
2501 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2502 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2505 // Support for high-density display images
2506 if ( $wgResponsiveImages ) {
2507 $this->addModules( 'mediawiki.hidpi' );
2512 * Get a ResourceLoader object associated with this OutputPage
2514 * @return ResourceLoader
2516 public function getResourceLoader() {
2517 if ( is_null( $this->mResourceLoader
) ) {
2518 $this->mResourceLoader
= new ResourceLoader();
2520 return $this->mResourceLoader
;
2525 * @param $modules Array/string with the module name(s)
2526 * @param $only String ResourceLoaderModule TYPE_ class constant
2527 * @param $useESI boolean
2528 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2529 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2530 * @return string html "<script>" and "<style>" tags
2532 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2533 global $wgResourceLoaderUseESI;
2535 $modules = (array) $modules;
2537 if ( !count( $modules ) ) {
2541 if ( count( $modules ) > 1 ) {
2542 // Remove duplicate module requests
2543 $modules = array_unique( $modules );
2544 // Sort module names so requests are more uniform
2547 if ( ResourceLoader
::inDebugMode() ) {
2548 // Recursively call us for every item
2550 foreach ( $modules as $name ) {
2551 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2557 // Create keyed-by-group list of module objects from modules list
2559 $resourceLoader = $this->getResourceLoader();
2560 foreach ( $modules as $name ) {
2561 $module = $resourceLoader->getModule( $name );
2562 # Check that we're allowed to include this module on this page
2564 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2565 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2566 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2567 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2573 $group = $module->getGroup();
2574 if ( !isset( $groups[$group] ) ) {
2575 $groups[$group] = array();
2577 $groups[$group][$name] = $module;
2581 foreach ( $groups as $group => $grpModules ) {
2582 // Special handling for user-specific groups
2584 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2585 $user = $this->getUser()->getName();
2588 // Create a fake request based on the one we are about to make so modules return
2589 // correct timestamp and emptiness data
2590 $query = ResourceLoader
::makeLoaderQuery(
2591 array(), // modules; not determined yet
2592 $this->getLanguage()->getCode(),
2593 $this->getSkin()->getSkinName(),
2595 null, // version; not determined yet
2596 ResourceLoader
::inDebugMode(),
2597 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2598 $this->isPrintable(),
2599 $this->getRequest()->getBool( 'handheld' ),
2602 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2603 // Extract modules that know they're empty
2604 $emptyModules = array ();
2605 foreach ( $grpModules as $key => $module ) {
2606 if ( $module->isKnownEmpty( $context ) ) {
2607 $emptyModules[$key] = 'ready';
2608 unset( $grpModules[$key] );
2611 // Inline empty modules: since they're empty, just mark them as 'ready'
2612 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2613 // If we're only getting the styles, we don't need to do anything for empty modules.
2614 $links .= Html
::inlineScript(
2616 ResourceLoader
::makeLoaderConditionalScript(
2618 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2625 // If there are no modules left, skip this group
2626 if ( count( $grpModules ) === 0 ) {
2630 // Inline private modules. These can't be loaded through load.php for security
2631 // reasons, see bug 34907. Note that these modules should be loaded from
2632 // getHeadScripts() before the first loader call. Otherwise other modules can't
2633 // properly use them as dependencies (bug 30914)
2634 if ( $group === 'private' ) {
2635 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2636 $links .= Html
::inlineStyle(
2637 $resourceLoader->makeModuleResponse( $context, $grpModules )
2640 $links .= Html
::inlineScript(
2641 ResourceLoader
::makeLoaderConditionalScript(
2642 $resourceLoader->makeModuleResponse( $context, $grpModules )
2649 // Special handling for the user group; because users might change their stuff
2650 // on-wiki like user pages, or user preferences; we need to find the highest
2651 // timestamp of these user-changable modules so we can ensure cache misses on change
2652 // This should NOT be done for the site group (bug 27564) because anons get that too
2653 // and we shouldn't be putting timestamps in Squid-cached HTML
2655 if ( $group === 'user' ) {
2656 // Get the maximum timestamp
2658 foreach ( $grpModules as $module ) {
2659 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2661 // Add a version parameter so cache will break when things change
2662 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2665 $url = ResourceLoader
::makeLoaderURL(
2666 array_keys( $grpModules ),
2667 $this->getLanguage()->getCode(),
2668 $this->getSkin()->getSkinName(),
2671 ResourceLoader
::inDebugMode(),
2672 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2673 $this->isPrintable(),
2674 $this->getRequest()->getBool( 'handheld' ),
2677 if ( $useESI && $wgResourceLoaderUseESI ) {
2678 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2679 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2680 $link = Html
::inlineStyle( $esi );
2682 $link = Html
::inlineScript( $esi );
2685 // Automatically select style/script elements
2686 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2687 $link = Html
::linkedStyle( $url );
2688 } else if ( $loadCall ) {
2689 $link = Html
::inlineScript(
2690 ResourceLoader
::makeLoaderConditionalScript(
2691 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2695 $link = Html
::linkedScript( $url );
2699 if( $group == 'noscript' ){
2700 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2702 $links .= $link . "\n";
2709 * JS stuff to put in the "<head>". This is the startup module, config
2710 * vars and modules marked with position 'top'
2712 * @return String: HTML fragment
2714 function getHeadScripts() {
2715 global $wgResourceLoaderExperimentalAsyncLoading;
2717 // Startup - this will immediately load jquery and mediawiki modules
2718 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2720 // Load config before anything else
2721 $scripts .= Html
::inlineScript(
2722 ResourceLoader
::makeLoaderConditionalScript(
2723 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2727 // Load embeddable private modules before any loader links
2728 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2729 // in mw.loader.implement() calls and deferred until mw.user is available
2730 $embedScripts = array( 'user.options', 'user.tokens' );
2731 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2733 // Script and Messages "only" requests marked for top inclusion
2734 // Messages should go first
2735 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2736 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2738 // Modules requests - let the client calculate dependencies and batch requests as it likes
2739 // Only load modules that have marked themselves for loading at the top
2740 $modules = $this->getModules( true, 'top' );
2742 $scripts .= Html
::inlineScript(
2743 ResourceLoader
::makeLoaderConditionalScript(
2744 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2749 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2750 $scripts .= $this->getScriptsForBottomQueue( true );
2757 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2758 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2759 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2760 * user preferences, site JS and user JS
2762 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2765 function getScriptsForBottomQueue( $inHead ) {
2766 global $wgUseSiteJs, $wgAllowUserJs;
2768 // Script and Messages "only" requests marked for bottom inclusion
2769 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2770 // Messages should go first
2771 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2772 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2773 /* $loadCall = */ $inHead
2775 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2776 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2777 /* $loadCall = */ $inHead
2780 // Modules requests - let the client calculate dependencies and batch requests as it likes
2781 // Only load modules that have marked themselves for loading at the bottom
2782 $modules = $this->getModules( true, 'bottom' );
2784 $scripts .= Html
::inlineScript(
2785 ResourceLoader
::makeLoaderConditionalScript(
2786 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2792 $scripts .= "\n" . $this->mScripts
;
2794 $defaultModules = array();
2796 // Add site JS if enabled
2797 if ( $wgUseSiteJs ) {
2798 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2799 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2801 $defaultModules['site'] = 'loading';
2803 // The wiki is configured to not allow a site module.
2804 $defaultModules['site'] = 'missing';
2807 // Add user JS if enabled
2808 if ( $wgAllowUserJs ) {
2809 if ( $this->getUser()->isLoggedIn() ) {
2810 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2811 # XXX: additional security check/prompt?
2812 // We're on a preview of a JS subpage
2813 // Exclude this page from the user module in case it's in there (bug 26283)
2814 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2815 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2817 // Load the previewed JS
2818 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2819 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2820 // asynchronously and may arrive *after* the inline script here. So the previewed code
2821 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2823 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2824 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2825 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2828 $defaultModules['user'] = 'loading';
2830 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2831 // blocking default gadgets that might depend on it. Although arguably default-enabled
2832 // gadgets should not depend on the user module, it's harmless and less error-prone to
2833 // handle this case.
2834 $defaultModules['user'] = 'ready';
2838 $defaultModules['user'] = 'missing';
2841 // Group JS is only enabled if site JS is enabled.
2842 if ( $wgUseSiteJs ) {
2843 if ( $this->getUser()->isLoggedIn() ) {
2844 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2845 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2847 $defaultModules['user.groups'] = 'loading';
2849 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2850 // avoid blocking gadgets that might depend upon the module.
2851 $defaultModules['user.groups'] = 'ready';
2854 // Site (and group JS) disabled
2855 $defaultModules['user.groups'] = 'missing';
2860 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2861 foreach ( $defaultModules as $m => $state ) {
2862 if ( $state == 'loading' ) {
2863 unset( $defaultModules[$m] );
2867 if ( count( $defaultModules ) > 0 ) {
2868 $loaderInit = Html
::inlineScript(
2869 ResourceLoader
::makeLoaderConditionalScript(
2870 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2874 return $loaderInit . $scripts;
2878 * JS stuff to put at the bottom of the "<body>"
2881 function getBottomScripts() {
2882 global $wgResourceLoaderExperimentalAsyncLoading;
2883 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2884 return $this->getScriptsForBottomQueue( false );
2891 * Add one or more variables to be set in mw.config in JavaScript.
2893 * @param $keys {String|Array} Key or array of key/value pairs.
2894 * @param $value {Mixed} [optional] Value of the configuration variable.
2896 public function addJsConfigVars( $keys, $value = null ) {
2897 if ( is_array( $keys ) ) {
2898 foreach ( $keys as $key => $value ) {
2899 $this->mJsConfigVars
[$key] = $value;
2904 $this->mJsConfigVars
[$keys] = $value;
2909 * Get an array containing the variables to be set in mw.config in JavaScript.
2911 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2912 * This is only public until that function is removed. You have been warned.
2914 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2915 * - in other words, page-independent/site-wide variables (without state).
2916 * You will only be adding bloat to the html page and causing page caches to
2917 * have to be purged on configuration changes.
2920 public function getJSVars() {
2925 $canonicalName = false; # bug 21115
2927 $title = $this->getTitle();
2928 $ns = $title->getNamespace();
2929 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
2931 // Get the relevant title so that AJAX features can use the correct page name
2932 // when making API requests from certain special pages (bug 34972).
2933 $relevantTitle = $this->getSkin()->getRelevantTitle();
2935 if ( $ns == NS_SPECIAL
) {
2936 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
2937 } elseif ( $this->canUseWikiPage() ) {
2938 $wikiPage = $this->getWikiPage();
2939 $latestRevID = $wikiPage->getLatest();
2940 $pageID = $wikiPage->getId();
2943 $lang = $title->getPageLanguage();
2945 // Pre-process information
2946 $separatorTransTable = $lang->separatorTransformTable();
2947 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
2948 $compactSeparatorTransTable = array(
2949 implode( "\t", array_keys( $separatorTransTable ) ),
2950 implode( "\t", $separatorTransTable ),
2952 $digitTransTable = $lang->digitTransformTable();
2953 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
2954 $compactDigitTransTable = array(
2955 implode( "\t", array_keys( $digitTransTable ) ),
2956 implode( "\t", $digitTransTable ),
2960 'wgCanonicalNamespace' => $nsname,
2961 'wgCanonicalSpecialPageName' => $canonicalName,
2962 'wgNamespaceNumber' => $title->getNamespace(),
2963 'wgPageName' => $title->getPrefixedDBKey(),
2964 'wgTitle' => $title->getText(),
2965 'wgCurRevisionId' => $latestRevID,
2966 'wgArticleId' => $pageID,
2967 'wgIsArticle' => $this->isArticle(),
2968 'wgAction' => Action
::getActionName( $this->getContext() ),
2969 'wgUserName' => $this->getUser()->isAnon() ?
null : $this->getUser()->getName(),
2970 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2971 'wgCategories' => $this->getCategories(),
2972 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2973 'wgPageContentLanguage' => $lang->getCode(),
2974 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2975 'wgDigitTransformTable' => $compactDigitTransTable,
2976 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
2977 'wgMonthNames' => $lang->getMonthNamesArray(),
2978 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
2979 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2981 if ( $wgContLang->hasVariants() ) {
2982 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2984 foreach ( $title->getRestrictionTypes() as $type ) {
2985 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2987 if ( $title->isMainPage() ) {
2988 $vars['wgIsMainPage'] = true;
2990 if ( $this->mRedirectedFrom
) {
2991 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBKey();
2994 // Allow extensions to add their custom variables to the mw.config map.
2995 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2996 // page-dependant but site-wide (without state).
2997 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2998 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3000 // Merge in variables from addJsConfigVars last
3001 return array_merge( $vars, $this->mJsConfigVars
);
3005 * To make it harder for someone to slip a user a fake
3006 * user-JavaScript or user-CSS preview, a random token
3007 * is associated with the login session. If it's not
3008 * passed back with the preview request, we won't render
3013 public function userCanPreview() {
3014 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3015 ||
!$this->getRequest()->wasPosted()
3016 ||
!$this->getUser()->matchEditToken(
3017 $this->getRequest()->getVal( 'wpEditToken' ) )
3021 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3025 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3029 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3031 * @return array in format "link name or number => 'link html'".
3033 public function getHeadLinksArray( $addContentType = false ) {
3034 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3035 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3036 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3037 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3038 $wgRightsPage, $wgRightsUrl;
3042 if ( $addContentType ) {
3044 # More succinct than <meta http-equiv=Content-Type>, has the
3046 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3048 $tags['meta-content-type'] = Html
::element( 'meta', array(
3049 'http-equiv' => 'Content-Type',
3050 'content' => "$wgMimeType; charset=UTF-8"
3052 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3053 'http-equiv' => 'Content-Style-Type',
3054 'content' => 'text/css'
3059 $tags['meta-generator'] = Html
::element( 'meta', array(
3060 'name' => 'generator',
3061 'content' => "MediaWiki $wgVersion",
3064 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3065 if( $p !== 'index,follow' ) {
3066 // http://www.robotstxt.org/wc/meta-user.html
3067 // Only show if it's different from the default robots policy
3068 $tags['meta-robots'] = Html
::element( 'meta', array(
3074 if ( count( $this->mKeywords
) > 0 ) {
3076 "/<.*?" . ">/" => '',
3079 $tags['meta-keywords'] = Html
::element( 'meta', array(
3080 'name' => 'keywords',
3081 'content' => preg_replace(
3082 array_keys( $strip ),
3083 array_values( $strip ),
3084 implode( ',', $this->mKeywords
)
3089 foreach ( $this->mMetatags
as $tag ) {
3090 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3092 $tag[0] = substr( $tag[0], 5 );
3096 $tagName = "meta-{$tag[0]}";
3097 if ( isset( $tags[$tagName] ) ) {
3098 $tagName .= $tag[1];
3100 $tags[$tagName] = Html
::element( 'meta',
3103 'content' => $tag[1]
3108 foreach ( $this->mLinktags
as $tag ) {
3109 $tags[] = Html
::element( 'link', $tag );
3112 # Universal edit button
3113 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3114 $user = $this->getUser();
3115 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3116 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3117 // Original UniversalEditButton
3118 $msg = $this->msg( 'edit' )->text();
3119 $tags['universal-edit-button'] = Html
::element( 'link', array(
3120 'rel' => 'alternate',
3121 'type' => 'application/x-wiki',
3123 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3125 // Alternate edit link
3126 $tags['alternative-edit'] = Html
::element( 'link', array(
3129 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3134 # Generally the order of the favicon and apple-touch-icon links
3135 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3136 # uses whichever one appears later in the HTML source. Make sure
3137 # apple-touch-icon is specified first to avoid this.
3138 if ( $wgAppleTouchIcon !== false ) {
3139 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3142 if ( $wgFavicon !== false ) {
3143 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3146 # OpenSearch description link
3147 $tags['opensearch'] = Html
::element( 'link', array(
3149 'type' => 'application/opensearchdescription+xml',
3150 'href' => wfScript( 'opensearch_desc' ),
3151 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3154 if ( $wgEnableAPI ) {
3155 # Real Simple Discovery link, provides auto-discovery information
3156 # for the MediaWiki API (and potentially additional custom API
3157 # support such as WordPress or Twitter-compatible APIs for a
3158 # blogging extension, etc)
3159 $tags['rsd'] = Html
::element( 'link', array(
3161 'type' => 'application/rsd+xml',
3162 // Output a protocol-relative URL here if $wgServer is protocol-relative
3163 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3164 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3170 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3171 $lang = $this->getTitle()->getPageLanguage();
3172 if ( $lang->hasVariants() ) {
3174 $urlvar = $lang->getURLVariant();
3177 $variants = $lang->getVariants();
3178 foreach ( $variants as $_v ) {
3179 $tags["variant-$_v"] = Html
::element( 'link', array(
3180 'rel' => 'alternate',
3182 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3186 $tags['canonical'] = Html
::element( 'link', array(
3187 'rel' => 'canonical',
3188 'href' => $this->getTitle()->getCanonicalUrl()
3196 if ( $wgRightsPage ) {
3197 $copy = Title
::newFromText( $wgRightsPage );
3200 $copyright = $copy->getLocalURL();
3204 if ( !$copyright && $wgRightsUrl ) {
3205 $copyright = $wgRightsUrl;
3209 $tags['copyright'] = Html
::element( 'link', array(
3210 'rel' => 'copyright',
3211 'href' => $copyright )
3217 foreach( $this->getSyndicationLinks() as $format => $link ) {
3218 # Use the page name for the title. In principle, this could
3219 # lead to issues with having the same name for different feeds
3220 # corresponding to the same page, but we can't avoid that at
3223 $tags[] = $this->feedLink(
3226 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3227 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3231 # Recent changes feed should appear on every page (except recentchanges,
3232 # that would be redundant). Put it after the per-page feed to avoid
3233 # changing existing behavior. It's still available, probably via a
3234 # menu in your browser. Some sites might have a different feed they'd
3235 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3236 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3237 # If so, use it instead.
3238 if ( $wgOverrideSiteFeed ) {
3239 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3240 // Note, this->feedLink escapes the url.
3241 $tags[] = $this->feedLink(
3244 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3247 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3248 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3249 foreach ( $wgAdvertisedFeedTypes as $format ) {
3250 $tags[] = $this->feedLink(
3252 $rctitle->getLocalURL( "feed={$format}" ),
3253 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3263 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3265 * @return string HTML tag links to be put in the header.
3267 public function getHeadLinks( $unused = null, $addContentType = false ) {
3268 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3272 * Generate a "<link rel/>" for a feed.
3274 * @param $type String: feed type
3275 * @param $url String: URL to the feed
3276 * @param $text String: value of the "title" attribute
3277 * @return String: HTML fragment
3279 private function feedLink( $type, $url, $text ) {
3280 return Html
::element( 'link', array(
3281 'rel' => 'alternate',
3282 'type' => "application/$type+xml",
3289 * Add a local or specified stylesheet, with the given media options.
3290 * Meant primarily for internal use...
3292 * @param $style String: URL to the file
3293 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3294 * @param $condition String: for IE conditional comments, specifying an IE version
3295 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3297 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3299 // Even though we expect the media type to be lowercase, but here we
3300 // force it to lowercase to be safe.
3302 $options['media'] = $media;
3305 $options['condition'] = $condition;
3308 $options['dir'] = $dir;
3310 $this->styles
[$style] = $options;
3314 * Adds inline CSS styles
3315 * @param $style_css Mixed: inline CSS
3316 * @param $flip String: Set to 'flip' to flip the CSS if needed
3318 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3319 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3320 # If wanted, and the interface is right-to-left, flip the CSS
3321 $style_css = CSSJanus
::transform( $style_css, true, false );
3323 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3327 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3328 * These will be applied to various media & IE conditionals.
3332 public function buildCssLinks() {
3333 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3334 $wgLang, $wgContLang;
3336 $this->getSkin()->setupSkinUserCss( $this );
3338 // Add ResourceLoader styles
3339 // Split the styles into four groups
3340 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3341 $otherTags = ''; // Tags to append after the normal <link> tags
3342 $resourceLoader = $this->getResourceLoader();
3344 $moduleStyles = $this->getModuleStyles();
3346 // Per-site custom styles
3347 if ( $wgUseSiteCss ) {
3348 $moduleStyles[] = 'site';
3349 $moduleStyles[] = 'noscript';
3350 if( $this->getUser()->isLoggedIn() ){
3351 $moduleStyles[] = 'user.groups';
3355 // Per-user custom styles
3356 if ( $wgAllowUserCss ) {
3357 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3358 // We're on a preview of a CSS subpage
3359 // Exclude this page from the user module in case it's in there (bug 26283)
3360 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3361 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3364 // Load the previewed CSS
3365 // If needed, Janus it first. This is user-supplied CSS, so it's
3366 // assumed to be right for the content language directionality.
3367 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3368 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3369 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3371 $otherTags .= Html
::inlineStyle( $previewedCSS );
3373 // Load the user styles normally
3374 $moduleStyles[] = 'user';
3378 // Per-user preference styles
3379 if ( $wgAllowUserCssPrefs ) {
3380 $moduleStyles[] = 'user.cssprefs';
3383 foreach ( $moduleStyles as $name ) {
3384 $module = $resourceLoader->getModule( $name );
3388 $group = $module->getGroup();
3389 // Modules in groups named "other" or anything different than "user", "site" or "private"
3390 // will be placed in the "other" group
3391 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3394 // We want site, private and user styles to override dynamically added styles from modules, but we want
3395 // dynamically added styles to override statically added styles from other modules. So the order
3396 // has to be other, dynamic, site, private, user
3397 // Add statically added styles for other modules
3398 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3399 // Add normal styles added through addStyle()/addInlineStyle() here
3400 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3401 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3402 // We use a <meta> tag with a made-up name for this because that's valid HTML
3403 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3405 // Add site, private and user styles
3406 // 'private' at present only contains user.options, so put that before 'user'
3407 // Any future private modules will likely have a similar user-specific character
3408 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3409 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3410 ResourceLoaderModule
::TYPE_STYLES
3414 // Add stuff in $otherTags (previewed user CSS if applicable)
3422 public function buildCssLinksArray() {
3425 // Add any extension CSS
3426 foreach ( $this->mExtStyles
as $url ) {
3427 $this->addStyle( $url );
3429 $this->mExtStyles
= array();
3431 foreach( $this->styles
as $file => $options ) {
3432 $link = $this->styleLink( $file, $options );
3434 $links[$file] = $link;
3441 * Generate \<link\> tags for stylesheets
3443 * @param $style String: URL to the file
3444 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3446 * @return String: HTML fragment
3448 protected function styleLink( $style, $options ) {
3449 if( isset( $options['dir'] ) ) {
3450 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3455 if( isset( $options['media'] ) ) {
3456 $media = self
::transformCssMedia( $options['media'] );
3457 if( is_null( $media ) ) {
3464 if( substr( $style, 0, 1 ) == '/' ||
3465 substr( $style, 0, 5 ) == 'http:' ||
3466 substr( $style, 0, 6 ) == 'https:' ) {
3469 global $wgStylePath, $wgStyleVersion;
3470 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3473 $link = Html
::linkedStyle( $url, $media );
3475 if( isset( $options['condition'] ) ) {
3476 $condition = htmlspecialchars( $options['condition'] );
3477 $link = "<!--[if $condition]>$link<![endif]-->";
3483 * Transform "media" attribute based on request parameters
3485 * @param $media String: current value of the "media" attribute
3486 * @return String: modified value of the "media" attribute
3488 public static function transformCssMedia( $media ) {
3489 global $wgRequest, $wgHandheldForIPhone;
3491 // Switch in on-screen display for media testing
3493 'printable' => 'print',
3494 'handheld' => 'handheld',
3496 foreach( $switches as $switch => $targetMedia ) {
3497 if( $wgRequest->getBool( $switch ) ) {
3498 if( $media == $targetMedia ) {
3500 } elseif( $media == 'screen' ) {
3506 // Expand longer media queries as iPhone doesn't grok 'handheld'
3507 if( $wgHandheldForIPhone ) {
3508 $mediaAliases = array(
3509 'screen' => 'screen and (min-device-width: 481px)',
3510 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3513 if( isset( $mediaAliases[$media] ) ) {
3514 $media = $mediaAliases[$media];
3522 * Add a wikitext-formatted message to the output.
3523 * This is equivalent to:
3525 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3527 public function addWikiMsg( /*...*/ ) {
3528 $args = func_get_args();
3529 $name = array_shift( $args );
3530 $this->addWikiMsgArray( $name, $args );
3534 * Add a wikitext-formatted message to the output.
3535 * Like addWikiMsg() except the parameters are taken as an array
3536 * instead of a variable argument list.
3538 * @param $name string
3539 * @param $args array
3541 public function addWikiMsgArray( $name, $args ) {
3542 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3546 * This function takes a number of message/argument specifications, wraps them in
3547 * some overall structure, and then parses the result and adds it to the output.
3549 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3550 * on. The subsequent arguments may either be strings, in which case they are the
3551 * message names, or arrays, in which case the first element is the message name,
3552 * and subsequent elements are the parameters to that message.
3554 * Don't use this for messages that are not in users interface language.
3558 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3562 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3564 * The newline after opening div is needed in some wikitext. See bug 19226.
3566 * @param $wrap string
3568 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3569 $msgSpecs = func_get_args();
3570 array_shift( $msgSpecs );
3571 $msgSpecs = array_values( $msgSpecs );
3573 foreach ( $msgSpecs as $n => $spec ) {
3574 if ( is_array( $spec ) ) {
3576 $name = array_shift( $args );
3577 if ( isset( $args['options'] ) ) {
3578 unset( $args['options'] );
3580 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3588 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3590 $this->addWikiText( $s );
3594 * Include jQuery core. Use this to avoid loading it multiple times
3595 * before we get a usable script loader.
3597 * @param $modules Array: list of jQuery modules which should be loaded
3598 * @return Array: the list of modules which were not loaded.
3600 * @deprecated since 1.17
3602 public function includeJQuery( $modules = array() ) {