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();
46 var $mCanonicalUrl = false;
48 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
49 var $mExtStyles = array();
51 /// Should be private - has getter and setter. Contains the HTML title
54 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
58 * Holds the debug lines that will be output as comments in page source if
59 * $wgDebugComments is enabled. See also $wgShowDebug.
60 * @deprecated since 1.20; use MWDebug class instead.
62 public $mDebugtext = '';
64 /// Should be private. Stores contents of "<title>" tag
67 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
68 var $mIsarticle = false;
71 * Should be private. Has get/set methods properly documented.
72 * Stores "article flag" toggle.
74 var $mIsArticleRelated = true;
77 * Should be private. We have to set isPrintable(). Some pages should
78 * never be printed (ex: redirections).
80 var $mPrintable = false;
83 * Should be private. We have set/get/append methods.
85 * Contains the page subtitle. Special pages usually have some links here.
86 * Don't confuse with site subtitle added by skins.
88 private $mSubtitle = array();
94 * mLastModified and mEtag are used for sending cache control.
95 * The whole caching system should probably be moved into its own class.
97 var $mLastModified = '';
100 * Should be private. No getter but used in sendCacheControl();
101 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
102 * as a unique identifier for the content. It is later used by the client
103 * to compare its cached version with the server version. Client sends
104 * headers If-Match and If-None-Match containing its locally cached ETAG value.
106 * To get more information, you will have to look at HTTP/1.1 protocol which
107 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
111 var $mCategoryLinks = array();
112 var $mCategories = array();
114 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
115 var $mLanguageLinks = array();
118 * Should be private. Used for JavaScript (pre resource loader)
119 * We should split js / css.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contains either a link to a stylesheet or inline css.
126 * Inline CSS styles. Use addInlineStyle() sparingly
128 var $mInlineStyles = '';
134 * Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 var $mPageLinkTitle = '';
139 /// Array of elements in "<head>". Parser might add its own headers!
140 var $mHeadItems = array();
142 // @todo FIXME: Next variables probably comes from the resource loader
143 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
144 var $mResourceLoader;
145 var $mJsConfigVars = array();
147 /** @todo FIXME: Is this still used ?*/
148 var $mInlineMsg = array();
150 var $mTemplateIds = array();
151 var $mImageTimeKeys = array();
153 var $mRedirectCode = '';
155 var $mFeedLinksAppendQuery = null;
157 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
158 # @see ResourceLoaderModule::$origin
159 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
160 protected $mAllowedModules = array(
161 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
165 * @EasterEgg I just love the name for this self documenting variable.
168 var $mDoNothing = false;
171 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
174 * lazy initialised, use parserOptions()
177 protected $mParserOptions = null;
180 * Handles the atom / rss links.
181 * We probably only support atom in 2011.
182 * Looks like a private variable.
183 * @see $wgAdvertisedFeedTypes
185 var $mFeedLinks = array();
187 // Gwicke work on squid caching? Roughly from 2003.
188 var $mEnableClientCache = true;
191 * Flag if output should only contain the body of the article.
194 var $mArticleBodyOnly = false;
196 var $mNewSectionLink = false;
197 var $mHideNewSectionLink = false;
200 * Comes from the parser. This was probably made to load CSS/JS only
201 * if we had "<gallery>". Used directly in CategoryPage.php
202 * Looks like resource loader can replace this.
204 var $mNoGallery = false;
206 // should be private.
207 var $mPageTitleActionText = '';
208 var $mParseWarnings = array();
210 // Cache stuff. Looks like mEnableClientCache
211 var $mSquidMaxage = 0;
214 var $mPreventClickjacking = true;
216 /// should be private. To include the variable {{REVISIONID}}
217 var $mRevisionId = null;
218 private $mRevisionTimestamp = null;
220 var $mFileVersion = null;
223 * An array of stylesheet filenames (relative from skins path), with options
224 * for CSS media, IE conditions, and RTL/LTR direction.
225 * For internal use; add settings in the skin via $this->addStyle()
227 * Style again! This seems like a code duplication since we already have
228 * mStyles. This is what makes OpenSource amazing.
230 var $styles = array();
233 * Whether jQuery is already handled.
235 protected $mJQueryDone = false;
237 private $mIndexPolicy = 'index';
238 private $mFollowPolicy = 'follow';
239 private $mVaryHeader = array(
240 'Accept-Encoding' => array( 'list-contains=gzip' ),
244 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
249 private $mRedirectedFrom = null;
252 * Additional key => value data
254 private $mProperties = array();
257 * @var string|null: ResourceLoader target for load.php links. If null, will be omitted
259 private $mTarget = null;
262 * Constructor for OutputPage. This should not be called directly.
263 * Instead a new RequestContext should be created and it will implicitly create
264 * a OutputPage tied to that context.
266 function __construct( IContextSource
$context = null ) {
267 if ( $context === null ) {
268 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
269 wfDeprecated( __METHOD__
, '1.18' );
271 $this->setContext( $context );
276 * Redirect to $url rather than displaying the normal page
278 * @param string $url URL
279 * @param string $responsecode HTTP status code
281 public function redirect( $url, $responsecode = '302' ) {
282 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
283 $this->mRedirect
= str_replace( "\n", '', $url );
284 $this->mRedirectCode
= $responsecode;
288 * Get the URL to redirect to, or an empty string if not redirect URL set
292 public function getRedirect() {
293 return $this->mRedirect
;
297 * Set the HTTP status code to send with the output.
299 * @param $statusCode Integer
301 public function setStatusCode( $statusCode ) {
302 $this->mStatusCode
= $statusCode;
306 * Add a new "<meta>" tag
307 * To add an http-equiv meta tag, precede the name with "http:"
309 * @param string $name tag name
310 * @param string $val tag value
312 function addMeta( $name, $val ) {
313 array_push( $this->mMetatags
, array( $name, $val ) );
317 * Add a keyword or a list of keywords in the page header
319 * @param string $text or array of strings
321 function addKeyword( $text ) {
322 if( is_array( $text ) ) {
323 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
325 array_push( $this->mKeywords
, $text );
330 * Add a new \<link\> tag to the page header.
332 * Note: use setCanonicalUrl() for rel=canonical.
334 * @param array $linkarr associative array of attributes.
336 function addLink( $linkarr ) {
337 array_push( $this->mLinktags
, $linkarr );
341 * Add a new \<link\> with "rel" attribute set to "meta"
343 * @param array $linkarr associative array mapping attribute names to their
344 * values, both keys and values will be escaped, and the
345 * "rel" attribute will be automatically added
347 function addMetadataLink( $linkarr ) {
348 $linkarr['rel'] = $this->getMetadataAttribute();
349 $this->addLink( $linkarr );
353 * Set the URL to be used for the <link rel=canonical>. This should be used
354 * in preference to addLink(), to avoid duplicate link tags.
356 function setCanonicalUrl( $url ) {
357 $this->mCanonicalUrl
= $url;
361 * Get the value of the "rel" attribute for metadata links
365 public function getMetadataAttribute() {
366 # note: buggy CC software only reads first "meta" link
367 static $haveMeta = false;
369 return 'alternate meta';
377 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
379 * @param string $script raw HTML
381 function addScript( $script ) {
382 $this->mScripts
.= $script . "\n";
386 * Register and add a stylesheet from an extension directory.
388 * @param string $url path to sheet. Provide either a full url (beginning
389 * with 'http', etc) or a relative path from the document root
390 * (beginning with '/'). Otherwise it behaves identically to
391 * addStyle() and draws from the /skins folder.
393 public function addExtensionStyle( $url ) {
394 array_push( $this->mExtStyles
, $url );
398 * Get all styles added by extensions
402 function getExtStyle() {
403 return $this->mExtStyles
;
407 * Add a JavaScript file out of skins/common, or a given relative path.
409 * @param string $file filename in skins/common or complete on-server path
411 * @param string $version style version of the file. Defaults to $wgStyleVersion
413 public function addScriptFile( $file, $version = null ) {
414 global $wgStylePath, $wgStyleVersion;
415 // See if $file parameter is an absolute URL or begins with a slash
416 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
419 $path = "{$wgStylePath}/common/{$file}";
421 if ( is_null( $version ) )
422 $version = $wgStyleVersion;
423 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
427 * Add a self-contained script tag with the given contents
429 * @param string $script JavaScript text, no "<script>" tags
431 public function addInlineScript( $script ) {
432 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
436 * Get all registered JS and CSS tags for the header.
440 function getScript() {
441 return $this->mScripts
. $this->getHeadItems();
445 * Filter an array of modules to remove insufficiently trustworthy members, and modules
446 * which are no longer registered (eg a page is cached before an extension is disabled)
447 * @param $modules Array
448 * @param string $position if not null, only return modules with this position
449 * @param $type string
452 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
) {
453 $resourceLoader = $this->getResourceLoader();
454 $filteredModules = array();
455 foreach( $modules as $val ) {
456 $module = $resourceLoader->getModule( $val );
457 if( $module instanceof ResourceLoaderModule
458 && $module->getOrigin() <= $this->getAllowedModules( $type )
459 && ( is_null( $position ) ||
$module->getPosition() == $position )
460 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) ) )
462 $filteredModules[] = $val;
465 return $filteredModules;
469 * Get the list of modules to include on this page
471 * @param bool $filter whether to filter out insufficiently trustworthy modules
472 * @param string $position if not null, only return modules with this position
473 * @param $param string
474 * @return Array of module names
476 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
477 $modules = array_values( array_unique( $this->$param ) );
479 ?
$this->filterModules( $modules, $position )
484 * Add one or more modules recognized by the resource loader. Modules added
485 * through this function will be loaded by the resource loader when the
488 * @param $modules Mixed: module name (string) or array of module names
490 public function addModules( $modules ) {
491 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
495 * Get the list of module JS to include on this page
500 * @return array of module names
502 public function getModuleScripts( $filter = false, $position = null ) {
503 return $this->getModules( $filter, $position, 'mModuleScripts' );
507 * Add only JS of one or more modules recognized by the resource loader. Module
508 * scripts added through this function will be loaded by the resource loader when
511 * @param $modules Mixed: module name (string) or array of module names
513 public function addModuleScripts( $modules ) {
514 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
518 * Get the list of module CSS to include on this page
523 * @return Array of module names
525 public function getModuleStyles( $filter = false, $position = null ) {
526 return $this->getModules( $filter, $position, 'mModuleStyles' );
530 * Add only CSS of one or more modules recognized by the resource loader.
532 * Module styles added through this function will be added using standard link CSS
533 * tags, rather than as a combined Javascript and CSS package. Thus, they will
534 * load when JavaScript is disabled (unless CSS also happens to be disabled).
536 * @param $modules Mixed: module name (string) or array of module names
538 public function addModuleStyles( $modules ) {
539 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
543 * Get the list of module messages to include on this page
548 * @return Array of module names
550 public function getModuleMessages( $filter = false, $position = null ) {
551 return $this->getModules( $filter, $position, 'mModuleMessages' );
555 * Add only messages of one or more modules recognized by the resource loader.
556 * Module messages added through this function will be loaded by the resource
557 * loader when the page loads.
559 * @param $modules Mixed: module name (string) or array of module names
561 public function addModuleMessages( $modules ) {
562 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
566 * @return null|string: ResourceLoader target
568 public function getTarget() {
569 return $this->mTarget
;
573 * Sets ResourceLoader target for load.php links. If null, will be omitted
575 * @param $target string|null
577 public function setTarget( $target ) {
578 $this->mTarget
= $target;
582 * Get an array of head items
586 function getHeadItemsArray() {
587 return $this->mHeadItems
;
591 * Get all header items in a string
595 function getHeadItems() {
597 foreach ( $this->mHeadItems
as $item ) {
604 * Add or replace an header item to the output
606 * @param string $name item name
607 * @param string $value raw HTML
609 public function addHeadItem( $name, $value ) {
610 $this->mHeadItems
[$name] = $value;
614 * Check if the header item $name is already set
616 * @param string $name item name
619 public function hasHeadItem( $name ) {
620 return isset( $this->mHeadItems
[$name] );
624 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
626 * @param string $tag value of "ETag" header
628 function setETag( $tag ) {
633 * Set whether the output should only contain the body of the article,
634 * without any skin, sidebar, etc.
635 * Used e.g. when calling with "action=render".
637 * @param $only Boolean: whether to output only the body of the article
639 public function setArticleBodyOnly( $only ) {
640 $this->mArticleBodyOnly
= $only;
644 * Return whether the output will contain only the body of the article
648 public function getArticleBodyOnly() {
649 return $this->mArticleBodyOnly
;
653 * Set an additional output property
656 * @param string $name
657 * @param mixed $value
659 public function setProperty( $name, $value ) {
660 $this->mProperties
[$name] = $value;
664 * Get an additional output property
668 * @return mixed: Property value or null if not found
670 public function getProperty( $name ) {
671 if ( isset( $this->mProperties
[$name] ) ) {
672 return $this->mProperties
[$name];
679 * checkLastModified tells the client to use the client-cached page if
680 * possible. If successful, the OutputPage is disabled so that
681 * any future call to OutputPage->output() have no effect.
683 * Side effect: sets mLastModified for Last-Modified header
685 * @param $timestamp string
687 * @return Boolean: true iff cache-ok headers was sent.
689 public function checkLastModified( $timestamp ) {
690 global $wgCachePages, $wgCacheEpoch;
692 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
693 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
696 if( !$wgCachePages ) {
697 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
700 if( $this->getUser()->getOption( 'nocache' ) ) {
701 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
705 $timestamp = wfTimestamp( TS_MW
, $timestamp );
706 $modifiedTimes = array(
707 'page' => $timestamp,
708 'user' => $this->getUser()->getTouched(),
709 'epoch' => $wgCacheEpoch
711 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
713 $maxModified = max( $modifiedTimes );
714 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
716 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
717 if ( $clientHeader === false ) {
718 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
722 # IE sends sizes after the date like this:
723 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
724 # this breaks strtotime().
725 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
727 wfSuppressWarnings(); // E_STRICT system time bitching
728 $clientHeaderTime = strtotime( $clientHeader );
730 if ( !$clientHeaderTime ) {
731 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
734 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
738 foreach ( $modifiedTimes as $name => $value ) {
739 if ( $info !== '' ) {
742 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
745 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
746 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
747 wfDebug( __METHOD__
. ": effective Last-Modified: " .
748 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
749 if( $clientHeaderTime < $maxModified ) {
750 wfDebug( __METHOD__
. ": STALE, $info\n", false );
755 # Give a 304 response code and disable body output
756 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
757 ini_set( 'zlib.output_compression', 0 );
758 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
759 $this->sendCacheControl();
762 // Don't output a compressed blob when using ob_gzhandler;
763 // it's technically against HTTP spec and seems to confuse
764 // Firefox when the response gets split over two packets.
765 wfClearOutputBuffers();
771 * Override the last modified timestamp
773 * @param string $timestamp new timestamp, in a format readable by
776 public function setLastModified( $timestamp ) {
777 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
781 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
783 * @param string $policy the literal string to output as the contents of
784 * the meta tag. Will be parsed according to the spec and output in
788 public function setRobotPolicy( $policy ) {
789 $policy = Article
::formatRobotPolicy( $policy );
791 if( isset( $policy['index'] ) ) {
792 $this->setIndexPolicy( $policy['index'] );
794 if( isset( $policy['follow'] ) ) {
795 $this->setFollowPolicy( $policy['follow'] );
800 * Set the index policy for the page, but leave the follow policy un-
803 * @param string $policy Either 'index' or 'noindex'.
806 public function setIndexPolicy( $policy ) {
807 $policy = trim( $policy );
808 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
809 $this->mIndexPolicy
= $policy;
814 * Set the follow policy for the page, but leave the index policy un-
817 * @param string $policy either 'follow' or 'nofollow'.
820 public function setFollowPolicy( $policy ) {
821 $policy = trim( $policy );
822 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
823 $this->mFollowPolicy
= $policy;
828 * Set the new value of the "action text", this will be added to the
829 * "HTML title", separated from it with " - ".
831 * @param string $text new value of the "action text"
833 public function setPageTitleActionText( $text ) {
834 $this->mPageTitleActionText
= $text;
838 * Get the value of the "action text"
842 public function getPageTitleActionText() {
843 if ( isset( $this->mPageTitleActionText
) ) {
844 return $this->mPageTitleActionText
;
850 * "HTML title" means the contents of "<title>".
851 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
853 * @param $name string
855 public function setHTMLTitle( $name ) {
856 if ( $name instanceof Message
) {
857 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
859 $this->mHTMLtitle
= $name;
864 * Return the "HTML title", i.e. the content of the "<title>" tag.
868 public function getHTMLTitle() {
869 return $this->mHTMLtitle
;
873 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
877 public function setRedirectedFrom( $t ) {
878 $this->mRedirectedFrom
= $t;
882 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
883 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
884 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
885 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
887 * @param $name string|Message
889 public function setPageTitle( $name ) {
890 if ( $name instanceof Message
) {
891 $name = $name->setContext( $this->getContext() )->text();
894 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
895 # but leave "<i>foobar</i>" alone
896 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
897 $this->mPagetitle
= $nameWithTags;
899 # change "<i>foo&bar</i>" to "foo&bar"
900 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) ) );
904 * Return the "page title", i.e. the content of the \<h1\> tag.
908 public function getPageTitle() {
909 return $this->mPagetitle
;
913 * Set the Title object to use
915 * @param $t Title object
917 public function setTitle( Title
$t ) {
918 $this->getContext()->setTitle( $t );
922 * Replace the subtitle with $str
924 * @param string|Message $str new value of the subtitle. String should be safe HTML.
926 public function setSubtitle( $str ) {
927 $this->clearSubtitle();
928 $this->addSubtitle( $str );
932 * Add $str to the subtitle
934 * @deprecated in 1.19; use addSubtitle() instead
935 * @param string|Message $str to add to the subtitle
937 public function appendSubtitle( $str ) {
938 $this->addSubtitle( $str );
942 * Add $str to the subtitle
944 * @param string|Message $str to add to the subtitle. String should be safe HTML.
946 public function addSubtitle( $str ) {
947 if ( $str instanceof Message
) {
948 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
950 $this->mSubtitle
[] = $str;
955 * Add a subtitle containing a backlink to a page
957 * @param $title Title to link to
959 public function addBacklinkSubtitle( Title
$title ) {
961 if ( $title->isRedirect() ) {
962 $query['redirect'] = 'no';
964 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
968 * Clear the subtitles
970 public function clearSubtitle() {
971 $this->mSubtitle
= array();
979 public function getSubtitle() {
980 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
984 * Set the page as printable, i.e. it'll be displayed with with all
985 * print styles included
987 public function setPrintable() {
988 $this->mPrintable
= true;
992 * Return whether the page is "printable"
996 public function isPrintable() {
997 return $this->mPrintable
;
1001 * Disable output completely, i.e. calling output() will have no effect
1003 public function disable() {
1004 $this->mDoNothing
= true;
1008 * Return whether the output will be completely disabled
1012 public function isDisabled() {
1013 return $this->mDoNothing
;
1017 * Show an "add new section" link?
1021 public function showNewSectionLink() {
1022 return $this->mNewSectionLink
;
1026 * Forcibly hide the new section link?
1030 public function forceHideNewSectionLink() {
1031 return $this->mHideNewSectionLink
;
1035 * Add or remove feed links in the page header
1036 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1037 * for the new version
1038 * @see addFeedLink()
1040 * @param $show Boolean: true: add default feeds, false: remove all feeds
1042 public function setSyndicated( $show = true ) {
1044 $this->setFeedAppendQuery( false );
1046 $this->mFeedLinks
= array();
1051 * Add default feeds to the page header
1052 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1053 * for the new version
1054 * @see addFeedLink()
1056 * @param string $val query to append to feed links or false to output
1059 public function setFeedAppendQuery( $val ) {
1060 global $wgAdvertisedFeedTypes;
1062 $this->mFeedLinks
= array();
1064 foreach ( $wgAdvertisedFeedTypes as $type ) {
1065 $query = "feed=$type";
1066 if ( is_string( $val ) ) {
1067 $query .= '&' . $val;
1069 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1074 * Add a feed link to the page header
1076 * @param string $format feed type, should be a key of $wgFeedClasses
1077 * @param string $href URL
1079 public function addFeedLink( $format, $href ) {
1080 global $wgAdvertisedFeedTypes;
1082 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1083 $this->mFeedLinks
[$format] = $href;
1088 * Should we output feed links for this page?
1091 public function isSyndicated() {
1092 return count( $this->mFeedLinks
) > 0;
1096 * Return URLs for each supported syndication format for this page.
1097 * @return array associating format keys with URLs
1099 public function getSyndicationLinks() {
1100 return $this->mFeedLinks
;
1104 * Will currently always return null
1108 public function getFeedAppendQuery() {
1109 return $this->mFeedLinksAppendQuery
;
1113 * Set whether the displayed content is related to the source of the
1114 * corresponding article on the wiki
1115 * Setting true will cause the change "article related" toggle to true
1119 public function setArticleFlag( $v ) {
1120 $this->mIsarticle
= $v;
1122 $this->mIsArticleRelated
= $v;
1127 * Return whether the content displayed page is related to the source of
1128 * the corresponding article on the wiki
1132 public function isArticle() {
1133 return $this->mIsarticle
;
1137 * Set whether this page is related an article on the wiki
1138 * Setting false will cause the change of "article flag" toggle to false
1142 public function setArticleRelated( $v ) {
1143 $this->mIsArticleRelated
= $v;
1145 $this->mIsarticle
= false;
1150 * Return whether this page is related an article on the wiki
1154 public function isArticleRelated() {
1155 return $this->mIsArticleRelated
;
1159 * Add new language links
1161 * @param array $newLinkArray Associative array mapping language code to the page
1164 public function addLanguageLinks( $newLinkArray ) {
1165 $this->mLanguageLinks +
= $newLinkArray;
1169 * Reset the language links and add new language links
1171 * @param array $newLinkArray Associative array mapping language code to the page
1174 public function setLanguageLinks( $newLinkArray ) {
1175 $this->mLanguageLinks
= $newLinkArray;
1179 * Get the list of language links
1181 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1183 public function getLanguageLinks() {
1184 return $this->mLanguageLinks
;
1188 * Add an array of categories, with names in the keys
1190 * @param array $categories mapping category name => sort key
1192 public function addCategoryLinks( $categories ) {
1195 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1199 # Add the links to a LinkBatch
1200 $arr = array( NS_CATEGORY
=> $categories );
1201 $lb = new LinkBatch
;
1202 $lb->setArray( $arr );
1204 # Fetch existence plus the hiddencat property
1205 $dbr = wfGetDB( DB_SLAVE
);
1206 $res = $dbr->select( array( 'page', 'page_props' ),
1207 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1208 $lb->constructSet( 'page', $dbr ),
1211 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1214 # Add the results to the link cache
1215 $lb->addResultToCache( LinkCache
::singleton(), $res );
1217 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1218 $categories = array_combine(
1219 array_keys( $categories ),
1220 array_fill( 0, count( $categories ), 'normal' )
1223 # Mark hidden categories
1224 foreach ( $res as $row ) {
1225 if ( isset( $row->pp_value
) ) {
1226 $categories[$row->page_title
] = 'hidden';
1230 # Add the remaining categories to the skin
1231 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1232 foreach ( $categories as $category => $type ) {
1233 $origcategory = $category;
1234 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1235 $wgContLang->findVariantLink( $category, $title, true );
1236 if ( $category != $origcategory ) {
1237 if ( array_key_exists( $category, $categories ) ) {
1241 $text = $wgContLang->convertHtml( $title->getText() );
1242 $this->mCategories
[] = $title->getText();
1243 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1249 * Reset the category links (but not the category list) and add $categories
1251 * @param array $categories mapping category name => sort key
1253 public function setCategoryLinks( $categories ) {
1254 $this->mCategoryLinks
= array();
1255 $this->addCategoryLinks( $categories );
1259 * Get the list of category links, in a 2-D array with the following format:
1260 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1261 * hidden categories) and $link a HTML fragment with a link to the category
1266 public function getCategoryLinks() {
1267 return $this->mCategoryLinks
;
1271 * Get the list of category names this page belongs to
1273 * @return Array of strings
1275 public function getCategories() {
1276 return $this->mCategories
;
1280 * Do not allow scripts which can be modified by wiki users to load on this page;
1281 * only allow scripts bundled with, or generated by, the software.
1283 public function disallowUserJs() {
1284 $this->reduceAllowedModules(
1285 ResourceLoaderModule
::TYPE_SCRIPTS
,
1286 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1291 * Return whether user JavaScript is allowed for this page
1292 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1293 * trustworthiness is identified and enforced automagically.
1294 * Will be removed in 1.20.
1297 public function isUserJsAllowed() {
1298 wfDeprecated( __METHOD__
, '1.18' );
1299 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1303 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1304 * @see ResourceLoaderModule::$origin
1305 * @param string $type ResourceLoaderModule TYPE_ constant
1306 * @return Int ResourceLoaderModule ORIGIN_ class constant
1308 public function getAllowedModules( $type ) {
1309 if( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1310 return min( array_values( $this->mAllowedModules
) );
1312 return isset( $this->mAllowedModules
[$type] )
1313 ?
$this->mAllowedModules
[$type]
1314 : ResourceLoaderModule
::ORIGIN_ALL
;
1319 * Set the highest level of CSS/JS untrustworthiness allowed
1320 * @param $type String ResourceLoaderModule TYPE_ constant
1321 * @param $level Int ResourceLoaderModule class constant
1323 public function setAllowedModules( $type, $level ) {
1324 $this->mAllowedModules
[$type] = $level;
1328 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1329 * @param $type String
1330 * @param $level Int ResourceLoaderModule class constant
1332 public function reduceAllowedModules( $type, $level ) {
1333 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1337 * Prepend $text to the body HTML
1339 * @param string $text HTML
1341 public function prependHTML( $text ) {
1342 $this->mBodytext
= $text . $this->mBodytext
;
1346 * Append $text to the body HTML
1348 * @param string $text HTML
1350 public function addHTML( $text ) {
1351 $this->mBodytext
.= $text;
1355 * Shortcut for adding an Html::element via addHTML.
1359 * @param $element string
1360 * @param $attribs array
1361 * @param $contents string
1363 public function addElement( $element, $attribs = array(), $contents = '' ) {
1364 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1368 * Clear the body HTML
1370 public function clearHTML() {
1371 $this->mBodytext
= '';
1377 * @return String: HTML
1379 public function getHTML() {
1380 return $this->mBodytext
;
1384 * Get/set the ParserOptions object to use for wikitext parsing
1386 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1387 * current ParserOption object
1388 * @return ParserOptions object
1390 public function parserOptions( $options = null ) {
1391 if ( !$this->mParserOptions
) {
1392 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1393 $this->mParserOptions
->setEditSection( false );
1395 return wfSetVar( $this->mParserOptions
, $options );
1399 * Set the revision ID which will be seen by the wiki text parser
1400 * for things such as embedded {{REVISIONID}} variable use.
1402 * @param $revid Mixed: an positive integer, or null
1403 * @return Mixed: previous value
1405 public function setRevisionId( $revid ) {
1406 $val = is_null( $revid ) ?
null : intval( $revid );
1407 return wfSetVar( $this->mRevisionId
, $val );
1411 * Get the displayed revision ID
1415 public function getRevisionId() {
1416 return $this->mRevisionId
;
1420 * Set the timestamp of the revision which will be displayed. This is used
1421 * to avoid a extra DB call in Skin::lastModified().
1423 * @param $timestamp Mixed: string, or null
1424 * @return Mixed: previous value
1426 public function setRevisionTimestamp( $timestamp ) {
1427 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1431 * Get the timestamp of displayed revision.
1432 * This will be null if not filled by setRevisionTimestamp().
1434 * @return String or null
1436 public function getRevisionTimestamp() {
1437 return $this->mRevisionTimestamp
;
1441 * Set the displayed file version
1443 * @param $file File|bool
1444 * @return Mixed: previous value
1446 public function setFileVersion( $file ) {
1448 if ( $file instanceof File
&& $file->exists() ) {
1449 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1451 return wfSetVar( $this->mFileVersion
, $val, true );
1455 * Get the displayed file version
1457 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1459 public function getFileVersion() {
1460 return $this->mFileVersion
;
1464 * Get the templates used on this page
1466 * @return Array (namespace => dbKey => revId)
1469 public function getTemplateIds() {
1470 return $this->mTemplateIds
;
1474 * Get the files used on this page
1476 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1479 public function getFileSearchOptions() {
1480 return $this->mImageTimeKeys
;
1484 * Convert wikitext to HTML and add it to the buffer
1485 * Default assumes that the current page title will be used.
1487 * @param $text String
1488 * @param $linestart Boolean: is this the start of a line?
1489 * @param $interface Boolean: is this text in the user interface language?
1491 public function addWikiText( $text, $linestart = true, $interface = true ) {
1492 $title = $this->getTitle(); // Work around E_STRICT
1494 throw new MWException( 'Title is null' );
1496 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1500 * Add wikitext with a custom Title object
1502 * @param string $text wikitext
1503 * @param $title Title object
1504 * @param $linestart Boolean: is this the start of a line?
1506 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1507 $this->addWikiTextTitle( $text, $title, $linestart );
1511 * Add wikitext with a custom Title object and tidy enabled.
1513 * @param string $text wikitext
1514 * @param $title Title object
1515 * @param $linestart Boolean: is this the start of a line?
1517 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1518 $this->addWikiTextTitle( $text, $title, $linestart, true );
1522 * Add wikitext with tidy enabled
1524 * @param string $text wikitext
1525 * @param $linestart Boolean: is this the start of a line?
1527 public function addWikiTextTidy( $text, $linestart = true ) {
1528 $title = $this->getTitle();
1529 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1533 * Add wikitext with a custom Title object
1535 * @param string $text wikitext
1536 * @param $title Title object
1537 * @param $linestart Boolean: is this the start of a line?
1538 * @param $tidy Boolean: whether to use tidy
1539 * @param $interface Boolean: whether it is an interface message
1540 * (for example disables conversion)
1542 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1545 wfProfileIn( __METHOD__
);
1547 $popts = $this->parserOptions();
1548 $oldTidy = $popts->setTidy( $tidy );
1549 $popts->setInterfaceMessage( (bool) $interface );
1551 $parserOutput = $wgParser->parse(
1552 $text, $title, $popts,
1553 $linestart, true, $this->mRevisionId
1556 $popts->setTidy( $oldTidy );
1558 $this->addParserOutput( $parserOutput );
1560 wfProfileOut( __METHOD__
);
1564 * Add a ParserOutput object, but without Html
1566 * @param $parserOutput ParserOutput object
1568 public function addParserOutputNoText( &$parserOutput ) {
1569 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1570 $this->addCategoryLinks( $parserOutput->getCategories() );
1571 $this->mNewSectionLink
= $parserOutput->getNewSection();
1572 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1574 $this->mParseWarnings
= $parserOutput->getWarnings();
1575 if ( !$parserOutput->isCacheable() ) {
1576 $this->enableClientCache( false );
1578 $this->mNoGallery
= $parserOutput->getNoGallery();
1579 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1580 $this->addModules( $parserOutput->getModules() );
1581 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1582 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1583 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1585 // Template versioning...
1586 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1587 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1588 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1590 $this->mTemplateIds
[$ns] = $dbks;
1593 // File versioning...
1594 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1595 $this->mImageTimeKeys
[$dbk] = $data;
1598 // Hooks registered in the object
1599 global $wgParserOutputHooks;
1600 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1601 list( $hookName, $data ) = $hookInfo;
1602 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1603 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1607 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1611 * Add a ParserOutput object
1613 * @param $parserOutput ParserOutput
1615 function addParserOutput( &$parserOutput ) {
1616 $this->addParserOutputNoText( $parserOutput );
1617 $text = $parserOutput->getText();
1618 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1619 $this->addHTML( $text );
1623 * Add the output of a QuickTemplate to the output buffer
1625 * @param $template QuickTemplate
1627 public function addTemplate( &$template ) {
1629 $template->execute();
1630 $this->addHTML( ob_get_contents() );
1635 * Parse wikitext and return the HTML.
1637 * @param $text String
1638 * @param $linestart Boolean: is this the start of a line?
1639 * @param $interface Boolean: use interface language ($wgLang instead of
1640 * $wgContLang) while parsing language sensitive magic
1641 * words like GRAMMAR and PLURAL. This also disables
1642 * LanguageConverter.
1643 * @param $language Language object: target language object, will override
1645 * @throws MWException
1646 * @return String: HTML
1648 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1651 if( is_null( $this->getTitle() ) ) {
1652 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1655 $popts = $this->parserOptions();
1657 $popts->setInterfaceMessage( true );
1659 if ( $language !== null ) {
1660 $oldLang = $popts->setTargetLanguage( $language );
1663 $parserOutput = $wgParser->parse(
1664 $text, $this->getTitle(), $popts,
1665 $linestart, true, $this->mRevisionId
1669 $popts->setInterfaceMessage( false );
1671 if ( $language !== null ) {
1672 $popts->setTargetLanguage( $oldLang );
1675 return $parserOutput->getText();
1679 * Parse wikitext, strip paragraphs, and return the HTML.
1681 * @param $text String
1682 * @param $linestart Boolean: is this the start of a line?
1683 * @param $interface Boolean: use interface language ($wgLang instead of
1684 * $wgContLang) while parsing language sensitive magic
1685 * words like GRAMMAR and PLURAL
1686 * @return String: HTML
1688 public function parseInline( $text, $linestart = true, $interface = false ) {
1689 $parsed = $this->parse( $text, $linestart, $interface );
1692 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1700 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1702 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1704 public function setSquidMaxage( $maxage ) {
1705 $this->mSquidMaxage
= $maxage;
1709 * Use enableClientCache(false) to force it to send nocache headers
1711 * @param $state bool
1715 public function enableClientCache( $state ) {
1716 return wfSetVar( $this->mEnableClientCache
, $state );
1720 * Get the list of cookies that will influence on the cache
1724 function getCacheVaryCookies() {
1725 global $wgCookiePrefix, $wgCacheVaryCookies;
1727 if ( $cookies === null ) {
1728 $cookies = array_merge(
1730 "{$wgCookiePrefix}Token",
1731 "{$wgCookiePrefix}LoggedOut",
1736 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1742 * Check if the request has a cache-varying cookie header
1743 * If it does, it's very important that we don't allow public caching
1747 function haveCacheVaryCookies() {
1748 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1749 if ( $cookieHeader === false ) {
1752 $cvCookies = $this->getCacheVaryCookies();
1753 foreach ( $cvCookies as $cookieName ) {
1754 # Check for a simple string match, like the way squid does it
1755 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1756 wfDebug( __METHOD__
. ": found $cookieName\n" );
1760 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1765 * Add an HTTP header that will influence on the cache
1767 * @param string $header header name
1768 * @param $option Array|null
1769 * @todo FIXME: Document the $option parameter; it appears to be for
1770 * X-Vary-Options but what format is acceptable?
1772 public function addVaryHeader( $header, $option = null ) {
1773 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1774 $this->mVaryHeader
[$header] = (array)$option;
1775 } elseif( is_array( $option ) ) {
1776 if( is_array( $this->mVaryHeader
[$header] ) ) {
1777 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1779 $this->mVaryHeader
[$header] = $option;
1782 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1786 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1787 * such as Accept-Encoding or Cookie
1791 public function getVaryHeader() {
1792 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1796 * Get a complete X-Vary-Options header
1800 public function getXVO() {
1801 $cvCookies = $this->getCacheVaryCookies();
1803 $cookiesOption = array();
1804 foreach ( $cvCookies as $cookieName ) {
1805 $cookiesOption[] = 'string-contains=' . $cookieName;
1807 $this->addVaryHeader( 'Cookie', $cookiesOption );
1810 foreach( $this->mVaryHeader
as $header => $option ) {
1811 $newheader = $header;
1812 if ( is_array( $option ) && count( $option ) > 0 ) {
1813 $newheader .= ';' . implode( ';', $option );
1815 $headers[] = $newheader;
1817 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1823 * bug 21672: Add Accept-Language to Vary and XVO headers
1824 * if there's no 'variant' parameter existed in GET.
1827 * /w/index.php?title=Main_page should always be served; but
1828 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1830 function addAcceptLanguage() {
1831 $lang = $this->getTitle()->getPageLanguage();
1832 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1833 $variants = $lang->getVariants();
1834 $aloption = array();
1835 foreach ( $variants as $variant ) {
1836 if( $variant === $lang->getCode() ) {
1839 $aloption[] = 'string-contains=' . $variant;
1841 // IE and some other browsers use BCP 47 standards in
1842 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1843 // We should handle these too.
1844 $variantBCP47 = wfBCP47( $variant );
1845 if ( $variantBCP47 !== $variant ) {
1846 $aloption[] = 'string-contains=' . $variantBCP47;
1850 $this->addVaryHeader( 'Accept-Language', $aloption );
1855 * Set a flag which will cause an X-Frame-Options header appropriate for
1856 * edit pages to be sent. The header value is controlled by
1857 * $wgEditPageFrameOptions.
1859 * This is the default for special pages. If you display a CSRF-protected
1860 * form on an ordinary view page, then you need to call this function.
1862 * @param $enable bool
1864 public function preventClickjacking( $enable = true ) {
1865 $this->mPreventClickjacking
= $enable;
1869 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1870 * This can be called from pages which do not contain any CSRF-protected
1873 public function allowClickjacking() {
1874 $this->mPreventClickjacking
= false;
1878 * Get the X-Frame-Options header value (without the name part), or false
1879 * if there isn't one. This is used by Skin to determine whether to enable
1880 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1884 public function getFrameOptions() {
1885 global $wgBreakFrames, $wgEditPageFrameOptions;
1886 if ( $wgBreakFrames ) {
1888 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1889 return $wgEditPageFrameOptions;
1895 * Send cache control HTTP headers
1897 public function sendCacheControl() {
1898 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1900 $response = $this->getRequest()->response();
1901 if ( $wgUseETag && $this->mETag
) {
1902 $response->header( "ETag: $this->mETag" );
1905 $this->addVaryHeader( 'Cookie' );
1906 $this->addAcceptLanguage();
1908 # don't serve compressed data to clients who can't handle it
1909 # maintain different caches for logged-in users and non-logged in ones
1910 $response->header( $this->getVaryHeader() );
1913 # Add an X-Vary-Options header for Squid with Wikimedia patches
1914 $response->header( $this->getXVO() );
1917 if( $this->mEnableClientCache
) {
1919 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1920 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1924 # We'll purge the proxy cache explicitly, but require end user agents
1925 # to revalidate against the proxy on each visit.
1926 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1927 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1928 # start with a shorter timeout for initial testing
1929 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1930 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
1931 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1933 # We'll purge the proxy cache for anons explicitly, but require end user agents
1934 # to revalidate against the proxy on each visit.
1935 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1936 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1937 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1938 # start with a shorter timeout for initial testing
1939 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1940 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0' );
1943 # We do want clients to cache if they can, but they *must* check for updates
1944 # on revisiting the page.
1945 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1946 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1947 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1949 if( $this->mLastModified
) {
1950 $response->header( "Last-Modified: {$this->mLastModified}" );
1953 wfDebug( __METHOD__
. ": no caching **\n", false );
1955 # In general, the absence of a last modified header should be enough to prevent
1956 # the client from using its cache. We send a few other things just to make sure.
1957 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1958 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1959 $response->header( 'Pragma: no-cache' );
1964 * Get the message associated with the HTTP response code $code
1966 * @param $code Integer: status code
1967 * @return String or null: message or null if $code is not in the list of
1970 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1972 public static function getStatusMessage( $code ) {
1973 wfDeprecated( __METHOD__
, '1.18' );
1974 return HttpStatus
::getMessage( $code );
1978 * Finally, all the text has been munged and accumulated into
1979 * the object, let's actually output it:
1981 public function output() {
1982 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1984 if( $this->mDoNothing
) {
1988 wfProfileIn( __METHOD__
);
1990 $response = $this->getRequest()->response();
1992 if ( $this->mRedirect
!= '' ) {
1993 # Standards require redirect URLs to be absolute
1994 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
1996 $redirect = $this->mRedirect
;
1997 $code = $this->mRedirectCode
;
1999 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2000 if( $code == '301' ||
$code == '303' ) {
2001 if( !$wgDebugRedirects ) {
2002 $message = HttpStatus
::getMessage( $code );
2003 $response->header( "HTTP/1.1 $code $message" );
2005 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2007 if ( $wgVaryOnXFP ) {
2008 $this->addVaryHeader( 'X-Forwarded-Proto' );
2010 $this->sendCacheControl();
2012 $response->header( "Content-Type: text/html; charset=utf-8" );
2013 if( $wgDebugRedirects ) {
2014 $url = htmlspecialchars( $redirect );
2015 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2016 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2017 print "</body>\n</html>\n";
2019 $response->header( 'Location: ' . $redirect );
2023 wfProfileOut( __METHOD__
);
2025 } elseif ( $this->mStatusCode
) {
2026 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2028 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2032 # Buffer output; final headers may depend on later processing
2035 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2036 $response->header( 'Content-language: ' . $wgLanguageCode );
2038 // Prevent framing, if requested
2039 $frameOptions = $this->getFrameOptions();
2040 if ( $frameOptions ) {
2041 $response->header( "X-Frame-Options: $frameOptions" );
2044 if ( $this->mArticleBodyOnly
) {
2045 $this->out( $this->mBodytext
);
2047 $this->addDefaultModules();
2049 $sk = $this->getSkin();
2051 // Hook that allows last minute changes to the output page, e.g.
2052 // adding of CSS or Javascript by extensions.
2053 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2055 wfProfileIn( 'Output-skin' );
2057 wfProfileOut( 'Output-skin' );
2060 // This hook allows last minute changes to final overall output by modifying output buffer
2061 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2063 $this->sendCacheControl();
2067 wfProfileOut( __METHOD__
);
2071 * Actually output something with print().
2073 * @param string $ins the string to output
2075 public function out( $ins ) {
2080 * Produce a "user is blocked" page.
2081 * @deprecated since 1.18
2083 function blockedPage() {
2084 throw new UserBlockedError( $this->getUser()->mBlock
);
2088 * Prepare this object to display an error page; disable caching and
2089 * indexing, clear the current text and redirect, set the page's title
2090 * and optionally an custom HTML title (content of the "<title>" tag).
2092 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2093 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2094 * optional, if not passed the "<title>" attribute will be
2095 * based on $pageTitle
2097 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2098 $this->setPageTitle( $pageTitle );
2099 if ( $htmlTitle !== false ) {
2100 $this->setHTMLTitle( $htmlTitle );
2102 $this->setRobotPolicy( 'noindex,nofollow' );
2103 $this->setArticleRelated( false );
2104 $this->enableClientCache( false );
2105 $this->mRedirect
= '';
2106 $this->clearSubtitle();
2111 * Output a standard error page
2113 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2114 * showErrorPage( 'titlemsg', $messageObject );
2115 * showErrorPage( $titleMessageObj, $messageObject );
2117 * @param $title Mixed: message key (string) for page title, or a Message object
2118 * @param $msg Mixed: message key (string) for page text, or a Message object
2119 * @param array $params message parameters; ignored if $msg is a Message object
2121 public function showErrorPage( $title, $msg, $params = array() ) {
2122 if( !$title instanceof Message
) {
2123 $title = $this->msg( $title );
2126 $this->prepareErrorPage( $title );
2128 if ( $msg instanceof Message
) {
2129 $this->addHTML( $msg->parseAsBlock() );
2131 $this->addWikiMsgArray( $msg, $params );
2134 $this->returnToMain();
2138 * Output a standard permission error page
2140 * @param array $errors error message keys
2141 * @param string $action action that was denied or null if unknown
2143 public function showPermissionsErrorPage( $errors, $action = null ) {
2144 // For some action (read, edit, create and upload), display a "login to do this action"
2145 // error if all of the following conditions are met:
2146 // 1. the user is not logged in
2147 // 2. the only error is insufficient permissions (i.e. no block or something else)
2148 // 3. the error can be avoided simply by logging in
2149 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2150 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2151 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2152 && ( User
::groupHasPermission( 'user', $action )
2153 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2155 $displayReturnto = null;
2157 # Due to bug 32276, if a user does not have read permissions,
2158 # $this->getTitle() will just give Special:Badtitle, which is
2159 # not especially useful as a returnto parameter. Use the title
2160 # from the request instead, if there was one.
2161 $request = $this->getRequest();
2162 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2163 if ( $action == 'edit' ) {
2164 $msg = 'whitelistedittext';
2165 $displayReturnto = $returnto;
2166 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2167 $msg = 'nocreatetext';
2168 } elseif ( $action == 'upload' ) {
2169 $msg = 'uploadnologintext';
2171 $msg = 'loginreqpagetext';
2172 $displayReturnto = Title
::newMainPage();
2178 $query['returnto'] = $returnto->getPrefixedText();
2180 if ( !$request->wasPosted() ) {
2181 $returntoquery = $request->getValues();
2182 unset( $returntoquery['title'] );
2183 unset( $returntoquery['returnto'] );
2184 unset( $returntoquery['returntoquery'] );
2185 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2188 $loginLink = Linker
::linkKnown(
2189 SpecialPage
::getTitleFor( 'Userlogin' ),
2190 $this->msg( 'loginreqlink' )->escaped(),
2195 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2196 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2198 # Don't return to a page the user can't read otherwise
2199 # we'll end up in a pointless loop
2200 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2201 $this->returnToMain( null, $displayReturnto );
2204 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2205 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2210 * Display an error page indicating that a given version of MediaWiki is
2211 * required to use it
2213 * @param $version Mixed: the version of MediaWiki needed to use the page
2215 public function versionRequired( $version ) {
2216 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2218 $this->addWikiMsg( 'versionrequiredtext', $version );
2219 $this->returnToMain();
2223 * Display an error page noting that a given permission bit is required.
2224 * @deprecated since 1.18, just throw the exception directly
2225 * @param string $permission key required
2226 * @throws PermissionsError
2228 public function permissionRequired( $permission ) {
2229 throw new PermissionsError( $permission );
2233 * Produce the stock "please login to use the wiki" page
2235 * @deprecated in 1.19; throw the exception directly
2237 public function loginToUse() {
2238 throw new PermissionsError( 'read' );
2242 * Format a list of error messages
2244 * @param array $errors of arrays returned by Title::getUserPermissionsErrors
2245 * @param string $action action that was denied or null if unknown
2246 * @return String: the wikitext error-messages, formatted into a list.
2248 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2249 if ( $action == null ) {
2250 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2252 $action_desc = $this->msg( "action-$action" )->plain();
2254 'permissionserrorstext-withaction',
2257 )->plain() . "\n\n";
2260 if ( count( $errors ) > 1 ) {
2261 $text .= '<ul class="permissions-errors">' . "\n";
2263 foreach( $errors as $error ) {
2265 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2270 $text .= "<div class=\"permissions-errors\">\n" .
2271 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2279 * Display a page stating that the Wiki is in read-only mode,
2280 * and optionally show the source of the page that the user
2281 * was trying to edit. Should only be called (for this
2282 * purpose) after wfReadOnly() has returned true.
2284 * For historical reasons, this function is _also_ used to
2285 * show the error message when a user tries to edit a page
2286 * they are not allowed to edit. (Unless it's because they're
2287 * blocked, then we show blockedPage() instead.) In this
2288 * case, the second parameter should be set to true and a list
2289 * of reasons supplied as the third parameter.
2291 * @todo Needs to be split into multiple functions.
2293 * @param $source String: source code to show (or null).
2294 * @param $protected Boolean: is this a permissions error?
2295 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2296 * @param $action String: action that was denied or null if unknown
2297 * @throws ReadOnlyError
2299 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2300 $this->setRobotPolicy( 'noindex,nofollow' );
2301 $this->setArticleRelated( false );
2303 // If no reason is given, just supply a default "I can't let you do
2304 // that, Dave" message. Should only occur if called by legacy code.
2305 if ( $protected && empty( $reasons ) ) {
2306 $reasons[] = array( 'badaccess-group0' );
2309 if ( !empty( $reasons ) ) {
2310 // Permissions error
2312 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2313 $this->addBacklinkSubtitle( $this->getTitle() );
2315 $this->setPageTitle( $this->msg( 'badaccess' ) );
2317 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2319 // Wiki is read only
2320 throw new ReadOnlyError
;
2323 // Show source, if supplied
2324 if( is_string( $source ) ) {
2325 $this->addWikiMsg( 'viewsourcetext' );
2327 $pageLang = $this->getTitle()->getPageLanguage();
2329 'id' => 'wpTextbox1',
2330 'name' => 'wpTextbox1',
2331 'cols' => $this->getUser()->getOption( 'cols' ),
2332 'rows' => $this->getUser()->getOption( 'rows' ),
2333 'readonly' => 'readonly',
2334 'lang' => $pageLang->getHtmlCode(),
2335 'dir' => $pageLang->getDir(),
2337 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2339 // Show templates used by this article
2340 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2341 $this->addHTML( "<div class='templatesUsed'>
2347 # If the title doesn't exist, it's fairly pointless to print a return
2348 # link to it. After all, you just tried editing it and couldn't, so
2349 # what's there to do there?
2350 if( $this->getTitle()->exists() ) {
2351 $this->returnToMain( null, $this->getTitle() );
2356 * Turn off regular page output and return an error response
2357 * for when rate limiting has triggered.
2359 public function rateLimited() {
2360 throw new ThrottledError
;
2364 * Show a warning about slave lag
2366 * If the lag is higher than $wgSlaveLagCritical seconds,
2367 * then the warning is a bit more obvious. If the lag is
2368 * lower than $wgSlaveLagWarning, then no warning is shown.
2370 * @param $lag Integer: slave lag
2372 public function showLagWarning( $lag ) {
2373 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2374 if( $lag >= $wgSlaveLagWarning ) {
2375 $message = $lag < $wgSlaveLagCritical
2378 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2379 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2383 public function showFatalError( $message ) {
2384 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2386 $this->addHTML( $message );
2389 public function showUnexpectedValueError( $name, $val ) {
2390 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2393 public function showFileCopyError( $old, $new ) {
2394 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2397 public function showFileRenameError( $old, $new ) {
2398 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2401 public function showFileDeleteError( $name ) {
2402 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2405 public function showFileNotFoundError( $name ) {
2406 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2410 * Add a "return to" link pointing to a specified title
2412 * @param $title Title to link
2413 * @param array $query query string parameters
2414 * @param string $text text of the link (input is not escaped)
2415 * @param $options Options array to pass to Linker
2417 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2418 if( in_array( 'http', $options ) ) {
2419 $proto = PROTO_HTTP
;
2420 } elseif( in_array( 'https', $options ) ) {
2421 $proto = PROTO_HTTPS
;
2423 $proto = PROTO_RELATIVE
;
2426 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL( '', false, $proto ) ) );
2427 $link = $this->msg( 'returnto' )->rawParams(
2428 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2429 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2433 * Add a "return to" link pointing to a specified title,
2434 * or the title indicated in the request, or else the main page
2437 * @param $returnto Title or String to return to
2438 * @param string $returntoquery query string for the return to link
2440 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2441 if ( $returnto == null ) {
2442 $returnto = $this->getRequest()->getText( 'returnto' );
2445 if ( $returntoquery == null ) {
2446 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2449 if ( $returnto === '' ) {
2450 $returnto = Title
::newMainPage();
2453 if ( is_object( $returnto ) ) {
2454 $titleObj = $returnto;
2456 $titleObj = Title
::newFromText( $returnto );
2458 if ( !is_object( $titleObj ) ) {
2459 $titleObj = Title
::newMainPage();
2462 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2466 * @param $sk Skin The given Skin
2467 * @param $includeStyle Boolean: unused
2468 * @return String: The doctype, opening "<html>", and head element.
2470 public function headElement( Skin
$sk, $includeStyle = true ) {
2473 $userdir = $this->getLanguage()->getDir();
2474 $sitedir = $wgContLang->getDir();
2476 if ( $sk->commonPrintStylesheet() ) {
2477 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2480 $ret = Html
::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2482 if ( $this->getHTMLTitle() == '' ) {
2483 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2486 $openHead = Html
::openElement( 'head' );
2488 # Don't bother with the newline if $head == ''
2489 $ret .= "$openHead\n";
2492 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2494 $ret .= implode( "\n", array(
2495 $this->getHeadLinks( null, true ),
2496 $this->buildCssLinks(),
2497 $this->getHeadScripts(),
2498 $this->getHeadItems()
2501 $closeHead = Html
::closeElement( 'head' );
2503 $ret .= "$closeHead\n";
2506 $bodyAttrs = array();
2508 # Classes for LTR/RTL directionality support
2509 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2511 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2512 # A <body> class is probably not the best way to do this . . .
2513 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2515 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2516 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2517 $bodyAttrs['class'] .= ' action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2519 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2520 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2522 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2528 * Add the default ResourceLoader modules to this object
2530 private function addDefaultModules() {
2531 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2532 $wgAjaxWatch, $wgResponsiveImages;
2534 // Add base resources
2535 $this->addModules( array(
2537 'mediawiki.page.startup',
2538 'mediawiki.page.ready',
2540 if ( $wgIncludeLegacyJavaScript ) {
2541 $this->addModules( 'mediawiki.legacy.wikibits' );
2544 if ( $wgPreloadJavaScriptMwUtil ) {
2545 $this->addModules( 'mediawiki.util' );
2548 MWDebug
::addModules( $this );
2550 // Add various resources if required
2552 $this->addModules( 'mediawiki.legacy.ajax' );
2554 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2556 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2557 $this->addModules( 'mediawiki.page.watch.ajax' );
2560 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2561 $this->addModules( 'mediawiki.searchSuggest' );
2565 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2566 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2569 # Crazy edit-on-double-click stuff
2570 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2571 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2574 // Support for high-density display images
2575 if ( $wgResponsiveImages ) {
2576 $this->addModules( 'mediawiki.hidpi' );
2581 * Get a ResourceLoader object associated with this OutputPage
2583 * @return ResourceLoader
2585 public function getResourceLoader() {
2586 if ( is_null( $this->mResourceLoader
) ) {
2587 $this->mResourceLoader
= new ResourceLoader();
2589 return $this->mResourceLoader
;
2594 * @param $modules Array/string with the module name(s)
2595 * @param string $only ResourceLoaderModule TYPE_ class constant
2596 * @param $useESI boolean
2597 * @param array $extraQuery with extra query parameters to add to each request. array( param => value )
2598 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2599 * @return string html "<script>" and "<style>" tags
2601 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2602 global $wgResourceLoaderUseESI;
2604 $modules = (array) $modules;
2606 if ( !count( $modules ) ) {
2610 if ( count( $modules ) > 1 ) {
2611 // Remove duplicate module requests
2612 $modules = array_unique( $modules );
2613 // Sort module names so requests are more uniform
2616 if ( ResourceLoader
::inDebugMode() ) {
2617 // Recursively call us for every item
2619 foreach ( $modules as $name ) {
2620 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2625 if ( !is_null( $this->mTarget
) ) {
2626 $extraQuery['target'] = $this->mTarget
;
2629 // Create keyed-by-group list of module objects from modules list
2631 $resourceLoader = $this->getResourceLoader();
2632 foreach ( $modules as $name ) {
2633 $module = $resourceLoader->getModule( $name );
2634 # Check that we're allowed to include this module on this page
2636 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2637 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2638 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2639 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2640 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2646 $group = $module->getGroup();
2647 if ( !isset( $groups[$group] ) ) {
2648 $groups[$group] = array();
2650 $groups[$group][$name] = $module;
2654 foreach ( $groups as $group => $grpModules ) {
2655 // Special handling for user-specific groups
2657 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2658 $user = $this->getUser()->getName();
2661 // Create a fake request based on the one we are about to make so modules return
2662 // correct timestamp and emptiness data
2663 $query = ResourceLoader
::makeLoaderQuery(
2664 array(), // modules; not determined yet
2665 $this->getLanguage()->getCode(),
2666 $this->getSkin()->getSkinName(),
2668 null, // version; not determined yet
2669 ResourceLoader
::inDebugMode(),
2670 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2671 $this->isPrintable(),
2672 $this->getRequest()->getBool( 'handheld' ),
2675 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2676 // Extract modules that know they're empty
2677 $emptyModules = array ();
2678 foreach ( $grpModules as $key => $module ) {
2679 if ( $module->isKnownEmpty( $context ) ) {
2680 $emptyModules[$key] = 'ready';
2681 unset( $grpModules[$key] );
2684 // Inline empty modules: since they're empty, just mark them as 'ready'
2685 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2686 // If we're only getting the styles, we don't need to do anything for empty modules.
2687 $links .= Html
::inlineScript(
2689 ResourceLoader
::makeLoaderConditionalScript(
2691 ResourceLoader
::makeLoaderStateScript( $emptyModules )
2698 // If there are no modules left, skip this group
2699 if ( count( $grpModules ) === 0 ) {
2703 // Inline private modules. These can't be loaded through load.php for security
2704 // reasons, see bug 34907. Note that these modules should be loaded from
2705 // getHeadScripts() before the first loader call. Otherwise other modules can't
2706 // properly use them as dependencies (bug 30914)
2707 if ( $group === 'private' ) {
2708 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2709 $links .= Html
::inlineStyle(
2710 $resourceLoader->makeModuleResponse( $context, $grpModules )
2713 $links .= Html
::inlineScript(
2714 ResourceLoader
::makeLoaderConditionalScript(
2715 $resourceLoader->makeModuleResponse( $context, $grpModules )
2722 // Special handling for the user group; because users might change their stuff
2723 // on-wiki like user pages, or user preferences; we need to find the highest
2724 // timestamp of these user-changeable modules so we can ensure cache misses on change
2725 // This should NOT be done for the site group (bug 27564) because anons get that too
2726 // and we shouldn't be putting timestamps in Squid-cached HTML
2728 if ( $group === 'user' ) {
2729 // Get the maximum timestamp
2731 foreach ( $grpModules as $module ) {
2732 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2734 // Add a version parameter so cache will break when things change
2735 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2738 $url = ResourceLoader
::makeLoaderURL(
2739 array_keys( $grpModules ),
2740 $this->getLanguage()->getCode(),
2741 $this->getSkin()->getSkinName(),
2744 ResourceLoader
::inDebugMode(),
2745 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2746 $this->isPrintable(),
2747 $this->getRequest()->getBool( 'handheld' ),
2750 if ( $useESI && $wgResourceLoaderUseESI ) {
2751 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2752 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2753 $link = Html
::inlineStyle( $esi );
2755 $link = Html
::inlineScript( $esi );
2758 // Automatically select style/script elements
2759 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2760 $link = Html
::linkedStyle( $url );
2761 } else if ( $loadCall ) {
2762 $link = Html
::inlineScript(
2763 ResourceLoader
::makeLoaderConditionalScript(
2764 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2768 $link = Html
::linkedScript( $url );
2772 if( $group == 'noscript' ) {
2773 $links .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2775 $links .= $link . "\n";
2782 * JS stuff to put in the "<head>". This is the startup module, config
2783 * vars and modules marked with position 'top'
2785 * @return String: HTML fragment
2787 function getHeadScripts() {
2788 global $wgResourceLoaderExperimentalAsyncLoading;
2790 // Startup - this will immediately load jquery and mediawiki modules
2791 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2793 // Load config before anything else
2794 $scripts .= Html
::inlineScript(
2795 ResourceLoader
::makeLoaderConditionalScript(
2796 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2800 // Load embeddable private modules before any loader links
2801 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2802 // in mw.loader.implement() calls and deferred until mw.user is available
2803 $embedScripts = array( 'user.options', 'user.tokens' );
2804 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2806 // Script and Messages "only" requests marked for top inclusion
2807 // Messages should go first
2808 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2809 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2811 // Modules requests - let the client calculate dependencies and batch requests as it likes
2812 // Only load modules that have marked themselves for loading at the top
2813 $modules = $this->getModules( true, 'top' );
2815 $scripts .= Html
::inlineScript(
2816 ResourceLoader
::makeLoaderConditionalScript(
2817 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2822 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2823 $scripts .= $this->getScriptsForBottomQueue( true );
2830 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2831 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2832 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2833 * user preferences, site JS and user JS
2835 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2838 function getScriptsForBottomQueue( $inHead ) {
2839 global $wgUseSiteJs, $wgAllowUserJs;
2841 // Script and Messages "only" requests marked for bottom inclusion
2842 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2843 // Messages should go first
2844 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2845 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2846 /* $loadCall = */ $inHead
2848 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2849 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2850 /* $loadCall = */ $inHead
2853 // Modules requests - let the client calculate dependencies and batch requests as it likes
2854 // Only load modules that have marked themselves for loading at the bottom
2855 $modules = $this->getModules( true, 'bottom' );
2857 $scripts .= Html
::inlineScript(
2858 ResourceLoader
::makeLoaderConditionalScript(
2859 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2865 $scripts .= "\n" . $this->mScripts
;
2867 $defaultModules = array();
2869 // Add site JS if enabled
2870 if ( $wgUseSiteJs ) {
2871 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2872 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2874 $defaultModules['site'] = 'loading';
2876 // The wiki is configured to not allow a site module.
2877 $defaultModules['site'] = 'missing';
2880 // Add user JS if enabled
2881 if ( $wgAllowUserJs ) {
2882 if ( $this->getUser()->isLoggedIn() ) {
2883 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2884 # XXX: additional security check/prompt?
2885 // We're on a preview of a JS subpage
2886 // Exclude this page from the user module in case it's in there (bug 26283)
2887 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2888 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2890 // Load the previewed JS
2891 $scripts .= Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2892 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2893 // asynchronously and may arrive *after* the inline script here. So the previewed code
2894 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2896 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2897 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2898 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2901 $defaultModules['user'] = 'loading';
2903 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2904 // blocking default gadgets that might depend on it. Although arguably default-enabled
2905 // gadgets should not depend on the user module, it's harmless and less error-prone to
2906 // handle this case.
2907 $defaultModules['user'] = 'ready';
2911 $defaultModules['user'] = 'missing';
2914 // Group JS is only enabled if site JS is enabled.
2915 if ( $wgUseSiteJs ) {
2916 if ( $this->getUser()->isLoggedIn() ) {
2917 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2918 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2920 $defaultModules['user.groups'] = 'loading';
2922 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2923 // avoid blocking gadgets that might depend upon the module.
2924 $defaultModules['user.groups'] = 'ready';
2927 // Site (and group JS) disabled
2928 $defaultModules['user.groups'] = 'missing';
2933 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2934 foreach ( $defaultModules as $m => $state ) {
2935 if ( $state == 'loading' ) {
2936 unset( $defaultModules[$m] );
2940 if ( count( $defaultModules ) > 0 ) {
2941 $loaderInit = Html
::inlineScript(
2942 ResourceLoader
::makeLoaderConditionalScript(
2943 ResourceLoader
::makeLoaderStateScript( $defaultModules )
2947 return $loaderInit . $scripts;
2951 * JS stuff to put at the bottom of the "<body>"
2954 function getBottomScripts() {
2955 global $wgResourceLoaderExperimentalAsyncLoading;
2956 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2957 return $this->getScriptsForBottomQueue( false );
2964 * Add one or more variables to be set in mw.config in JavaScript.
2966 * @param $keys {String|Array} Key or array of key/value pairs.
2967 * @param $value {Mixed} [optional] Value of the configuration variable.
2969 public function addJsConfigVars( $keys, $value = null ) {
2970 if ( is_array( $keys ) ) {
2971 foreach ( $keys as $key => $value ) {
2972 $this->mJsConfigVars
[$key] = $value;
2977 $this->mJsConfigVars
[$keys] = $value;
2981 * Get an array containing the variables to be set in mw.config in JavaScript.
2983 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2984 * This is only public until that function is removed. You have been warned.
2986 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2987 * - in other words, page-independent/site-wide variables (without state).
2988 * You will only be adding bloat to the html page and causing page caches to
2989 * have to be purged on configuration changes.
2992 public function getJSVars() {
2997 $canonicalName = false; # bug 21115
2999 $title = $this->getTitle();
3000 $ns = $title->getNamespace();
3001 $nsname = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
3003 // Get the relevant title so that AJAX features can use the correct page name
3004 // when making API requests from certain special pages (bug 34972).
3005 $relevantTitle = $this->getSkin()->getRelevantTitle();
3007 if ( $ns == NS_SPECIAL
) {
3008 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3009 } elseif ( $this->canUseWikiPage() ) {
3010 $wikiPage = $this->getWikiPage();
3011 $latestRevID = $wikiPage->getLatest();
3012 $pageID = $wikiPage->getId();
3015 $lang = $title->getPageLanguage();
3017 // Pre-process information
3018 $separatorTransTable = $lang->separatorTransformTable();
3019 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3020 $compactSeparatorTransTable = array(
3021 implode( "\t", array_keys( $separatorTransTable ) ),
3022 implode( "\t", $separatorTransTable ),
3024 $digitTransTable = $lang->digitTransformTable();
3025 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3026 $compactDigitTransTable = array(
3027 implode( "\t", array_keys( $digitTransTable ) ),
3028 implode( "\t", $digitTransTable ),
3031 $user = $this->getUser();
3034 'wgCanonicalNamespace' => $nsname,
3035 'wgCanonicalSpecialPageName' => $canonicalName,
3036 'wgNamespaceNumber' => $title->getNamespace(),
3037 'wgPageName' => $title->getPrefixedDBkey(),
3038 'wgTitle' => $title->getText(),
3039 'wgCurRevisionId' => $latestRevID,
3040 'wgArticleId' => $pageID,
3041 'wgIsArticle' => $this->isArticle(),
3042 'wgAction' => Action
::getActionName( $this->getContext() ),
3043 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3044 'wgUserGroups' => $user->getEffectiveGroups(),
3045 'wgCategories' => $this->getCategories(),
3046 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3047 'wgPageContentLanguage' => $lang->getCode(),
3048 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3049 'wgDigitTransformTable' => $compactDigitTransTable,
3050 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3051 'wgMonthNames' => $lang->getMonthNamesArray(),
3052 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3053 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3055 if ( $user->isLoggedIn() ) {
3056 $vars['wgUserId'] = $user->getId();
3057 $vars['wgUserEditCount'] = $user->getEditCount();
3058 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3059 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3061 if ( $wgContLang->hasVariants() ) {
3062 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3064 foreach ( $title->getRestrictionTypes() as $type ) {
3065 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3067 if ( $title->isMainPage() ) {
3068 $vars['wgIsMainPage'] = true;
3070 if ( $this->mRedirectedFrom
) {
3071 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3074 // Allow extensions to add their custom variables to the mw.config map.
3075 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3076 // page-dependant but site-wide (without state).
3077 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3078 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3080 // Merge in variables from addJsConfigVars last
3081 return array_merge( $vars, $this->mJsConfigVars
);
3085 * To make it harder for someone to slip a user a fake
3086 * user-JavaScript or user-CSS preview, a random token
3087 * is associated with the login session. If it's not
3088 * passed back with the preview request, we won't render
3093 public function userCanPreview() {
3094 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3095 ||
!$this->getRequest()->wasPosted()
3096 ||
!$this->getUser()->matchEditToken(
3097 $this->getRequest()->getVal( 'wpEditToken' ) )
3101 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3105 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3109 * @param bool $addContentType Whether "<meta>" specifying content type should be returned
3111 * @return array in format "link name or number => 'link html'".
3113 public function getHeadLinksArray( $addContentType = false ) {
3114 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3115 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3116 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3117 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3118 $wgRightsPage, $wgRightsUrl;
3122 $canonicalUrl = $this->mCanonicalUrl
;
3124 if ( $addContentType ) {
3126 # More succinct than <meta http-equiv=Content-Type>, has the
3128 $tags['meta-charset'] = Html
::element( 'meta', array( 'charset' => 'UTF-8' ) );
3130 $tags['meta-content-type'] = Html
::element( 'meta', array(
3131 'http-equiv' => 'Content-Type',
3132 'content' => "$wgMimeType; charset=UTF-8"
3134 $tags['meta-content-style-type'] = Html
::element( 'meta', array( // bug 15835
3135 'http-equiv' => 'Content-Style-Type',
3136 'content' => 'text/css'
3141 $tags['meta-generator'] = Html
::element( 'meta', array(
3142 'name' => 'generator',
3143 'content' => "MediaWiki $wgVersion",
3146 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3147 if( $p !== 'index,follow' ) {
3148 // http://www.robotstxt.org/wc/meta-user.html
3149 // Only show if it's different from the default robots policy
3150 $tags['meta-robots'] = Html
::element( 'meta', array(
3156 if ( count( $this->mKeywords
) > 0 ) {
3158 "/<.*?" . ">/" => '',
3161 $tags['meta-keywords'] = Html
::element( 'meta', array(
3162 'name' => 'keywords',
3163 'content' => preg_replace(
3164 array_keys( $strip ),
3165 array_values( $strip ),
3166 implode( ',', $this->mKeywords
)
3171 foreach ( $this->mMetatags
as $tag ) {
3172 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3174 $tag[0] = substr( $tag[0], 5 );
3178 $tagName = "meta-{$tag[0]}";
3179 if ( isset( $tags[$tagName] ) ) {
3180 $tagName .= $tag[1];
3182 $tags[$tagName] = Html
::element( 'meta',
3185 'content' => $tag[1]
3190 foreach ( $this->mLinktags
as $tag ) {
3191 $tags[] = Html
::element( 'link', $tag );
3194 # Universal edit button
3195 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3196 $user = $this->getUser();
3197 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3198 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3199 // Original UniversalEditButton
3200 $msg = $this->msg( 'edit' )->text();
3201 $tags['universal-edit-button'] = Html
::element( 'link', array(
3202 'rel' => 'alternate',
3203 'type' => 'application/x-wiki',
3205 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3207 // Alternate edit link
3208 $tags['alternative-edit'] = Html
::element( 'link', array(
3211 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3216 # Generally the order of the favicon and apple-touch-icon links
3217 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3218 # uses whichever one appears later in the HTML source. Make sure
3219 # apple-touch-icon is specified first to avoid this.
3220 if ( $wgAppleTouchIcon !== false ) {
3221 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3224 if ( $wgFavicon !== false ) {
3225 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3228 # OpenSearch description link
3229 $tags['opensearch'] = Html
::element( 'link', array(
3231 'type' => 'application/opensearchdescription+xml',
3232 'href' => wfScript( 'opensearch_desc' ),
3233 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3236 if ( $wgEnableAPI ) {
3237 # Real Simple Discovery link, provides auto-discovery information
3238 # for the MediaWiki API (and potentially additional custom API
3239 # support such as WordPress or Twitter-compatible APIs for a
3240 # blogging extension, etc)
3241 $tags['rsd'] = Html
::element( 'link', array(
3243 'type' => 'application/rsd+xml',
3244 // Output a protocol-relative URL here if $wgServer is protocol-relative
3245 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3246 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3251 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3252 $lang = $this->getTitle()->getPageLanguage();
3253 if ( $lang->hasVariants() ) {
3255 $urlvar = $lang->getURLVariant();
3258 $variants = $lang->getVariants();
3259 foreach ( $variants as $_v ) {
3260 $tags["variant-$_v"] = Html
::element( 'link', array(
3261 'rel' => 'alternate',
3263 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3267 $canonicalUrl = $this->getTitle()->getLocalURL();
3274 if ( $wgRightsPage ) {
3275 $copy = Title
::newFromText( $wgRightsPage );
3278 $copyright = $copy->getLocalURL();
3282 if ( !$copyright && $wgRightsUrl ) {
3283 $copyright = $wgRightsUrl;
3287 $tags['copyright'] = Html
::element( 'link', array(
3288 'rel' => 'copyright',
3289 'href' => $copyright )
3295 foreach( $this->getSyndicationLinks() as $format => $link ) {
3296 # Use the page name for the title. In principle, this could
3297 # lead to issues with having the same name for different feeds
3298 # corresponding to the same page, but we can't avoid that at
3301 $tags[] = $this->feedLink(
3304 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3305 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3309 # Recent changes feed should appear on every page (except recentchanges,
3310 # that would be redundant). Put it after the per-page feed to avoid
3311 # changing existing behavior. It's still available, probably via a
3312 # menu in your browser. Some sites might have a different feed they'd
3313 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3314 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3315 # If so, use it instead.
3316 if ( $wgOverrideSiteFeed ) {
3317 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3318 // Note, this->feedLink escapes the url.
3319 $tags[] = $this->feedLink(
3322 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3325 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3326 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3327 foreach ( $wgAdvertisedFeedTypes as $format ) {
3328 $tags[] = $this->feedLink(
3330 $rctitle->getLocalURL( "feed={$format}" ),
3331 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3338 global $wgEnableCanonicalServerLink;
3339 if ( $wgEnableCanonicalServerLink ) {
3340 if ( $canonicalUrl !== false ) {
3341 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3343 $reqUrl = $this->getRequest()->getRequestURL();
3344 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3347 if ( $canonicalUrl !== false ) {
3348 $tags[] = Html
::element( 'link', array(
3349 'rel' => 'canonical',
3350 'href' => $canonicalUrl
3359 * @param bool $addContentType Whether "<meta>" specifying content type should be returned
3361 * @return string HTML tag links to be put in the header.
3363 public function getHeadLinks( $unused = null, $addContentType = false ) {
3364 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3368 * Generate a "<link rel/>" for a feed.
3370 * @param string $type feed type
3371 * @param string $url URL to the feed
3372 * @param string $text value of the "title" attribute
3373 * @return String: HTML fragment
3375 private function feedLink( $type, $url, $text ) {
3376 return Html
::element( 'link', array(
3377 'rel' => 'alternate',
3378 'type' => "application/$type+xml",
3385 * Add a local or specified stylesheet, with the given media options.
3386 * Meant primarily for internal use...
3388 * @param string $style URL to the file
3389 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3390 * @param string $condition for IE conditional comments, specifying an IE version
3391 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3393 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3395 // Even though we expect the media type to be lowercase, but here we
3396 // force it to lowercase to be safe.
3398 $options['media'] = $media;
3401 $options['condition'] = $condition;
3404 $options['dir'] = $dir;
3406 $this->styles
[$style] = $options;
3410 * Adds inline CSS styles
3411 * @param $style_css Mixed: inline CSS
3412 * @param string $flip Set to 'flip' to flip the CSS if needed
3414 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3415 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3416 # If wanted, and the interface is right-to-left, flip the CSS
3417 $style_css = CSSJanus
::transform( $style_css, true, false );
3419 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
3423 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3424 * These will be applied to various media & IE conditionals.
3428 public function buildCssLinks() {
3429 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3431 $this->getSkin()->setupSkinUserCss( $this );
3433 // Add ResourceLoader styles
3434 // Split the styles into four groups
3435 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3436 $otherTags = ''; // Tags to append after the normal <link> tags
3437 $resourceLoader = $this->getResourceLoader();
3439 $moduleStyles = $this->getModuleStyles();
3441 // Per-site custom styles
3442 if ( $wgUseSiteCss ) {
3443 $moduleStyles[] = 'site';
3444 $moduleStyles[] = 'noscript';
3445 if( $this->getUser()->isLoggedIn() ) {
3446 $moduleStyles[] = 'user.groups';
3450 // Per-user custom styles
3451 if ( $wgAllowUserCss ) {
3452 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3453 // We're on a preview of a CSS subpage
3454 // Exclude this page from the user module in case it's in there (bug 26283)
3455 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3456 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3459 // Load the previewed CSS
3460 // If needed, Janus it first. This is user-supplied CSS, so it's
3461 // assumed to be right for the content language directionality.
3462 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3463 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3464 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3466 $otherTags .= Html
::inlineStyle( $previewedCSS );
3468 // Load the user styles normally
3469 $moduleStyles[] = 'user';
3473 // Per-user preference styles
3474 if ( $wgAllowUserCssPrefs ) {
3475 $moduleStyles[] = 'user.cssprefs';
3478 foreach ( $moduleStyles as $name ) {
3479 $module = $resourceLoader->getModule( $name );
3483 $group = $module->getGroup();
3484 // Modules in groups named "other" or anything different than "user", "site" or "private"
3485 // will be placed in the "other" group
3486 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3489 // We want site, private and user styles to override dynamically added styles from modules, but we want
3490 // dynamically added styles to override statically added styles from other modules. So the order
3491 // has to be other, dynamic, site, private, user
3492 // Add statically added styles for other modules
3493 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3494 // Add normal styles added through addStyle()/addInlineStyle() here
3495 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3496 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3497 // We use a <meta> tag with a made-up name for this because that's valid HTML
3498 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3500 // Add site, private and user styles
3501 // 'private' at present only contains user.options, so put that before 'user'
3502 // Any future private modules will likely have a similar user-specific character
3503 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3504 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3505 ResourceLoaderModule
::TYPE_STYLES
3509 // Add stuff in $otherTags (previewed user CSS if applicable)
3517 public function buildCssLinksArray() {
3520 // Add any extension CSS
3521 foreach ( $this->mExtStyles
as $url ) {
3522 $this->addStyle( $url );
3524 $this->mExtStyles
= array();
3526 foreach( $this->styles
as $file => $options ) {
3527 $link = $this->styleLink( $file, $options );
3529 $links[$file] = $link;
3536 * Generate \<link\> tags for stylesheets
3538 * @param string $style URL to the file
3539 * @param array $options option, can contain 'condition', 'dir', 'media'
3541 * @return String: HTML fragment
3543 protected function styleLink( $style, $options ) {
3544 if( isset( $options['dir'] ) ) {
3545 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3550 if( isset( $options['media'] ) ) {
3551 $media = self
::transformCssMedia( $options['media'] );
3552 if( is_null( $media ) ) {
3559 if( substr( $style, 0, 1 ) == '/' ||
3560 substr( $style, 0, 5 ) == 'http:' ||
3561 substr( $style, 0, 6 ) == 'https:' ) {
3564 global $wgStylePath, $wgStyleVersion;
3565 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3568 $link = Html
::linkedStyle( $url, $media );
3570 if( isset( $options['condition'] ) ) {
3571 $condition = htmlspecialchars( $options['condition'] );
3572 $link = "<!--[if $condition]>$link<![endif]-->";
3578 * Transform "media" attribute based on request parameters
3580 * @param string $media current value of the "media" attribute
3581 * @return String: modified value of the "media" attribute, or null to skip
3584 public static function transformCssMedia( $media ) {
3585 global $wgRequest, $wgHandheldForIPhone;
3587 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3588 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3590 // Switch in on-screen display for media testing
3592 'printable' => 'print',
3593 'handheld' => 'handheld',
3595 foreach( $switches as $switch => $targetMedia ) {
3596 if( $wgRequest->getBool( $switch ) ) {
3597 if( $media == $targetMedia ) {
3599 } elseif( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3600 // This regex will not attempt to understand a comma-separated media_query_list
3602 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3603 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3605 // If it's a print request, we never want any kind of screen stylesheets
3606 // If it's a handheld request (currently the only other choice with a switch),
3607 // we don't want simple 'screen' but we might want screen queries that
3608 // have a max-width or something, so we'll pass all others on and let the
3609 // client do the query.
3610 if( $targetMedia == 'print' ||
$media == 'screen' ) {
3617 // Expand longer media queries as iPhone doesn't grok 'handheld'
3618 if( $wgHandheldForIPhone ) {
3619 $mediaAliases = array(
3620 'screen' => 'screen and (min-device-width: 481px)',
3621 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3624 if( isset( $mediaAliases[$media] ) ) {
3625 $media = $mediaAliases[$media];
3633 * Add a wikitext-formatted message to the output.
3634 * This is equivalent to:
3636 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3638 public function addWikiMsg( /*...*/ ) {
3639 $args = func_get_args();
3640 $name = array_shift( $args );
3641 $this->addWikiMsgArray( $name, $args );
3645 * Add a wikitext-formatted message to the output.
3646 * Like addWikiMsg() except the parameters are taken as an array
3647 * instead of a variable argument list.
3649 * @param $name string
3650 * @param $args array
3652 public function addWikiMsgArray( $name, $args ) {
3653 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3657 * This function takes a number of message/argument specifications, wraps them in
3658 * some overall structure, and then parses the result and adds it to the output.
3660 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3661 * on. The subsequent arguments may either be strings, in which case they are the
3662 * message names, or arrays, in which case the first element is the message name,
3663 * and subsequent elements are the parameters to that message.
3665 * Don't use this for messages that are not in users interface language.
3669 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3673 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3675 * The newline after opening div is needed in some wikitext. See bug 19226.
3677 * @param $wrap string
3679 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3680 $msgSpecs = func_get_args();
3681 array_shift( $msgSpecs );
3682 $msgSpecs = array_values( $msgSpecs );
3684 foreach ( $msgSpecs as $n => $spec ) {
3685 if ( is_array( $spec ) ) {
3687 $name = array_shift( $args );
3688 if ( isset( $args['options'] ) ) {
3689 unset( $args['options'] );
3691 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3699 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3701 $this->addWikiText( $s );
3705 * Include jQuery core. Use this to avoid loading it multiple times
3706 * before we get a usable script loader.
3708 * @param array $modules list of jQuery modules which should be loaded
3709 * @return Array: the list of modules which were not loaded.
3711 * @deprecated since 1.17
3713 public function includeJQuery( $modules = array() ) {