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 var $mLinktags = array();
43 var $mCanonicalUrl = false;
45 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
46 var $mExtStyles = array();
48 /// Should be private - has getter and setter. Contains the HTML title
51 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
55 * Holds the debug lines that will be output as comments in page source if
56 * $wgDebugComments is enabled. See also $wgShowDebug.
57 * @deprecated since 1.20; use MWDebug class instead.
59 public $mDebugtext = '';
61 /// Should be private. Stores contents of "<title>" tag
64 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
65 var $mIsarticle = false;
68 * Should be private. Has get/set methods properly documented.
69 * Stores "article flag" toggle.
71 var $mIsArticleRelated = true;
74 * Should be private. We have to set isPrintable(). Some pages should
75 * never be printed (ex: redirections).
77 var $mPrintable = false;
80 * Should be private. We have set/get/append methods.
82 * Contains the page subtitle. Special pages usually have some links here.
83 * Don't confuse with site subtitle added by skins.
85 private $mSubtitle = array();
91 * mLastModified and mEtag are used for sending cache control.
92 * The whole caching system should probably be moved into its own class.
94 var $mLastModified = '';
97 * Should be private. No getter but used in sendCacheControl();
98 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
99 * as a unique identifier for the content. It is later used by the client
100 * to compare its cached version with the server version. Client sends
101 * headers If-Match and If-None-Match containing its locally cached ETAG value.
103 * To get more information, you will have to look at HTTP/1.1 protocol which
104 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
108 var $mCategoryLinks = array();
109 var $mCategories = array();
111 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
112 var $mLanguageLinks = array();
115 * Should be private. Used for JavaScript (pre resource loader)
116 * We should split js / css.
117 * mScripts content is inserted as is in "<head>" by Skin. This might
118 * contains either a link to a stylesheet or inline css.
123 * Inline CSS styles. Use addInlineStyle() sparingly
125 var $mInlineStyles = '';
131 * Used by skin template.
132 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
134 var $mPageLinkTitle = '';
136 /// Array of elements in "<head>". Parser might add its own headers!
137 var $mHeadItems = array();
139 // @todo FIXME: Next variables probably comes from the resource loader
140 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
141 var $mResourceLoader;
142 var $mJsConfigVars = array();
144 /** @todo FIXME: Is this still used ?*/
145 var $mInlineMsg = array();
147 var $mTemplateIds = array();
148 var $mImageTimeKeys = array();
150 var $mRedirectCode = '';
152 var $mFeedLinksAppendQuery = null;
154 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
155 # @see ResourceLoaderModule::$origin
156 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
157 protected $mAllowedModules = array(
158 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
162 * Whether output is disabled. If this is true, the 'output' method will do nothing.
164 * @var bool $mDoNothing
166 var $mDoNothing = false;
169 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
172 * lazy initialised, use parserOptions()
175 protected $mParserOptions = null;
178 * Handles the atom / rss links.
179 * We probably only support atom in 2011.
180 * Looks like a private variable.
181 * @see $wgAdvertisedFeedTypes
183 var $mFeedLinks = array();
185 // Gwicke work on squid caching? Roughly from 2003.
186 var $mEnableClientCache = true;
189 * Flag if output should only contain the body of the article.
192 var $mArticleBodyOnly = false;
194 var $mNewSectionLink = false;
195 var $mHideNewSectionLink = false;
198 * Comes from the parser. This was probably made to load CSS/JS only
199 * if we had "<gallery>". Used directly in CategoryPage.php
200 * Looks like resource loader can replace this.
202 var $mNoGallery = false;
204 // should be private.
205 var $mPageTitleActionText = '';
206 var $mParseWarnings = array();
208 // Cache stuff. Looks like mEnableClientCache
209 var $mSquidMaxage = 0;
212 var $mPreventClickjacking = true;
214 /// should be private. To include the variable {{REVISIONID}}
215 var $mRevisionId = null;
216 private $mRevisionTimestamp = null;
218 var $mFileVersion = null;
221 * An array of stylesheet filenames (relative from skins path), with options
222 * for CSS media, IE conditions, and RTL/LTR direction.
223 * For internal use; add settings in the skin via $this->addStyle()
225 * Style again! This seems like a code duplication since we already have
226 * mStyles. This is what makes OpenSource amazing.
228 var $styles = array();
231 * Whether jQuery is already handled.
233 protected $mJQueryDone = false;
235 private $mIndexPolicy = 'index';
236 private $mFollowPolicy = 'follow';
237 private $mVaryHeader = array(
238 'Accept-Encoding' => array( 'list-contains=gzip' ),
242 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
247 private $mRedirectedFrom = null;
250 * Additional key => value data
252 private $mProperties = array();
255 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
257 private $mTarget = null;
260 * @var bool Whether parser output should contain table of contents
262 private $mEnableTOC = true;
265 * @var bool Whether parser output should contain section edit links
267 private $mEnableSectionEditLinks = true;
270 * Constructor for OutputPage. This should not be called directly.
271 * Instead a new RequestContext should be created and it will implicitly create
272 * a OutputPage tied to that context.
274 function __construct( IContextSource
$context = null ) {
275 if ( $context === null ) {
276 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
277 wfDeprecated( __METHOD__
, '1.18' );
279 $this->setContext( $context );
284 * Redirect to $url rather than displaying the normal page
286 * @param string $url URL
287 * @param string $responsecode HTTP status code
289 public function redirect( $url, $responsecode = '302' ) {
290 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
291 $this->mRedirect
= str_replace( "\n", '', $url );
292 $this->mRedirectCode
= $responsecode;
296 * Get the URL to redirect to, or an empty string if not redirect URL set
300 public function getRedirect() {
301 return $this->mRedirect
;
305 * Set the HTTP status code to send with the output.
307 * @param int $statusCode
309 public function setStatusCode( $statusCode ) {
310 $this->mStatusCode
= $statusCode;
314 * Add a new "<meta>" tag
315 * To add an http-equiv meta tag, precede the name with "http:"
317 * @param string $name tag name
318 * @param string $val tag value
320 function addMeta( $name, $val ) {
321 array_push( $this->mMetatags
, array( $name, $val ) );
325 * Add a new \<link\> tag to the page header.
327 * Note: use setCanonicalUrl() for rel=canonical.
329 * @param array $linkarr associative array of attributes.
331 function addLink( $linkarr ) {
332 array_push( $this->mLinktags
, $linkarr );
336 * Add a new \<link\> with "rel" attribute set to "meta"
338 * @param array $linkarr associative array mapping attribute names to their
339 * values, both keys and values will be escaped, and the
340 * "rel" attribute will be automatically added
342 function addMetadataLink( $linkarr ) {
343 $linkarr['rel'] = $this->getMetadataAttribute();
344 $this->addLink( $linkarr );
348 * Set the URL to be used for the <link rel=canonical>. This should be used
349 * in preference to addLink(), to avoid duplicate link tags.
351 function setCanonicalUrl( $url ) {
352 $this->mCanonicalUrl
= $url;
356 * Get the value of the "rel" attribute for metadata links
360 public function getMetadataAttribute() {
361 # note: buggy CC software only reads first "meta" link
362 static $haveMeta = false;
364 return 'alternate meta';
372 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
374 * @param string $script raw HTML
376 function addScript( $script ) {
377 $this->mScripts
.= $script . "\n";
381 * Register and add a stylesheet from an extension directory.
383 * @param string $url path to sheet. Provide either a full url (beginning
384 * with 'http', etc) or a relative path from the document root
385 * (beginning with '/'). Otherwise it behaves identically to
386 * addStyle() and draws from the /skins folder.
388 public function addExtensionStyle( $url ) {
389 array_push( $this->mExtStyles
, $url );
393 * Get all styles added by extensions
397 function getExtStyle() {
398 return $this->mExtStyles
;
402 * Add a JavaScript file out of skins/common, or a given relative path.
404 * @param string $file filename in skins/common or complete on-server path
406 * @param string $version style version of the file. Defaults to $wgStyleVersion
408 public function addScriptFile( $file, $version = null ) {
409 global $wgStylePath, $wgStyleVersion;
410 // See if $file parameter is an absolute URL or begins with a slash
411 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
414 $path = "{$wgStylePath}/common/{$file}";
416 if ( is_null( $version ) ) {
417 $version = $wgStyleVersion;
419 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
423 * Add a self-contained script tag with the given contents
425 * @param string $script JavaScript text, no "<script>" tags
427 public function addInlineScript( $script ) {
428 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
432 * Get all registered JS and CSS tags for the header.
436 function getScript() {
437 return $this->mScripts
. $this->getHeadItems();
441 * Filter an array of modules to remove insufficiently trustworthy members, and modules
442 * which are no longer registered (eg a page is cached before an extension is disabled)
443 * @param array $modules
444 * @param string|null $position if not null, only return modules with this position
445 * @param string $type
448 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule
::TYPE_COMBINED
) {
449 $resourceLoader = $this->getResourceLoader();
450 $filteredModules = array();
451 foreach ( $modules as $val ) {
452 $module = $resourceLoader->getModule( $val );
453 if ( $module instanceof ResourceLoaderModule
454 && $module->getOrigin() <= $this->getAllowedModules( $type )
455 && ( is_null( $position ) ||
$module->getPosition() == $position )
456 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
458 $filteredModules[] = $val;
461 return $filteredModules;
465 * Get the list of modules to include on this page
467 * @param bool $filter Whether to filter out insufficiently trustworthy modules
468 * @param string|null $position If not null, only return modules with this position
469 * @param string $param
470 * @return array Array of module names
472 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
473 $modules = array_values( array_unique( $this->$param ) );
475 ?
$this->filterModules( $modules, $position )
480 * Add one or more modules recognized by the resource loader. Modules added
481 * through this function will be loaded by the resource loader when the
484 * @param string|array $modules Module name (string) or array of module names
486 public function addModules( $modules ) {
487 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
491 * Get the list of module JS to include on this page
493 * @param bool $filter
494 * @param string|null $position
496 * @return array Array of module names
498 public function getModuleScripts( $filter = false, $position = null ) {
499 return $this->getModules( $filter, $position, 'mModuleScripts' );
503 * Add only JS of one or more modules recognized by the resource loader. Module
504 * scripts added through this function will be loaded by the resource loader when
507 * @param string|array $modules Module name (string) or array of module names
509 public function addModuleScripts( $modules ) {
510 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
514 * Get the list of module CSS to include on this page
516 * @param bool $filter
517 * @param string|null $position
519 * @return array Array of module names
521 public function getModuleStyles( $filter = false, $position = null ) {
522 return $this->getModules( $filter, $position, 'mModuleStyles' );
526 * Add only CSS of one or more modules recognized by the resource loader.
528 * Module styles added through this function will be added using standard link CSS
529 * tags, rather than as a combined Javascript and CSS package. Thus, they will
530 * load when JavaScript is disabled (unless CSS also happens to be disabled).
532 * @param string|array $modules Module name (string) or array of module names
534 public function addModuleStyles( $modules ) {
535 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
539 * Get the list of module messages to include on this page
541 * @param bool $filter
542 * @param string|null $position
544 * @return array Array of module names
546 public function getModuleMessages( $filter = false, $position = null ) {
547 return $this->getModules( $filter, $position, 'mModuleMessages' );
551 * Add only messages of one or more modules recognized by the resource loader.
552 * Module messages added through this function will be loaded by the resource
553 * loader when the page loads.
555 * @param string|array $modules Module name (string) or array of module names
557 public function addModuleMessages( $modules ) {
558 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
562 * @return null|string ResourceLoader target
564 public function getTarget() {
565 return $this->mTarget
;
569 * Sets ResourceLoader target for load.php links. If null, will be omitted
571 * @param string|null $target
573 public function setTarget( $target ) {
574 $this->mTarget
= $target;
578 * Get an array of head items
582 function getHeadItemsArray() {
583 return $this->mHeadItems
;
587 * Get all header items in a string
591 function getHeadItems() {
593 foreach ( $this->mHeadItems
as $item ) {
600 * Add or replace an header item to the output
602 * @param string $name item name
603 * @param string $value raw HTML
605 public function addHeadItem( $name, $value ) {
606 $this->mHeadItems
[$name] = $value;
610 * Check if the header item $name is already set
612 * @param string $name Item name
615 public function hasHeadItem( $name ) {
616 return isset( $this->mHeadItems
[$name] );
620 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
622 * @param string $tag value of "ETag" header
624 function setETag( $tag ) {
629 * Set whether the output should only contain the body of the article,
630 * without any skin, sidebar, etc.
631 * Used e.g. when calling with "action=render".
633 * @param bool $only Whether to output only the body of the article
635 public function setArticleBodyOnly( $only ) {
636 $this->mArticleBodyOnly
= $only;
640 * Return whether the output will contain only the body of the article
644 public function getArticleBodyOnly() {
645 return $this->mArticleBodyOnly
;
649 * Set an additional output property
652 * @param string $name
653 * @param mixed $value
655 public function setProperty( $name, $value ) {
656 $this->mProperties
[$name] = $value;
660 * Get an additional output property
663 * @param string $name
664 * @return mixed Property value or null if not found
666 public function getProperty( $name ) {
667 if ( isset( $this->mProperties
[$name] ) ) {
668 return $this->mProperties
[$name];
675 * checkLastModified tells the client to use the client-cached page if
676 * possible. If successful, the OutputPage is disabled so that
677 * any future call to OutputPage->output() have no effect.
679 * Side effect: sets mLastModified for Last-Modified header
681 * @param string $timestamp
683 * @return bool True if cache-ok headers was sent.
685 public function checkLastModified( $timestamp ) {
686 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
688 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
689 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
692 if ( !$wgCachePages ) {
693 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
697 $timestamp = wfTimestamp( TS_MW
, $timestamp );
698 $modifiedTimes = array(
699 'page' => $timestamp,
700 'user' => $this->getUser()->getTouched(),
701 'epoch' => $wgCacheEpoch
704 // bug 44570: the core page itself may not change, but resources might
705 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $wgSquidMaxage );
707 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
709 $maxModified = max( $modifiedTimes );
710 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
712 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
713 if ( $clientHeader === false ) {
714 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
718 # IE sends sizes after the date like this:
719 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
720 # this breaks strtotime().
721 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
723 wfSuppressWarnings(); // E_STRICT system time bitching
724 $clientHeaderTime = strtotime( $clientHeader );
726 if ( !$clientHeaderTime ) {
727 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
730 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
734 foreach ( $modifiedTimes as $name => $value ) {
735 if ( $info !== '' ) {
738 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
741 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
742 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
743 wfDebug( __METHOD__
. ": effective Last-Modified: " .
744 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
745 if ( $clientHeaderTime < $maxModified ) {
746 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
751 # Give a 304 response code and disable body output
752 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
753 ini_set( 'zlib.output_compression', 0 );
754 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
755 $this->sendCacheControl();
758 // Don't output a compressed blob when using ob_gzhandler;
759 // it's technically against HTTP spec and seems to confuse
760 // Firefox when the response gets split over two packets.
761 wfClearOutputBuffers();
767 * Override the last modified timestamp
769 * @param string $timestamp new timestamp, in a format readable by
772 public function setLastModified( $timestamp ) {
773 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
777 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
779 * @param string $policy the literal string to output as the contents of
780 * the meta tag. Will be parsed according to the spec and output in
784 public function setRobotPolicy( $policy ) {
785 $policy = Article
::formatRobotPolicy( $policy );
787 if ( isset( $policy['index'] ) ) {
788 $this->setIndexPolicy( $policy['index'] );
790 if ( isset( $policy['follow'] ) ) {
791 $this->setFollowPolicy( $policy['follow'] );
796 * Set the index policy for the page, but leave the follow policy un-
799 * @param string $policy Either 'index' or 'noindex'.
802 public function setIndexPolicy( $policy ) {
803 $policy = trim( $policy );
804 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
805 $this->mIndexPolicy
= $policy;
810 * Set the follow policy for the page, but leave the index policy un-
813 * @param string $policy either 'follow' or 'nofollow'.
816 public function setFollowPolicy( $policy ) {
817 $policy = trim( $policy );
818 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
819 $this->mFollowPolicy
= $policy;
824 * Set the new value of the "action text", this will be added to the
825 * "HTML title", separated from it with " - ".
827 * @param string $text new value of the "action text"
829 public function setPageTitleActionText( $text ) {
830 $this->mPageTitleActionText
= $text;
834 * Get the value of the "action text"
838 public function getPageTitleActionText() {
839 if ( isset( $this->mPageTitleActionText
) ) {
840 return $this->mPageTitleActionText
;
846 * "HTML title" means the contents of "<title>".
847 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
849 * @param string $name
851 public function setHTMLTitle( $name ) {
852 if ( $name instanceof Message
) {
853 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
855 $this->mHTMLtitle
= $name;
860 * Return the "HTML title", i.e. the content of the "<title>" tag.
864 public function getHTMLTitle() {
865 return $this->mHTMLtitle
;
869 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
873 public function setRedirectedFrom( $t ) {
874 $this->mRedirectedFrom
= $t;
878 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
879 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
880 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
881 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
883 * @param string|Message $name
885 public function setPageTitle( $name ) {
886 if ( $name instanceof Message
) {
887 $name = $name->setContext( $this->getContext() )->text();
890 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
891 # but leave "<i>foobar</i>" alone
892 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
893 $this->mPagetitle
= $nameWithTags;
895 # change "<i>foo&bar</i>" to "foo&bar"
897 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
898 ->inContentLanguage()
903 * Return the "page title", i.e. the content of the \<h1\> tag.
907 public function getPageTitle() {
908 return $this->mPagetitle
;
912 * Set the Title object to use
916 public function setTitle( Title
$t ) {
917 $this->getContext()->setTitle( $t );
921 * Replace the subtitle with $str
923 * @param string|Message $str new value of the subtitle. String should be safe HTML.
925 public function setSubtitle( $str ) {
926 $this->clearSubtitle();
927 $this->addSubtitle( $str );
931 * Add $str to the subtitle
933 * @deprecated since 1.19; use addSubtitle() instead
934 * @param string|Message $str to add to the subtitle
936 public function appendSubtitle( $str ) {
937 $this->addSubtitle( $str );
941 * Add $str to the subtitle
943 * @param string|Message $str to add to the subtitle. String should be safe HTML.
945 public function addSubtitle( $str ) {
946 if ( $str instanceof Message
) {
947 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
949 $this->mSubtitle
[] = $str;
954 * Add a subtitle containing a backlink to a page
956 * @param Title $title Title to link to
958 public function addBacklinkSubtitle( Title
$title ) {
960 if ( $title->isRedirect() ) {
961 $query['redirect'] = 'no';
963 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker
::link( $title, null, array(), $query ) ) );
967 * Clear the subtitles
969 public function clearSubtitle() {
970 $this->mSubtitle
= array();
978 public function getSubtitle() {
979 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
983 * Set the page as printable, i.e. it'll be displayed with with all
984 * print styles included
986 public function setPrintable() {
987 $this->mPrintable
= true;
991 * Return whether the page is "printable"
995 public function isPrintable() {
996 return $this->mPrintable
;
1000 * Disable output completely, i.e. calling output() will have no effect
1002 public function disable() {
1003 $this->mDoNothing
= true;
1007 * Return whether the output will be completely disabled
1011 public function isDisabled() {
1012 return $this->mDoNothing
;
1016 * Show an "add new section" link?
1020 public function showNewSectionLink() {
1021 return $this->mNewSectionLink
;
1025 * Forcibly hide the new section link?
1029 public function forceHideNewSectionLink() {
1030 return $this->mHideNewSectionLink
;
1034 * Add or remove feed links in the page header
1035 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1036 * for the new version
1037 * @see addFeedLink()
1039 * @param bool $show true: add default feeds, false: remove all feeds
1041 public function setSyndicated( $show = true ) {
1043 $this->setFeedAppendQuery( false );
1045 $this->mFeedLinks
= array();
1050 * Add default feeds to the page header
1051 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1052 * for the new version
1053 * @see addFeedLink()
1055 * @param string $val query to append to feed links or false to output
1058 public function setFeedAppendQuery( $val ) {
1059 global $wgAdvertisedFeedTypes;
1061 $this->mFeedLinks
= array();
1063 foreach ( $wgAdvertisedFeedTypes as $type ) {
1064 $query = "feed=$type";
1065 if ( is_string( $val ) ) {
1066 $query .= '&' . $val;
1068 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1073 * Add a feed link to the page header
1075 * @param string $format feed type, should be a key of $wgFeedClasses
1076 * @param string $href URL
1078 public function addFeedLink( $format, $href ) {
1079 global $wgAdvertisedFeedTypes;
1081 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1082 $this->mFeedLinks
[$format] = $href;
1087 * Should we output feed links for this page?
1090 public function isSyndicated() {
1091 return count( $this->mFeedLinks
) > 0;
1095 * Return URLs for each supported syndication format for this page.
1096 * @return array associating format keys with URLs
1098 public function getSyndicationLinks() {
1099 return $this->mFeedLinks
;
1103 * Will currently always return null
1107 public function getFeedAppendQuery() {
1108 return $this->mFeedLinksAppendQuery
;
1112 * Set whether the displayed content is related to the source of the
1113 * corresponding article on the wiki
1114 * Setting true will cause the change "article related" toggle to true
1118 public function setArticleFlag( $v ) {
1119 $this->mIsarticle
= $v;
1121 $this->mIsArticleRelated
= $v;
1126 * Return whether the content displayed page is related to the source of
1127 * the corresponding article on the wiki
1131 public function isArticle() {
1132 return $this->mIsarticle
;
1136 * Set whether this page is related an article on the wiki
1137 * Setting false will cause the change of "article flag" toggle to false
1141 public function setArticleRelated( $v ) {
1142 $this->mIsArticleRelated
= $v;
1144 $this->mIsarticle
= false;
1149 * Return whether this page is related an article on the wiki
1153 public function isArticleRelated() {
1154 return $this->mIsArticleRelated
;
1158 * Add new language links
1160 * @param array $newLinkArray Associative array mapping language code to the page
1163 public function addLanguageLinks( $newLinkArray ) {
1164 $this->mLanguageLinks +
= $newLinkArray;
1168 * Reset the language links and add new language links
1170 * @param array $newLinkArray Associative array mapping language code to the page
1173 public function setLanguageLinks( $newLinkArray ) {
1174 $this->mLanguageLinks
= $newLinkArray;
1178 * Get the list of language links
1180 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1182 public function getLanguageLinks() {
1183 return $this->mLanguageLinks
;
1187 * Add an array of categories, with names in the keys
1189 * @param array $categories mapping category name => sort key
1191 public function addCategoryLinks( $categories ) {
1194 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1198 # Add the links to a LinkBatch
1199 $arr = array( NS_CATEGORY
=> $categories );
1200 $lb = new LinkBatch
;
1201 $lb->setArray( $arr );
1203 # Fetch existence plus the hiddencat property
1204 $dbr = wfGetDB( DB_SLAVE
);
1205 $res = $dbr->select( array( 'page', 'page_props' ),
1206 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1207 $lb->constructSet( 'page', $dbr ),
1210 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1213 # Add the results to the link cache
1214 $lb->addResultToCache( LinkCache
::singleton(), $res );
1216 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1217 $categories = array_combine(
1218 array_keys( $categories ),
1219 array_fill( 0, count( $categories ), 'normal' )
1222 # Mark hidden categories
1223 foreach ( $res as $row ) {
1224 if ( isset( $row->pp_value
) ) {
1225 $categories[$row->page_title
] = 'hidden';
1229 # Add the remaining categories to the skin
1230 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1231 foreach ( $categories as $category => $type ) {
1232 $origcategory = $category;
1233 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1234 $wgContLang->findVariantLink( $category, $title, true );
1235 if ( $category != $origcategory ) {
1236 if ( array_key_exists( $category, $categories ) ) {
1240 $text = $wgContLang->convertHtml( $title->getText() );
1241 $this->mCategories
[] = $title->getText();
1242 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1248 * Reset the category links (but not the category list) and add $categories
1250 * @param array $categories mapping category name => sort key
1252 public function setCategoryLinks( $categories ) {
1253 $this->mCategoryLinks
= array();
1254 $this->addCategoryLinks( $categories );
1258 * Get the list of category links, in a 2-D array with the following format:
1259 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1260 * hidden categories) and $link a HTML fragment with a link to the category
1265 public function getCategoryLinks() {
1266 return $this->mCategoryLinks
;
1270 * Get the list of category names this page belongs to
1272 * @return array Array of strings
1274 public function getCategories() {
1275 return $this->mCategories
;
1279 * Do not allow scripts which can be modified by wiki users to load on this page;
1280 * only allow scripts bundled with, or generated by, the software.
1282 public function disallowUserJs() {
1283 $this->reduceAllowedModules(
1284 ResourceLoaderModule
::TYPE_SCRIPTS
,
1285 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1290 * Return whether user JavaScript is allowed for this page
1291 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1292 * trustworthiness is identified and enforced automagically.
1295 public function isUserJsAllowed() {
1296 wfDeprecated( __METHOD__
, '1.18' );
1297 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >= ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1301 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1302 * @see ResourceLoaderModule::$origin
1303 * @param string $type ResourceLoaderModule TYPE_ constant
1304 * @return int ResourceLoaderModule ORIGIN_ class constant
1306 public function getAllowedModules( $type ) {
1307 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1308 return min( array_values( $this->mAllowedModules
) );
1310 return isset( $this->mAllowedModules
[$type] )
1311 ?
$this->mAllowedModules
[$type]
1312 : ResourceLoaderModule
::ORIGIN_ALL
;
1317 * Set the highest level of CSS/JS untrustworthiness allowed
1318 * @param string $type ResourceLoaderModule TYPE_ constant
1319 * @param int $level ResourceLoaderModule class constant
1321 public function setAllowedModules( $type, $level ) {
1322 $this->mAllowedModules
[$type] = $level;
1326 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1327 * @param string $type
1328 * @param int $level ResourceLoaderModule class constant
1330 public function reduceAllowedModules( $type, $level ) {
1331 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1335 * Prepend $text to the body HTML
1337 * @param string $text HTML
1339 public function prependHTML( $text ) {
1340 $this->mBodytext
= $text . $this->mBodytext
;
1344 * Append $text to the body HTML
1346 * @param string $text HTML
1348 public function addHTML( $text ) {
1349 $this->mBodytext
.= $text;
1353 * Shortcut for adding an Html::element via addHTML.
1357 * @param string $element
1358 * @param array $attribs
1359 * @param string $contents
1361 public function addElement( $element, $attribs = array(), $contents = '' ) {
1362 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1366 * Clear the body HTML
1368 public function clearHTML() {
1369 $this->mBodytext
= '';
1375 * @return string HTML
1377 public function getHTML() {
1378 return $this->mBodytext
;
1382 * Get/set the ParserOptions object to use for wikitext parsing
1384 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1385 * current ParserOption object
1386 * @return ParserOptions
1388 public function parserOptions( $options = null ) {
1389 if ( !$this->mParserOptions
) {
1390 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1391 $this->mParserOptions
->setEditSection( false );
1393 return wfSetVar( $this->mParserOptions
, $options );
1397 * Set the revision ID which will be seen by the wiki text parser
1398 * for things such as embedded {{REVISIONID}} variable use.
1400 * @param int|null $revid An positive integer, or null
1401 * @return mixed Previous value
1403 public function setRevisionId( $revid ) {
1404 $val = is_null( $revid ) ?
null : intval( $revid );
1405 return wfSetVar( $this->mRevisionId
, $val );
1409 * Get the displayed revision ID
1413 public function getRevisionId() {
1414 return $this->mRevisionId
;
1418 * Set the timestamp of the revision which will be displayed. This is used
1419 * to avoid a extra DB call in Skin::lastModified().
1421 * @param string|null $timestamp
1422 * @return mixed Previous value
1424 public function setRevisionTimestamp( $timestamp ) {
1425 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1429 * Get the timestamp of displayed revision.
1430 * This will be null if not filled by setRevisionTimestamp().
1432 * @return string|null
1434 public function getRevisionTimestamp() {
1435 return $this->mRevisionTimestamp
;
1439 * Set the displayed file version
1441 * @param File|bool $file
1442 * @return mixed Previous value
1444 public function setFileVersion( $file ) {
1446 if ( $file instanceof File
&& $file->exists() ) {
1447 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1449 return wfSetVar( $this->mFileVersion
, $val, true );
1453 * Get the displayed file version
1455 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1457 public function getFileVersion() {
1458 return $this->mFileVersion
;
1462 * Get the templates used on this page
1464 * @return array (namespace => dbKey => revId)
1467 public function getTemplateIds() {
1468 return $this->mTemplateIds
;
1472 * Get the files used on this page
1474 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1477 public function getFileSearchOptions() {
1478 return $this->mImageTimeKeys
;
1482 * Convert wikitext to HTML and add it to the buffer
1483 * Default assumes that the current page title will be used.
1485 * @param string $text
1486 * @param bool $linestart Is this the start of a line?
1487 * @param bool $interface Is this text in the user interface language?
1489 public function addWikiText( $text, $linestart = true, $interface = true ) {
1490 $title = $this->getTitle(); // Work around E_STRICT
1492 throw new MWException( 'Title is null' );
1494 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1498 * Add wikitext with a custom Title object
1500 * @param string $text Wikitext
1501 * @param Title $title
1502 * @param bool $linestart Is this the start of a line?
1504 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1505 $this->addWikiTextTitle( $text, $title, $linestart );
1509 * Add wikitext with a custom Title object and tidy enabled.
1511 * @param string $text Wikitext
1512 * @param Title $title
1513 * @param bool $linestart Is this the start of a line?
1515 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1516 $this->addWikiTextTitle( $text, $title, $linestart, true );
1520 * Add wikitext with tidy enabled
1522 * @param string $text Wikitext
1523 * @param bool $linestart Is this the start of a line?
1525 public function addWikiTextTidy( $text, $linestart = true ) {
1526 $title = $this->getTitle();
1527 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1531 * Add wikitext with a custom Title object
1533 * @param string $text Wikitext
1534 * @param Title $title
1535 * @param bool $linestart Is this the start of a line?
1536 * @param bool $tidy Whether to use tidy
1537 * @param bool $interface Whether it is an interface message
1538 * (for example disables conversion)
1540 public function addWikiTextTitle( $text, Title
$title, $linestart, $tidy = false, $interface = false ) {
1543 wfProfileIn( __METHOD__
);
1545 $popts = $this->parserOptions();
1546 $oldTidy = $popts->setTidy( $tidy );
1547 $popts->setInterfaceMessage( (bool)$interface );
1549 $parserOutput = $wgParser->parse(
1550 $text, $title, $popts,
1551 $linestart, true, $this->mRevisionId
1554 $popts->setTidy( $oldTidy );
1556 $this->addParserOutput( $parserOutput );
1558 wfProfileOut( __METHOD__
);
1562 * Add a ParserOutput object, but without Html
1564 * @param ParserOutput $parserOutput
1566 public function addParserOutputNoText( &$parserOutput ) {
1567 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1568 $this->addCategoryLinks( $parserOutput->getCategories() );
1569 $this->mNewSectionLink
= $parserOutput->getNewSection();
1570 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1572 $this->mParseWarnings
= $parserOutput->getWarnings();
1573 if ( !$parserOutput->isCacheable() ) {
1574 $this->enableClientCache( false );
1576 $this->mNoGallery
= $parserOutput->getNoGallery();
1577 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1578 $this->addModules( $parserOutput->getModules() );
1579 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1580 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1581 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1582 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1584 // Template versioning...
1585 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1586 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1587 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1589 $this->mTemplateIds
[$ns] = $dbks;
1592 // File versioning...
1593 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1594 $this->mImageTimeKeys
[$dbk] = $data;
1597 // Hooks registered in the object
1598 global $wgParserOutputHooks;
1599 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1600 list( $hookName, $data ) = $hookInfo;
1601 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1602 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1606 // Link flags are ignored for now, but may in the future be
1607 // used to mark individual language links.
1608 $linkFlags = array();
1609 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1610 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1614 * Add a ParserOutput object
1616 * @param ParserOutput $parserOutput
1618 function addParserOutput( &$parserOutput ) {
1619 $this->addParserOutputNoText( $parserOutput );
1620 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1622 // Touch section edit links only if not previously disabled
1623 if ( $parserOutput->getEditSectionTokens() ) {
1624 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1626 $text = $parserOutput->getText();
1627 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1628 $this->addHTML( $text );
1632 * Add the output of a QuickTemplate to the output buffer
1634 * @param QuickTemplate $template
1636 public function addTemplate( &$template ) {
1637 $this->addHTML( $template->getHTML() );
1641 * Parse wikitext and return the HTML.
1643 * @param string $text
1644 * @param bool $linestart Is this the start of a line?
1645 * @param bool $interface Use interface language ($wgLang instead of
1646 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1647 * This also disables LanguageConverter.
1648 * @param Language $language Target language object, will override $interface
1649 * @throws MWException
1650 * @return string HTML
1652 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1655 if ( is_null( $this->getTitle() ) ) {
1656 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1659 $popts = $this->parserOptions();
1661 $popts->setInterfaceMessage( true );
1663 if ( $language !== null ) {
1664 $oldLang = $popts->setTargetLanguage( $language );
1667 $parserOutput = $wgParser->parse(
1668 $text, $this->getTitle(), $popts,
1669 $linestart, true, $this->mRevisionId
1673 $popts->setInterfaceMessage( false );
1675 if ( $language !== null ) {
1676 $popts->setTargetLanguage( $oldLang );
1679 return $parserOutput->getText();
1683 * Parse wikitext, strip paragraphs, and return the HTML.
1685 * @param string $text
1686 * @param bool $linestart Is this the start of a line?
1687 * @param bool $interface Use interface language ($wgLang instead of
1688 * $wgContLang) while parsing language sensitive magic
1689 * words like GRAMMAR and PLURAL
1690 * @return string HTML
1692 public function parseInline( $text, $linestart = true, $interface = false ) {
1693 $parsed = $this->parse( $text, $linestart, $interface );
1696 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1704 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1706 * @param int $maxage Maximum cache time on the Squid, in seconds.
1708 public function setSquidMaxage( $maxage ) {
1709 $this->mSquidMaxage
= $maxage;
1713 * Use enableClientCache(false) to force it to send nocache headers
1715 * @param bool $state
1719 public function enableClientCache( $state ) {
1720 return wfSetVar( $this->mEnableClientCache
, $state );
1724 * Get the list of cookies that will influence on the cache
1728 function getCacheVaryCookies() {
1729 global $wgCookiePrefix, $wgCacheVaryCookies;
1731 if ( $cookies === null ) {
1732 $cookies = array_merge(
1734 "{$wgCookiePrefix}Token",
1735 "{$wgCookiePrefix}LoggedOut",
1741 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1747 * Check if the request has a cache-varying cookie header
1748 * If it does, it's very important that we don't allow public caching
1752 function haveCacheVaryCookies() {
1753 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1754 if ( $cookieHeader === false ) {
1757 $cvCookies = $this->getCacheVaryCookies();
1758 foreach ( $cvCookies as $cookieName ) {
1759 # Check for a simple string match, like the way squid does it
1760 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1761 wfDebug( __METHOD__
. ": found $cookieName\n" );
1765 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1770 * Add an HTTP header that will influence on the cache
1772 * @param string $header header name
1773 * @param array|null $option
1774 * @todo FIXME: Document the $option parameter; it appears to be for
1775 * X-Vary-Options but what format is acceptable?
1777 public function addVaryHeader( $header, $option = null ) {
1778 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1779 $this->mVaryHeader
[$header] = (array)$option;
1780 } elseif ( is_array( $option ) ) {
1781 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1782 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1784 $this->mVaryHeader
[$header] = $option;
1787 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1791 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1792 * such as Accept-Encoding or Cookie
1796 public function getVaryHeader() {
1797 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1801 * Get a complete X-Vary-Options header
1805 public function getXVO() {
1806 $cvCookies = $this->getCacheVaryCookies();
1808 $cookiesOption = array();
1809 foreach ( $cvCookies as $cookieName ) {
1810 $cookiesOption[] = 'string-contains=' . $cookieName;
1812 $this->addVaryHeader( 'Cookie', $cookiesOption );
1815 foreach ( $this->mVaryHeader
as $header => $option ) {
1816 $newheader = $header;
1817 if ( is_array( $option ) && count( $option ) > 0 ) {
1818 $newheader .= ';' . implode( ';', $option );
1820 $headers[] = $newheader;
1822 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1828 * bug 21672: Add Accept-Language to Vary and XVO headers
1829 * if there's no 'variant' parameter existed in GET.
1832 * /w/index.php?title=Main_page should always be served; but
1833 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1835 function addAcceptLanguage() {
1836 $lang = $this->getTitle()->getPageLanguage();
1837 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1838 $variants = $lang->getVariants();
1839 $aloption = array();
1840 foreach ( $variants as $variant ) {
1841 if ( $variant === $lang->getCode() ) {
1844 $aloption[] = 'string-contains=' . $variant;
1846 // IE and some other browsers use BCP 47 standards in
1847 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1848 // We should handle these too.
1849 $variantBCP47 = wfBCP47( $variant );
1850 if ( $variantBCP47 !== $variant ) {
1851 $aloption[] = 'string-contains=' . $variantBCP47;
1855 $this->addVaryHeader( 'Accept-Language', $aloption );
1860 * Set a flag which will cause an X-Frame-Options header appropriate for
1861 * edit pages to be sent. The header value is controlled by
1862 * $wgEditPageFrameOptions.
1864 * This is the default for special pages. If you display a CSRF-protected
1865 * form on an ordinary view page, then you need to call this function.
1867 * @param bool $enable
1869 public function preventClickjacking( $enable = true ) {
1870 $this->mPreventClickjacking
= $enable;
1874 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1875 * This can be called from pages which do not contain any CSRF-protected
1878 public function allowClickjacking() {
1879 $this->mPreventClickjacking
= false;
1883 * Get the X-Frame-Options header value (without the name part), or false
1884 * if there isn't one. This is used by Skin to determine whether to enable
1885 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1889 public function getFrameOptions() {
1890 global $wgBreakFrames, $wgEditPageFrameOptions;
1891 if ( $wgBreakFrames ) {
1893 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1894 return $wgEditPageFrameOptions;
1900 * Send cache control HTTP headers
1902 public function sendCacheControl() {
1903 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1905 $response = $this->getRequest()->response();
1906 if ( $wgUseETag && $this->mETag
) {
1907 $response->header( "ETag: $this->mETag" );
1910 $this->addVaryHeader( 'Cookie' );
1911 $this->addAcceptLanguage();
1913 # don't serve compressed data to clients who can't handle it
1914 # maintain different caches for logged-in users and non-logged in ones
1915 $response->header( $this->getVaryHeader() );
1918 # Add an X-Vary-Options header for Squid with Wikimedia patches
1919 $response->header( $this->getXVO() );
1922 if ( $this->mEnableClientCache
) {
1924 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1925 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1928 # We'll purge the proxy cache explicitly, but require end user agents
1929 # to revalidate against the proxy on each visit.
1930 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1931 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
1932 # start with a shorter timeout for initial testing
1933 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1934 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
1935 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1937 # We'll purge the proxy cache for anons explicitly, but require end user agents
1938 # to revalidate against the proxy on each visit.
1939 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1940 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1941 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
1942 # start with a shorter timeout for initial testing
1943 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1944 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
. ', must-revalidate, max-age=0' );
1947 # We do want clients to cache if they can, but they *must* check for updates
1948 # on revisiting the page.
1949 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
1950 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1951 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1953 if ( $this->mLastModified
) {
1954 $response->header( "Last-Modified: {$this->mLastModified}" );
1957 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
1959 # In general, the absence of a last modified header should be enough to prevent
1960 # the client from using its cache. We send a few other things just to make sure.
1961 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1962 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1963 $response->header( 'Pragma: no-cache' );
1968 * Get the message associated with the HTTP response code $code
1970 * @param int $code Status code
1971 * @return string|null Message or null if $code is not in the list of messages
1973 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1975 public static function getStatusMessage( $code ) {
1976 wfDeprecated( __METHOD__
, '1.18' );
1977 return HttpStatus
::getMessage( $code );
1981 * Finally, all the text has been munged and accumulated into
1982 * the object, let's actually output it:
1984 public function output() {
1985 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
1986 $wgUseAjax, $wgResponsiveImages;
1988 if ( $this->mDoNothing
) {
1992 wfProfileIn( __METHOD__
);
1994 $response = $this->getRequest()->response();
1996 if ( $this->mRedirect
!= '' ) {
1997 # Standards require redirect URLs to be absolute
1998 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2000 $redirect = $this->mRedirect
;
2001 $code = $this->mRedirectCode
;
2003 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2004 if ( $code == '301' ||
$code == '303' ) {
2005 if ( !$wgDebugRedirects ) {
2006 $message = HttpStatus
::getMessage( $code );
2007 $response->header( "HTTP/1.1 $code $message" );
2009 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2011 if ( $wgVaryOnXFP ) {
2012 $this->addVaryHeader( 'X-Forwarded-Proto' );
2014 $this->sendCacheControl();
2016 $response->header( "Content-Type: text/html; charset=utf-8" );
2017 if ( $wgDebugRedirects ) {
2018 $url = htmlspecialchars( $redirect );
2019 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2020 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2021 print "</body>\n</html>\n";
2023 $response->header( 'Location: ' . $redirect );
2027 wfProfileOut( __METHOD__
);
2029 } elseif ( $this->mStatusCode
) {
2030 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2032 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2036 # Buffer output; final headers may depend on later processing
2039 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2040 $response->header( 'Content-language: ' . $wgLanguageCode );
2042 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2043 // jQuery etc. can work correctly.
2044 $response->header( 'X-UA-Compatible: IE=Edge' );
2046 // Prevent framing, if requested
2047 $frameOptions = $this->getFrameOptions();
2048 if ( $frameOptions ) {
2049 $response->header( "X-Frame-Options: $frameOptions" );
2052 if ( $this->mArticleBodyOnly
) {
2053 echo $this->mBodytext
;
2056 $sk = $this->getSkin();
2057 // add skin specific modules
2058 $modules = $sk->getDefaultModules();
2060 // enforce various default modules for all skins
2061 $coreModules = array(
2062 // keep this list as small as possible
2063 'mediawiki.page.startup',
2067 // Support for high-density display images if enabled
2068 if ( $wgResponsiveImages ) {
2069 $coreModules[] = 'mediawiki.hidpi';
2072 $this->addModules( $coreModules );
2073 foreach ( $modules as $group ) {
2074 $this->addModules( $group );
2076 MWDebug
::addModules( $this );
2078 // FIXME: deprecate? - not clear why this is useful
2079 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2082 // Hook that allows last minute changes to the output page, e.g.
2083 // adding of CSS or Javascript by extensions.
2084 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2086 wfProfileIn( 'Output-skin' );
2088 wfProfileOut( 'Output-skin' );
2091 // This hook allows last minute changes to final overall output by modifying output buffer
2092 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2094 $this->sendCacheControl();
2098 wfProfileOut( __METHOD__
);
2102 * Actually output something with print.
2104 * @param string $ins the string to output
2105 * @deprecated since 1.22 Use echo yourself.
2107 public function out( $ins ) {
2108 wfDeprecated( __METHOD__
, '1.22' );
2113 * Produce a "user is blocked" page.
2114 * @deprecated since 1.18
2116 function blockedPage() {
2117 throw new UserBlockedError( $this->getUser()->mBlock
);
2121 * Prepare this object to display an error page; disable caching and
2122 * indexing, clear the current text and redirect, set the page's title
2123 * and optionally an custom HTML title (content of the "<title>" tag).
2125 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2126 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2127 * optional, if not passed the "<title>" attribute will be
2128 * based on $pageTitle
2130 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2131 $this->setPageTitle( $pageTitle );
2132 if ( $htmlTitle !== false ) {
2133 $this->setHTMLTitle( $htmlTitle );
2135 $this->setRobotPolicy( 'noindex,nofollow' );
2136 $this->setArticleRelated( false );
2137 $this->enableClientCache( false );
2138 $this->mRedirect
= '';
2139 $this->clearSubtitle();
2144 * Output a standard error page
2146 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2147 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2148 * showErrorPage( 'titlemsg', $messageObject );
2149 * showErrorPage( $titleMessageObject, $messageObject );
2151 * @param string|Message $title Message key (string) for page title, or a Message object
2152 * @param string|Message $msg Message key (string) for page text, or a Message object
2153 * @param array $params Message parameters; ignored if $msg is a Message object
2155 public function showErrorPage( $title, $msg, $params = array() ) {
2156 if ( !$title instanceof Message
) {
2157 $title = $this->msg( $title );
2160 $this->prepareErrorPage( $title );
2162 if ( $msg instanceof Message
) {
2163 if ( $params !== array() ) {
2164 trigger_error( 'Argument ignored: $params. The message parameters argument is discarded when the $msg argument is a Message object instead of a string.', E_USER_NOTICE
);
2166 $this->addHTML( $msg->parseAsBlock() );
2168 $this->addWikiMsgArray( $msg, $params );
2171 $this->returnToMain();
2175 * Output a standard permission error page
2177 * @param array $errors error message keys
2178 * @param string $action action that was denied or null if unknown
2180 public function showPermissionsErrorPage( $errors, $action = null ) {
2181 // For some action (read, edit, create and upload), display a "login to do this action"
2182 // error if all of the following conditions are met:
2183 // 1. the user is not logged in
2184 // 2. the only error is insufficient permissions (i.e. no block or something else)
2185 // 3. the error can be avoided simply by logging in
2186 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2187 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2188 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2189 && ( User
::groupHasPermission( 'user', $action )
2190 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2192 $displayReturnto = null;
2194 # Due to bug 32276, if a user does not have read permissions,
2195 # $this->getTitle() will just give Special:Badtitle, which is
2196 # not especially useful as a returnto parameter. Use the title
2197 # from the request instead, if there was one.
2198 $request = $this->getRequest();
2199 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2200 if ( $action == 'edit' ) {
2201 $msg = 'whitelistedittext';
2202 $displayReturnto = $returnto;
2203 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2204 $msg = 'nocreatetext';
2205 } elseif ( $action == 'upload' ) {
2206 $msg = 'uploadnologintext';
2208 $msg = 'loginreqpagetext';
2209 $displayReturnto = Title
::newMainPage();
2215 $query['returnto'] = $returnto->getPrefixedText();
2217 if ( !$request->wasPosted() ) {
2218 $returntoquery = $request->getValues();
2219 unset( $returntoquery['title'] );
2220 unset( $returntoquery['returnto'] );
2221 unset( $returntoquery['returntoquery'] );
2222 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2225 $loginLink = Linker
::linkKnown(
2226 SpecialPage
::getTitleFor( 'Userlogin' ),
2227 $this->msg( 'loginreqlink' )->escaped(),
2232 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2233 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2235 # Don't return to a page the user can't read otherwise
2236 # we'll end up in a pointless loop
2237 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2238 $this->returnToMain( null, $displayReturnto );
2241 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2242 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2247 * Display an error page indicating that a given version of MediaWiki is
2248 * required to use it
2250 * @param mixed $version The version of MediaWiki needed to use the page
2252 public function versionRequired( $version ) {
2253 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2255 $this->addWikiMsg( 'versionrequiredtext', $version );
2256 $this->returnToMain();
2260 * Display an error page noting that a given permission bit is required.
2261 * @deprecated since 1.18, just throw the exception directly
2262 * @param string $permission key required
2263 * @throws PermissionsError
2265 public function permissionRequired( $permission ) {
2266 throw new PermissionsError( $permission );
2270 * Produce the stock "please login to use the wiki" page
2272 * @deprecated since 1.19; throw the exception directly
2274 public function loginToUse() {
2275 throw new PermissionsError( 'read' );
2279 * Format a list of error messages
2281 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2282 * @param string $action Action that was denied or null if unknown
2283 * @return string The wikitext error-messages, formatted into a list.
2285 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2286 if ( $action == null ) {
2287 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2289 $action_desc = $this->msg( "action-$action" )->plain();
2291 'permissionserrorstext-withaction',
2294 )->plain() . "\n\n";
2297 if ( count( $errors ) > 1 ) {
2298 $text .= '<ul class="permissions-errors">' . "\n";
2300 foreach ( $errors as $error ) {
2302 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2307 $text .= "<div class=\"permissions-errors\">\n" .
2308 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2316 * Display a page stating that the Wiki is in read-only mode,
2317 * and optionally show the source of the page that the user
2318 * was trying to edit. Should only be called (for this
2319 * purpose) after wfReadOnly() has returned true.
2321 * For historical reasons, this function is _also_ used to
2322 * show the error message when a user tries to edit a page
2323 * they are not allowed to edit. (Unless it's because they're
2324 * blocked, then we show blockedPage() instead.) In this
2325 * case, the second parameter should be set to true and a list
2326 * of reasons supplied as the third parameter.
2328 * @todo Needs to be split into multiple functions.
2330 * @param string $source Source code to show (or null).
2331 * @param bool $protected Is this a permissions error?
2332 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
2333 * @param string $action Action that was denied or null if unknown
2334 * @throws ReadOnlyError
2336 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2337 $this->setRobotPolicy( 'noindex,nofollow' );
2338 $this->setArticleRelated( false );
2340 // If no reason is given, just supply a default "I can't let you do
2341 // that, Dave" message. Should only occur if called by legacy code.
2342 if ( $protected && empty( $reasons ) ) {
2343 $reasons[] = array( 'badaccess-group0' );
2346 if ( !empty( $reasons ) ) {
2347 // Permissions error
2349 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2350 $this->addBacklinkSubtitle( $this->getTitle() );
2352 $this->setPageTitle( $this->msg( 'badaccess' ) );
2354 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2356 // Wiki is read only
2357 throw new ReadOnlyError
;
2360 // Show source, if supplied
2361 if ( is_string( $source ) ) {
2362 $this->addWikiMsg( 'viewsourcetext' );
2364 $pageLang = $this->getTitle()->getPageLanguage();
2366 'id' => 'wpTextbox1',
2367 'name' => 'wpTextbox1',
2368 'cols' => $this->getUser()->getOption( 'cols' ),
2369 'rows' => $this->getUser()->getOption( 'rows' ),
2370 'readonly' => 'readonly',
2371 'lang' => $pageLang->getHtmlCode(),
2372 'dir' => $pageLang->getDir(),
2374 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2376 // Show templates used by this article
2377 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2378 $this->addHTML( "<div class='templatesUsed'>
2384 # If the title doesn't exist, it's fairly pointless to print a return
2385 # link to it. After all, you just tried editing it and couldn't, so
2386 # what's there to do there?
2387 if ( $this->getTitle()->exists() ) {
2388 $this->returnToMain( null, $this->getTitle() );
2393 * Turn off regular page output and return an error response
2394 * for when rate limiting has triggered.
2396 public function rateLimited() {
2397 throw new ThrottledError
;
2401 * Show a warning about slave lag
2403 * If the lag is higher than $wgSlaveLagCritical seconds,
2404 * then the warning is a bit more obvious. If the lag is
2405 * lower than $wgSlaveLagWarning, then no warning is shown.
2407 * @param int $lag Slave lag
2409 public function showLagWarning( $lag ) {
2410 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2411 if ( $lag >= $wgSlaveLagWarning ) {
2412 $message = $lag < $wgSlaveLagCritical
2415 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2416 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2420 public function showFatalError( $message ) {
2421 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2423 $this->addHTML( $message );
2426 public function showUnexpectedValueError( $name, $val ) {
2427 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2430 public function showFileCopyError( $old, $new ) {
2431 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2434 public function showFileRenameError( $old, $new ) {
2435 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2438 public function showFileDeleteError( $name ) {
2439 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2442 public function showFileNotFoundError( $name ) {
2443 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2447 * Add a "return to" link pointing to a specified title
2449 * @param Title $title Title to link
2450 * @param array $query Query string parameters
2451 * @param string $text Text of the link (input is not escaped)
2452 * @param array $options Options array to pass to Linker
2454 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2455 $link = $this->msg( 'returnto' )->rawParams(
2456 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2457 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2461 * Add a "return to" link pointing to a specified title,
2462 * or the title indicated in the request, or else the main page
2464 * @param mixed $unused
2465 * @param Title|string $returnto Title or String to return to
2466 * @param string $returntoquery Query string for the return to link
2468 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2469 if ( $returnto == null ) {
2470 $returnto = $this->getRequest()->getText( 'returnto' );
2473 if ( $returntoquery == null ) {
2474 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2477 if ( $returnto === '' ) {
2478 $returnto = Title
::newMainPage();
2481 if ( is_object( $returnto ) ) {
2482 $titleObj = $returnto;
2484 $titleObj = Title
::newFromText( $returnto );
2486 if ( !is_object( $titleObj ) ) {
2487 $titleObj = Title
::newMainPage();
2490 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2494 * @param Skin $sk The given Skin
2495 * @param bool $includeStyle Unused
2496 * @return string The doctype, opening "<html>", and head element.
2498 public function headElement( Skin
$sk, $includeStyle = true ) {
2499 global $wgContLang, $wgMimeType;
2501 $userdir = $this->getLanguage()->getDir();
2502 $sitedir = $wgContLang->getDir();
2504 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2506 if ( $this->getHTMLTitle() == '' ) {
2507 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2510 $openHead = Html
::openElement( 'head' );
2512 # Don't bother with the newline if $head == ''
2513 $ret .= "$openHead\n";
2516 if ( !Html
::isXmlMimeType( $wgMimeType ) ) {
2517 // Add <meta charset="UTF-8">
2518 // This should be before <title> since it defines the charset used by
2519 // text including the text inside <title>.
2520 // The spec recommends defining XHTML5's charset using the XML declaration
2522 // Our XML declaration is output by Html::htmlHeader.
2523 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2524 // http://www.whatwg.org/html/semantics.html#charset
2525 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2528 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2531 $this->getHeadLinks() .
2533 $this->buildCssLinks() .
2534 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2535 $this->getHeadScripts() .
2537 $this->getHeadItems()
2540 $closeHead = Html
::closeElement( 'head' );
2542 $ret .= "$closeHead\n";
2545 $bodyClasses = array();
2546 $bodyClasses[] = 'mediawiki';
2548 # Classes for LTR/RTL directionality support
2549 $bodyClasses[] = $userdir;
2550 $bodyClasses[] = "sitedir-$sitedir";
2552 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2553 # A <body> class is probably not the best way to do this . . .
2554 $bodyClasses[] = 'capitalize-all-nouns';
2557 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2558 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2559 $bodyClasses[] = 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2561 $bodyAttrs = array();
2562 // While the implode() is not strictly needed, it's used for backwards compatibility
2563 // (this used to be built as a string and hooks likely still expect that).
2564 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2566 // Allow skins and extensions to add body attributes they need
2567 $sk->addToBodyAttributes( $this, $bodyAttrs );
2568 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2570 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2576 * Get a ResourceLoader object associated with this OutputPage
2578 * @return ResourceLoader
2580 public function getResourceLoader() {
2581 if ( is_null( $this->mResourceLoader
) ) {
2582 $this->mResourceLoader
= new ResourceLoader();
2584 return $this->mResourceLoader
;
2589 * @param array|string $modules One or more module names
2590 * @param string $only ResourceLoaderModule TYPE_ class constant
2591 * @param bool $useESI
2592 * @param array $extraQuery Array with extra query parameters to add to each request. array( param => value )
2593 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2594 * @return string The html "<script>", "<link>" and "<style>" tags
2596 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2597 global $wgResourceLoaderUseESI;
2599 $modules = (array)$modules;
2603 'states' => array(),
2606 if ( !count( $modules ) ) {
2611 if ( count( $modules ) > 1 ) {
2612 // Remove duplicate module requests
2613 $modules = array_unique( $modules );
2614 // Sort module names so requests are more uniform
2617 if ( ResourceLoader
::inDebugMode() ) {
2618 // Recursively call us for every item
2619 foreach ( $modules as $name ) {
2620 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2621 $links['html'] .= $link['html'];
2622 $links['states'] +
= $link['states'];
2628 if ( !is_null( $this->mTarget
) ) {
2629 $extraQuery['target'] = $this->mTarget
;
2632 // Create keyed-by-group list of module objects from modules list
2634 $resourceLoader = $this->getResourceLoader();
2635 foreach ( $modules as $name ) {
2636 $module = $resourceLoader->getModule( $name );
2637 # Check that we're allowed to include this module on this page
2639 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2640 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2641 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2642 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2643 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2648 $group = $module->getGroup();
2649 if ( !isset( $groups[$group] ) ) {
2650 $groups[$group] = array();
2652 $groups[$group][$name] = $module;
2655 foreach ( $groups as $group => $grpModules ) {
2656 // Special handling for user-specific groups
2658 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2659 $user = $this->getUser()->getName();
2662 // Create a fake request based on the one we are about to make so modules return
2663 // correct timestamp and emptiness data
2664 $query = ResourceLoader
::makeLoaderQuery(
2665 array(), // modules; not determined yet
2666 $this->getLanguage()->getCode(),
2667 $this->getSkin()->getSkinName(),
2669 null, // version; not determined yet
2670 ResourceLoader
::inDebugMode(),
2671 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2672 $this->isPrintable(),
2673 $this->getRequest()->getBool( 'handheld' ),
2676 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2678 // Extract modules that know they're empty
2679 foreach ( $grpModules as $key => $module ) {
2680 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2681 // If we're only getting the styles, we don't need to do anything for empty modules.
2682 if ( $module->isKnownEmpty( $context ) ) {
2683 unset( $grpModules[$key] );
2684 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2685 $links['states'][$key] = 'ready';
2690 // If there are no non-empty modules, skip this group
2691 if ( count( $grpModules ) === 0 ) {
2695 // Inline private modules. These can't be loaded through load.php for security
2696 // reasons, see bug 34907. Note that these modules should be loaded from
2697 // getHeadScripts() before the first loader call. Otherwise other modules can't
2698 // properly use them as dependencies (bug 30914)
2699 if ( $group === 'private' ) {
2700 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2701 $links['html'] .= Html
::inlineStyle(
2702 $resourceLoader->makeModuleResponse( $context, $grpModules )
2705 $links['html'] .= Html
::inlineScript(
2706 ResourceLoader
::makeLoaderConditionalScript(
2707 $resourceLoader->makeModuleResponse( $context, $grpModules )
2711 $links['html'] .= "\n";
2715 // Special handling for the user group; because users might change their stuff
2716 // on-wiki like user pages, or user preferences; we need to find the highest
2717 // timestamp of these user-changeable modules so we can ensure cache misses on change
2718 // This should NOT be done for the site group (bug 27564) because anons get that too
2719 // and we shouldn't be putting timestamps in Squid-cached HTML
2721 if ( $group === 'user' ) {
2722 // Get the maximum timestamp
2724 foreach ( $grpModules as $module ) {
2725 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2727 // Add a version parameter so cache will break when things change
2728 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2731 $url = ResourceLoader
::makeLoaderURL(
2732 array_keys( $grpModules ),
2733 $this->getLanguage()->getCode(),
2734 $this->getSkin()->getSkinName(),
2737 ResourceLoader
::inDebugMode(),
2738 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2739 $this->isPrintable(),
2740 $this->getRequest()->getBool( 'handheld' ),
2743 if ( $useESI && $wgResourceLoaderUseESI ) {
2744 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2745 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2746 $link = Html
::inlineStyle( $esi );
2748 $link = Html
::inlineScript( $esi );
2751 // Automatically select style/script elements
2752 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2753 $link = Html
::linkedStyle( $url );
2754 } elseif ( $loadCall ) {
2755 $link = Html
::inlineScript(
2756 ResourceLoader
::makeLoaderConditionalScript(
2757 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2761 $link = Html
::linkedScript( $url );
2763 // For modules requested directly in the html via <link> or <script>,
2764 // tell mw.loader they are being loading to prevent duplicate requests.
2765 foreach ( $grpModules as $key => $module ) {
2766 // Don't output state=loading for the startup module..
2767 if ( $key !== 'startup' ) {
2768 $links['states'][$key] = 'loading';
2774 if ( $group == 'noscript' ) {
2775 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2777 $links['html'] .= $link . "\n";
2785 * Build html output from an array of links from makeResourceLoaderLink.
2786 * @param array $links
2787 * @return string HTML
2789 protected static function getHtmlFromLoaderLinks( Array $links ) {
2792 foreach ( $links as $link ) {
2793 if ( !is_array( $link ) ) {
2796 $html .= $link['html'];
2797 $states +
= $link['states'];
2801 if ( count( $states ) ) {
2802 $html = Html
::inlineScript(
2803 ResourceLoader
::makeLoaderConditionalScript(
2804 ResourceLoader
::makeLoaderStateScript( $states )
2813 * JS stuff to put in the "<head>". This is the startup module, config
2814 * vars and modules marked with position 'top'
2816 * @return string HTML fragment
2818 function getHeadScripts() {
2819 global $wgResourceLoaderExperimentalAsyncLoading;
2821 // Startup - this will immediately load jquery and mediawiki modules
2823 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2825 // Load config before anything else
2826 $links[] = Html
::inlineScript(
2827 ResourceLoader
::makeLoaderConditionalScript(
2828 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2832 // Load embeddable private modules before any loader links
2833 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2834 // in mw.loader.implement() calls and deferred until mw.user is available
2835 $embedScripts = array( 'user.options', 'user.tokens' );
2836 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2838 // Scripts and messages "only" requests marked for top inclusion
2839 // Messages should go first
2840 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule
::TYPE_MESSAGES
);
2841 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule
::TYPE_SCRIPTS
);
2843 // Modules requests - let the client calculate dependencies and batch requests as it likes
2844 // Only load modules that have marked themselves for loading at the top
2845 $modules = $this->getModules( true, 'top' );
2847 $links[] = Html
::inlineScript(
2848 ResourceLoader
::makeLoaderConditionalScript(
2849 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2854 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2855 $links[] = $this->getScriptsForBottomQueue( true );
2858 return self
::getHtmlFromLoaderLinks( $links );
2862 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2863 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2864 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2865 * user preferences, site JS and user JS.
2867 * @param bool $inHead If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2870 function getScriptsForBottomQueue( $inHead ) {
2871 global $wgUseSiteJs, $wgAllowUserJs;
2873 // Scripts and messages "only" requests marked for bottom inclusion
2874 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2875 // Messages should go first
2877 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2878 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2879 /* $loadCall = */ $inHead
2881 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2882 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2883 /* $loadCall = */ $inHead
2886 // Modules requests - let the client calculate dependencies and batch requests as it likes
2887 // Only load modules that have marked themselves for loading at the bottom
2888 $modules = $this->getModules( true, 'bottom' );
2890 $links[] = Html
::inlineScript(
2891 ResourceLoader
::makeLoaderConditionalScript(
2892 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2898 $links[] = "\n" . $this->mScripts
;
2900 // Add site JS if enabled
2901 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2902 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2905 // Add user JS if enabled
2906 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() && $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2907 # XXX: additional security check/prompt?
2908 // We're on a preview of a JS subpage
2909 // Exclude this page from the user module in case it's in there (bug 26283)
2910 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2911 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2913 // Load the previewed JS
2914 $links[] = Html
::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2916 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2917 // asynchronously and may arrive *after* the inline script here. So the previewed code
2918 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2920 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2921 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
2922 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2926 // Group JS is only enabled if site JS is enabled.
2927 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
2928 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2931 return self
::getHtmlFromLoaderLinks( $links );
2935 * JS stuff to put at the bottom of the "<body>"
2938 function getBottomScripts() {
2939 global $wgResourceLoaderExperimentalAsyncLoading;
2941 // Optimise jQuery ready event cross-browser.
2942 // This also enforces $.isReady to be true at </body> which fixes the
2943 // mw.loader bug in Firefox with using document.write between </body>
2944 // and the DOMContentReady event (bug 47457).
2945 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
2947 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2948 $html .= $this->getScriptsForBottomQueue( false );
2955 * Get the javascript config vars to include on this page
2957 * @return array Array of javascript config vars
2960 public function getJsConfigVars() {
2961 return $this->mJsConfigVars
;
2965 * Add one or more variables to be set in mw.config in JavaScript
2967 * @param string|array $keys Key or array of key/value pairs
2968 * @param mixed $value [optional] Value of the configuration variable
2970 public function addJsConfigVars( $keys, $value = null ) {
2971 if ( is_array( $keys ) ) {
2972 foreach ( $keys as $key => $value ) {
2973 $this->mJsConfigVars
[$key] = $value;
2978 $this->mJsConfigVars
[$keys] = $value;
2982 * Get an array containing the variables to be set in mw.config in JavaScript.
2984 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2985 * This is only public until that function is removed. You have been warned.
2987 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2988 * - in other words, page-independent/site-wide variables (without state).
2989 * You will only be adding bloat to the html page and causing page caches to
2990 * have to be purged on configuration changes.
2993 public function getJSVars() {
2998 $canonicalSpecialPageName = false; # bug 21115
3000 $title = $this->getTitle();
3001 $ns = $title->getNamespace();
3002 $canonicalNamespace = MWNamespace
::exists( $ns ) ? MWNamespace
::getCanonicalName( $ns ) : $title->getNsText();
3004 $sk = $this->getSkin();
3005 // Get the relevant title so that AJAX features can use the correct page name
3006 // when making API requests from certain special pages (bug 34972).
3007 $relevantTitle = $sk->getRelevantTitle();
3008 $relevantUser = $sk->getRelevantUser();
3010 if ( $ns == NS_SPECIAL
) {
3011 list( $canonicalSpecialPageName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3012 } elseif ( $this->canUseWikiPage() ) {
3013 $wikiPage = $this->getWikiPage();
3014 $curRevisionId = $wikiPage->getLatest();
3015 $articleId = $wikiPage->getId();
3018 $lang = $title->getPageLanguage();
3020 // Pre-process information
3021 $separatorTransTable = $lang->separatorTransformTable();
3022 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3023 $compactSeparatorTransTable = array(
3024 implode( "\t", array_keys( $separatorTransTable ) ),
3025 implode( "\t", $separatorTransTable ),
3027 $digitTransTable = $lang->digitTransformTable();
3028 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3029 $compactDigitTransTable = array(
3030 implode( "\t", array_keys( $digitTransTable ) ),
3031 implode( "\t", $digitTransTable ),
3034 $user = $this->getUser();
3037 'wgCanonicalNamespace' => $canonicalNamespace,
3038 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3039 'wgNamespaceNumber' => $title->getNamespace(),
3040 'wgPageName' => $title->getPrefixedDBkey(),
3041 'wgTitle' => $title->getText(),
3042 'wgCurRevisionId' => $curRevisionId,
3043 'wgRevisionId' => (int)$this->getRevisionId(),
3044 'wgArticleId' => $articleId,
3045 'wgIsArticle' => $this->isArticle(),
3046 'wgIsRedirect' => $title->isRedirect(),
3047 'wgAction' => Action
::getActionName( $this->getContext() ),
3048 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3049 'wgUserGroups' => $user->getEffectiveGroups(),
3050 'wgCategories' => $this->getCategories(),
3051 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3052 'wgPageContentLanguage' => $lang->getCode(),
3053 'wgPageContentModel' => $title->getContentModel(),
3054 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3055 'wgDigitTransformTable' => $compactDigitTransTable,
3056 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3057 'wgMonthNames' => $lang->getMonthNamesArray(),
3058 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3059 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3061 if ( $user->isLoggedIn() ) {
3062 $vars['wgUserId'] = $user->getId();
3063 $vars['wgUserEditCount'] = $user->getEditCount();
3064 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3065 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3066 // Get the revision ID of the oldest new message on the user's talk
3067 // page. This can be used for constructing new message alerts on
3069 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3071 if ( $wgContLang->hasVariants() ) {
3072 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3074 // Same test as SkinTemplate
3075 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user ) && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3076 foreach ( $title->getRestrictionTypes() as $type ) {
3077 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3079 if ( $title->isMainPage() ) {
3080 $vars['wgIsMainPage'] = true;
3082 if ( $this->mRedirectedFrom
) {
3083 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3085 if ( $relevantUser ) {
3086 $vars['wgRelevantUserName'] = $relevantUser->getName();
3089 // Allow extensions to add their custom variables to the mw.config map.
3090 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3091 // page-dependant but site-wide (without state).
3092 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3093 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3095 // Merge in variables from addJsConfigVars last
3096 return array_merge( $vars, $this->getJsConfigVars() );
3100 * To make it harder for someone to slip a user a fake
3101 * user-JavaScript or user-CSS preview, a random token
3102 * is associated with the login session. If it's not
3103 * passed back with the preview request, we won't render
3108 public function userCanPreview() {
3109 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3110 ||
!$this->getRequest()->wasPosted()
3111 ||
!$this->getUser()->matchEditToken(
3112 $this->getRequest()->getVal( 'wpEditToken' ) )
3116 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3120 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3124 * @return array in format "link name or number => 'link html'".
3126 public function getHeadLinksArray() {
3127 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3128 $wgSitename, $wgVersion,
3129 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3130 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3131 $wgRightsPage, $wgRightsUrl;
3135 $canonicalUrl = $this->mCanonicalUrl
;
3137 $tags['meta-generator'] = Html
::element( 'meta', array(
3138 'name' => 'generator',
3139 'content' => "MediaWiki $wgVersion",
3142 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3143 if ( $p !== 'index,follow' ) {
3144 // http://www.robotstxt.org/wc/meta-user.html
3145 // Only show if it's different from the default robots policy
3146 $tags['meta-robots'] = Html
::element( 'meta', array(
3152 foreach ( $this->mMetatags
as $tag ) {
3153 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3155 $tag[0] = substr( $tag[0], 5 );
3159 $tagName = "meta-{$tag[0]}";
3160 if ( isset( $tags[$tagName] ) ) {
3161 $tagName .= $tag[1];
3163 $tags[$tagName] = Html
::element( 'meta',
3166 'content' => $tag[1]
3171 foreach ( $this->mLinktags
as $tag ) {
3172 $tags[] = Html
::element( 'link', $tag );
3175 # Universal edit button
3176 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3177 $user = $this->getUser();
3178 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3179 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3180 // Original UniversalEditButton
3181 $msg = $this->msg( 'edit' )->text();
3182 $tags['universal-edit-button'] = Html
::element( 'link', array(
3183 'rel' => 'alternate',
3184 'type' => 'application/x-wiki',
3186 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3188 // Alternate edit link
3189 $tags['alternative-edit'] = Html
::element( 'link', array(
3192 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3197 # Generally the order of the favicon and apple-touch-icon links
3198 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3199 # uses whichever one appears later in the HTML source. Make sure
3200 # apple-touch-icon is specified first to avoid this.
3201 if ( $wgAppleTouchIcon !== false ) {
3202 $tags['apple-touch-icon'] = Html
::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3205 if ( $wgFavicon !== false ) {
3206 $tags['favicon'] = Html
::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3209 # OpenSearch description link
3210 $tags['opensearch'] = Html
::element( 'link', array(
3212 'type' => 'application/opensearchdescription+xml',
3213 'href' => wfScript( 'opensearch_desc' ),
3214 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3217 if ( $wgEnableAPI ) {
3218 # Real Simple Discovery link, provides auto-discovery information
3219 # for the MediaWiki API (and potentially additional custom API
3220 # support such as WordPress or Twitter-compatible APIs for a
3221 # blogging extension, etc)
3222 $tags['rsd'] = Html
::element( 'link', array(
3224 'type' => 'application/rsd+xml',
3225 // Output a protocol-relative URL here if $wgServer is protocol-relative
3226 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3227 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE
),
3232 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3233 $lang = $this->getTitle()->getPageLanguage();
3234 if ( $lang->hasVariants() ) {
3236 $urlvar = $lang->getURLVariant();
3239 $variants = $lang->getVariants();
3240 foreach ( $variants as $_v ) {
3241 $tags["variant-$_v"] = Html
::element( 'link', array(
3242 'rel' => 'alternate',
3243 'hreflang' => wfBCP47( $_v ),
3244 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3248 $canonicalUrl = $this->getTitle()->getLocalURL();
3255 if ( $wgRightsPage ) {
3256 $copy = Title
::newFromText( $wgRightsPage );
3259 $copyright = $copy->getLocalURL();
3263 if ( !$copyright && $wgRightsUrl ) {
3264 $copyright = $wgRightsUrl;
3268 $tags['copyright'] = Html
::element( 'link', array(
3269 'rel' => 'copyright',
3270 'href' => $copyright )
3276 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3277 # Use the page name for the title. In principle, this could
3278 # lead to issues with having the same name for different feeds
3279 # corresponding to the same page, but we can't avoid that at
3282 $tags[] = $this->feedLink(
3285 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3286 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3290 # Recent changes feed should appear on every page (except recentchanges,
3291 # that would be redundant). Put it after the per-page feed to avoid
3292 # changing existing behavior. It's still available, probably via a
3293 # menu in your browser. Some sites might have a different feed they'd
3294 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3295 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3296 # If so, use it instead.
3297 if ( $wgOverrideSiteFeed ) {
3298 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3299 // Note, this->feedLink escapes the url.
3300 $tags[] = $this->feedLink(
3303 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3306 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3307 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3308 foreach ( $wgAdvertisedFeedTypes as $format ) {
3309 $tags[] = $this->feedLink(
3311 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3312 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3319 global $wgEnableCanonicalServerLink;
3320 if ( $wgEnableCanonicalServerLink ) {
3321 if ( $canonicalUrl !== false ) {
3322 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3324 $reqUrl = $this->getRequest()->getRequestURL();
3325 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3328 if ( $canonicalUrl !== false ) {
3329 $tags[] = Html
::element( 'link', array(
3330 'rel' => 'canonical',
3331 'href' => $canonicalUrl
3339 * @return string HTML tag links to be put in the header.
3341 public function getHeadLinks() {
3342 return implode( "\n", $this->getHeadLinksArray() );
3346 * Generate a "<link rel/>" for a feed.
3348 * @param string $type Feed type
3349 * @param string $url URL to the feed
3350 * @param string $text Value of the "title" attribute
3351 * @return string HTML fragment
3353 private function feedLink( $type, $url, $text ) {
3354 return Html
::element( 'link', array(
3355 'rel' => 'alternate',
3356 'type' => "application/$type+xml",
3363 * Add a local or specified stylesheet, with the given media options.
3364 * Meant primarily for internal use...
3366 * @param string $style URL to the file
3367 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3368 * @param string $condition for IE conditional comments, specifying an IE version
3369 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3371 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3373 // Even though we expect the media type to be lowercase, but here we
3374 // force it to lowercase to be safe.
3376 $options['media'] = $media;
3379 $options['condition'] = $condition;
3382 $options['dir'] = $dir;
3384 $this->styles
[$style] = $options;
3388 * Adds inline CSS styles
3389 * @param mixed $style_css Inline CSS
3390 * @param string $flip Set to 'flip' to flip the CSS if needed
3392 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3393 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3394 # If wanted, and the interface is right-to-left, flip the CSS
3395 $style_css = CSSJanus
::transform( $style_css, true, false );
3397 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3401 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3402 * These will be applied to various media & IE conditionals.
3406 public function buildCssLinks() {
3407 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3409 $this->getSkin()->setupSkinUserCss( $this );
3411 // Add ResourceLoader styles
3412 // Split the styles into these groups
3413 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3415 $otherTags = ''; // Tags to append after the normal <link> tags
3416 $resourceLoader = $this->getResourceLoader();
3418 $moduleStyles = $this->getModuleStyles();
3420 // Per-site custom styles
3421 $moduleStyles[] = 'site';
3422 $moduleStyles[] = 'noscript';
3423 $moduleStyles[] = 'user.groups';
3425 // Per-user custom styles
3426 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3427 // We're on a preview of a CSS subpage
3428 // Exclude this page from the user module in case it's in there (bug 26283)
3429 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3430 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3432 $otherTags .= $link['html'];
3434 // Load the previewed CSS
3435 // If needed, Janus it first. This is user-supplied CSS, so it's
3436 // assumed to be right for the content language directionality.
3437 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3438 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3439 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3441 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3443 // Load the user styles normally
3444 $moduleStyles[] = 'user';
3447 // Per-user preference styles
3448 $moduleStyles[] = 'user.cssprefs';
3450 foreach ( $moduleStyles as $name ) {
3451 $module = $resourceLoader->getModule( $name );
3455 $group = $module->getGroup();
3456 // Modules in groups different than the ones listed on top (see $styles assignment)
3457 // will be placed in the "other" group
3458 $styles[ isset( $styles[$group] ) ?
$group : 'other' ][] = $name;
3461 // We want site, private and user styles to override dynamically added styles from modules, but we want
3462 // dynamically added styles to override statically added styles from other modules. So the order
3463 // has to be other, dynamic, site, private, user
3464 // Add statically added styles for other modules
3465 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3466 // Add normal styles added through addStyle()/addInlineStyle() here
3467 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3468 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3469 // We use a <meta> tag with a made-up name for this because that's valid HTML
3470 $links[] = Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3472 // Add site, private and user styles
3473 // 'private' at present only contains user.options, so put that before 'user'
3474 // Any future private modules will likely have a similar user-specific character
3475 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3476 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3477 ResourceLoaderModule
::TYPE_STYLES
3481 // Add stuff in $otherTags (previewed user CSS if applicable)
3482 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3488 public function buildCssLinksArray() {
3491 // Add any extension CSS
3492 foreach ( $this->mExtStyles
as $url ) {
3493 $this->addStyle( $url );
3495 $this->mExtStyles
= array();
3497 foreach ( $this->styles
as $file => $options ) {
3498 $link = $this->styleLink( $file, $options );
3500 $links[$file] = $link;
3507 * Generate \<link\> tags for stylesheets
3509 * @param string $style URL to the file
3510 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3511 * @return string HTML fragment
3513 protected function styleLink( $style, $options ) {
3514 if ( isset( $options['dir'] ) ) {
3515 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3520 if ( isset( $options['media'] ) ) {
3521 $media = self
::transformCssMedia( $options['media'] );
3522 if ( is_null( $media ) ) {
3529 if ( substr( $style, 0, 1 ) == '/' ||
3530 substr( $style, 0, 5 ) == 'http:' ||
3531 substr( $style, 0, 6 ) == 'https:' ) {
3534 global $wgStylePath, $wgStyleVersion;
3535 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3538 $link = Html
::linkedStyle( $url, $media );
3540 if ( isset( $options['condition'] ) ) {
3541 $condition = htmlspecialchars( $options['condition'] );
3542 $link = "<!--[if $condition]>$link<![endif]-->";
3548 * Transform "media" attribute based on request parameters
3550 * @param string $media Current value of the "media" attribute
3551 * @return string Modified value of the "media" attribute, or null to skip
3554 public static function transformCssMedia( $media ) {
3557 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3558 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3560 // Switch in on-screen display for media testing
3562 'printable' => 'print',
3563 'handheld' => 'handheld',
3565 foreach ( $switches as $switch => $targetMedia ) {
3566 if ( $wgRequest->getBool( $switch ) ) {
3567 if ( $media == $targetMedia ) {
3569 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3570 // This regex will not attempt to understand a comma-separated media_query_list
3572 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3573 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3575 // If it's a print request, we never want any kind of screen stylesheets
3576 // If it's a handheld request (currently the only other choice with a switch),
3577 // we don't want simple 'screen' but we might want screen queries that
3578 // have a max-width or something, so we'll pass all others on and let the
3579 // client do the query.
3580 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3591 * Add a wikitext-formatted message to the output.
3592 * This is equivalent to:
3594 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3596 public function addWikiMsg( /*...*/ ) {
3597 $args = func_get_args();
3598 $name = array_shift( $args );
3599 $this->addWikiMsgArray( $name, $args );
3603 * Add a wikitext-formatted message to the output.
3604 * Like addWikiMsg() except the parameters are taken as an array
3605 * instead of a variable argument list.
3607 * @param string $name
3608 * @param array $args
3610 public function addWikiMsgArray( $name, $args ) {
3611 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3615 * This function takes a number of message/argument specifications, wraps them in
3616 * some overall structure, and then parses the result and adds it to the output.
3618 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3619 * on. The subsequent arguments may either be strings, in which case they are the
3620 * message names, or arrays, in which case the first element is the message name,
3621 * and subsequent elements are the parameters to that message.
3623 * Don't use this for messages that are not in users interface language.
3627 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3631 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3633 * The newline after opening div is needed in some wikitext. See bug 19226.
3635 * @param string $wrap
3637 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3638 $msgSpecs = func_get_args();
3639 array_shift( $msgSpecs );
3640 $msgSpecs = array_values( $msgSpecs );
3642 foreach ( $msgSpecs as $n => $spec ) {
3643 if ( is_array( $spec ) ) {
3645 $name = array_shift( $args );
3646 if ( isset( $args['options'] ) ) {
3647 unset( $args['options'] );
3649 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3657 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3659 $this->addWikiText( $s );
3663 * Include jQuery core. Use this to avoid loading it multiple times
3664 * before we get a usable script loader.
3666 * @param array $modules List of jQuery modules which should be loaded
3667 * @return array The list of modules which were not loaded.
3669 * @deprecated since 1.17
3671 public function includeJQuery( $modules = array() ) {
3676 * Enables/disables TOC, doesn't override __NOTOC__
3680 public function enableTOC( $flag = true ) {
3681 $this->mEnableTOC
= $flag;
3688 public function isTOCEnabled() {
3689 return $this->mEnableTOC
;
3693 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3697 public function enableSectionEditLinks( $flag = true ) {
3698 $this->mEnableSectionEditLinks
= $flag;
3705 public function sectionEditLinksEnabled() {
3706 return $this->mEnableSectionEditLinks
;