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 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @ var string mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
125 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
126 private $mLanguageLinks = array();
129 * Used for JavaScript (pre resource loader)
130 * @todo We should split JS / CSS.
131 * mScripts content is inserted as is in "<head>" by Skin. This might
132 * contain either a link to a stylesheet or inline CSS.
134 private $mScripts = '';
136 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
137 protected $mInlineStyles = '';
140 private $mLinkColours;
143 * @var string Used by skin template.
144 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
146 public $mPageLinkTitle = '';
148 /** @var array Array of elements in "<head>". Parser might add its own headers! */
149 protected $mHeadItems = array();
151 // @todo FIXME: Next 5 variables probably come from the resource loader
154 protected $mModules = array();
157 protected $mModuleScripts = array();
160 protected $mModuleStyles = array();
163 protected $mModuleMessages = array();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
200 private $mContainsOldMagic = 0;
203 protected $mContainsNewMagic = 0;
206 * lazy initialised, use parserOptions()
209 protected $mParserOptions = null;
212 * Handles the Atom / RSS links.
213 * We probably only support Atom in 2011.
214 * @see $wgAdvertisedFeedTypes
216 private $mFeedLinks = array();
218 // Gwicke work on squid caching? Roughly from 2003.
219 protected $mEnableClientCache = true;
221 /** @var bool Flag if output should only contain the body of the article. */
222 private $mArticleBodyOnly = false;
225 protected $mNewSectionLink = false;
228 protected $mHideNewSectionLink = false;
231 * @var bool Comes from the parser. This was probably made to load CSS/JS
232 * only if we had "<gallery>". Used directly in CategoryPage.php.
233 * Looks like resource loader can replace this.
235 public $mNoGallery = false;
238 private $mPageTitleActionText = '';
241 private $mParseWarnings = array();
243 /** @var int Cache stuff. Looks like mEnableClientCache */
244 protected $mSquidMaxage = 0;
250 protected $mPreventClickjacking = true;
252 /** @var int To include the variable {{REVISIONID}} */
253 private $mRevisionId = null;
256 private $mRevisionTimestamp = null;
259 protected $mFileVersion = null;
262 * @var array An array of stylesheet filenames (relative from skins path),
263 * with options for CSS media, IE conditions, and RTL/LTR direction.
264 * For internal use; add settings in the skin via $this->addStyle()
266 * Style again! This seems like a code duplication since we already have
267 * mStyles. This is what makes Open Source amazing.
269 protected $styles = array();
272 * Whether jQuery is already handled.
274 protected $mJQueryDone = false;
276 private $mIndexPolicy = 'index';
277 private $mFollowPolicy = 'follow';
278 private $mVaryHeader = array(
279 'Accept-Encoding' => array( 'list-contains=gzip' ),
283 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
288 private $mRedirectedFrom = null;
291 * Additional key => value data
293 private $mProperties = array();
296 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
298 private $mTarget = null;
301 * @var bool Whether parser output should contain table of contents
303 private $mEnableTOC = true;
306 * @var bool Whether parser output should contain section edit links
308 private $mEnableSectionEditLinks = true;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
315 function __construct( IContextSource
$context = null ) {
316 if ( $context === null ) {
317 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
318 wfDeprecated( __METHOD__
, '1.18' );
320 $this->setContext( $context );
325 * Redirect to $url rather than displaying the normal page
327 * @param string $url URL
328 * @param string $responsecode HTTP status code
330 public function redirect( $url, $responsecode = '302' ) {
331 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
332 $this->mRedirect
= str_replace( "\n", '', $url );
333 $this->mRedirectCode
= $responsecode;
337 * Get the URL to redirect to, or an empty string if not redirect URL set
341 public function getRedirect() {
342 return $this->mRedirect
;
346 * Set the HTTP status code to send with the output.
348 * @param int $statusCode
350 public function setStatusCode( $statusCode ) {
351 $this->mStatusCode
= $statusCode;
355 * Add a new "<meta>" tag
356 * To add an http-equiv meta tag, precede the name with "http:"
358 * @param string $name tag name
359 * @param string $val tag value
361 function addMeta( $name, $val ) {
362 array_push( $this->mMetatags
, array( $name, $val ) );
366 * Add a new \<link\> tag to the page header.
368 * Note: use setCanonicalUrl() for rel=canonical.
370 * @param array $linkarr associative array of attributes.
372 function addLink( $linkarr ) {
373 array_push( $this->mLinktags
, $linkarr );
377 * Add a new \<link\> with "rel" attribute set to "meta"
379 * @param array $linkarr associative array mapping attribute names to their
380 * values, both keys and values will be escaped, and the
381 * "rel" attribute will be automatically added
383 function addMetadataLink( $linkarr ) {
384 $linkarr['rel'] = $this->getMetadataAttribute();
385 $this->addLink( $linkarr );
389 * Set the URL to be used for the <link rel=canonical>. This should be used
390 * in preference to addLink(), to avoid duplicate link tags.
392 function setCanonicalUrl( $url ) {
393 $this->mCanonicalUrl
= $url;
397 * Get the value of the "rel" attribute for metadata links
401 public function getMetadataAttribute() {
402 # note: buggy CC software only reads first "meta" link
403 static $haveMeta = false;
405 return 'alternate meta';
413 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
415 * @param string $script raw HTML
417 function addScript( $script ) {
418 $this->mScripts
.= $script . "\n";
422 * Register and add a stylesheet from an extension directory.
424 * @param string $url path to sheet. Provide either a full url (beginning
425 * with 'http', etc) or a relative path from the document root
426 * (beginning with '/'). Otherwise it behaves identically to
427 * addStyle() and draws from the /skins folder.
429 public function addExtensionStyle( $url ) {
430 array_push( $this->mExtStyles
, $url );
434 * Get all styles added by extensions
438 function getExtStyle() {
439 return $this->mExtStyles
;
443 * Add a JavaScript file out of skins/common, or a given relative path.
445 * @param string $file filename in skins/common or complete on-server path
447 * @param string $version style version of the file. Defaults to $wgStyleVersion
449 public function addScriptFile( $file, $version = null ) {
450 global $wgStylePath, $wgStyleVersion;
451 // See if $file parameter is an absolute URL or begins with a slash
452 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
455 $path = "{$wgStylePath}/common/{$file}";
457 if ( is_null( $version ) ) {
458 $version = $wgStyleVersion;
460 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
464 * Add a self-contained script tag with the given contents
466 * @param string $script JavaScript text, no "<script>" tags
468 public function addInlineScript( $script ) {
469 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
473 * Get all registered JS and CSS tags for the header.
476 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
478 function getScript() {
479 wfDeprecated( __METHOD__
, '1.24' );
480 return $this->mScripts
. $this->getHeadItems();
484 * Filter an array of modules to remove insufficiently trustworthy members, and modules
485 * which are no longer registered (eg a page is cached before an extension is disabled)
486 * @param array $modules
487 * @param string|null $position if not null, only return modules with this position
488 * @param string $type
491 protected function filterModules( $modules, $position = null,
492 $type = ResourceLoaderModule
::TYPE_COMBINED
494 $resourceLoader = $this->getResourceLoader();
495 $filteredModules = array();
496 foreach ( $modules as $val ) {
497 $module = $resourceLoader->getModule( $val );
498 if ( $module instanceof ResourceLoaderModule
499 && $module->getOrigin() <= $this->getAllowedModules( $type )
500 && ( is_null( $position ) ||
$module->getPosition() == $position )
501 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
503 $filteredModules[] = $val;
506 return $filteredModules;
510 * Get the list of modules to include on this page
512 * @param bool $filter Whether to filter out insufficiently trustworthy modules
513 * @param string|null $position If not null, only return modules with this position
514 * @param string $param
515 * @return array Array of module names
517 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
518 $modules = array_values( array_unique( $this->$param ) );
520 ?
$this->filterModules( $modules, $position )
525 * Add one or more modules recognized by the resource loader. Modules added
526 * through this function will be loaded by the resource loader when the
529 * @param string|array $modules Module name (string) or array of module names
531 public function addModules( $modules ) {
532 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
536 * Get the list of module JS to include on this page
538 * @param bool $filter
539 * @param string|null $position
541 * @return array Array of module names
543 public function getModuleScripts( $filter = false, $position = null ) {
544 return $this->getModules( $filter, $position, 'mModuleScripts' );
548 * Add only JS of one or more modules recognized by the resource loader. Module
549 * scripts added through this function will be loaded by the resource loader when
552 * @param string|array $modules Module name (string) or array of module names
554 public function addModuleScripts( $modules ) {
555 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
559 * Get the list of module CSS to include on this page
561 * @param bool $filter
562 * @param string|null $position
564 * @return array Array of module names
566 public function getModuleStyles( $filter = false, $position = null ) {
567 return $this->getModules( $filter, $position, 'mModuleStyles' );
571 * Add only CSS of one or more modules recognized by the resource loader.
573 * Module styles added through this function will be added using standard link CSS
574 * tags, rather than as a combined Javascript and CSS package. Thus, they will
575 * load when JavaScript is disabled (unless CSS also happens to be disabled).
577 * @param string|array $modules Module name (string) or array of module names
579 public function addModuleStyles( $modules ) {
580 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
584 * Get the list of module messages to include on this page
586 * @param bool $filter
587 * @param string|null $position
589 * @return array Array of module names
591 public function getModuleMessages( $filter = false, $position = null ) {
592 return $this->getModules( $filter, $position, 'mModuleMessages' );
596 * Add only messages of one or more modules recognized by the resource loader.
597 * Module messages added through this function will be loaded by the resource
598 * loader when the page loads.
600 * @param string|array $modules Module name (string) or array of module names
602 public function addModuleMessages( $modules ) {
603 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
607 * @return null|string ResourceLoader target
609 public function getTarget() {
610 return $this->mTarget
;
614 * Sets ResourceLoader target for load.php links. If null, will be omitted
616 * @param string|null $target
618 public function setTarget( $target ) {
619 $this->mTarget
= $target;
623 * Get an array of head items
627 function getHeadItemsArray() {
628 return $this->mHeadItems
;
632 * Get all header items in a string
635 * @deprecated since 1.24 Use OutputPage::headElement or
636 * if absolutely necessary use OutputPage::getHeadItemsArray
638 function getHeadItems() {
639 wfDeprecated( __METHOD__
, '1.24' );
641 foreach ( $this->mHeadItems
as $item ) {
648 * Add or replace an header item to the output
650 * @param string $name item name
651 * @param string $value raw HTML
653 public function addHeadItem( $name, $value ) {
654 $this->mHeadItems
[$name] = $value;
658 * Check if the header item $name is already set
660 * @param string $name Item name
663 public function hasHeadItem( $name ) {
664 return isset( $this->mHeadItems
[$name] );
668 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
670 * @param string $tag value of "ETag" header
672 function setETag( $tag ) {
677 * Set whether the output should only contain the body of the article,
678 * without any skin, sidebar, etc.
679 * Used e.g. when calling with "action=render".
681 * @param bool $only Whether to output only the body of the article
683 public function setArticleBodyOnly( $only ) {
684 $this->mArticleBodyOnly
= $only;
688 * Return whether the output will contain only the body of the article
692 public function getArticleBodyOnly() {
693 return $this->mArticleBodyOnly
;
697 * Set an additional output property
700 * @param string $name
701 * @param mixed $value
703 public function setProperty( $name, $value ) {
704 $this->mProperties
[$name] = $value;
708 * Get an additional output property
711 * @param string $name
712 * @return mixed Property value or null if not found
714 public function getProperty( $name ) {
715 if ( isset( $this->mProperties
[$name] ) ) {
716 return $this->mProperties
[$name];
723 * checkLastModified tells the client to use the client-cached page if
724 * possible. If successful, the OutputPage is disabled so that
725 * any future call to OutputPage->output() have no effect.
727 * Side effect: sets mLastModified for Last-Modified header
729 * @param string $timestamp
731 * @return bool True if cache-ok headers was sent.
733 public function checkLastModified( $timestamp ) {
734 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
736 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
737 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
740 if ( !$wgCachePages ) {
741 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
745 $timestamp = wfTimestamp( TS_MW
, $timestamp );
746 $modifiedTimes = array(
747 'page' => $timestamp,
748 'user' => $this->getUser()->getTouched(),
749 'epoch' => $wgCacheEpoch
752 // bug 44570: the core page itself may not change, but resources might
753 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $wgSquidMaxage );
755 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
757 $maxModified = max( $modifiedTimes );
758 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
760 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
761 if ( $clientHeader === false ) {
762 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
766 # IE sends sizes after the date like this:
767 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
768 # this breaks strtotime().
769 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
771 wfSuppressWarnings(); // E_STRICT system time bitching
772 $clientHeaderTime = strtotime( $clientHeader );
774 if ( !$clientHeaderTime ) {
776 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
779 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
783 foreach ( $modifiedTimes as $name => $value ) {
784 if ( $info !== '' ) {
787 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
790 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
791 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
792 wfDebug( __METHOD__
. ": effective Last-Modified: " .
793 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
794 if ( $clientHeaderTime < $maxModified ) {
795 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
800 # Give a 304 response code and disable body output
801 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
802 ini_set( 'zlib.output_compression', 0 );
803 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
804 $this->sendCacheControl();
807 // Don't output a compressed blob when using ob_gzhandler;
808 // it's technically against HTTP spec and seems to confuse
809 // Firefox when the response gets split over two packets.
810 wfClearOutputBuffers();
816 * Override the last modified timestamp
818 * @param string $timestamp new timestamp, in a format readable by
821 public function setLastModified( $timestamp ) {
822 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
826 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
828 * @param string $policy the literal string to output as the contents of
829 * the meta tag. Will be parsed according to the spec and output in
833 public function setRobotPolicy( $policy ) {
834 $policy = Article
::formatRobotPolicy( $policy );
836 if ( isset( $policy['index'] ) ) {
837 $this->setIndexPolicy( $policy['index'] );
839 if ( isset( $policy['follow'] ) ) {
840 $this->setFollowPolicy( $policy['follow'] );
845 * Set the index policy for the page, but leave the follow policy un-
848 * @param string $policy Either 'index' or 'noindex'.
851 public function setIndexPolicy( $policy ) {
852 $policy = trim( $policy );
853 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
854 $this->mIndexPolicy
= $policy;
859 * Set the follow policy for the page, but leave the index policy un-
862 * @param string $policy either 'follow' or 'nofollow'.
865 public function setFollowPolicy( $policy ) {
866 $policy = trim( $policy );
867 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
868 $this->mFollowPolicy
= $policy;
873 * Set the new value of the "action text", this will be added to the
874 * "HTML title", separated from it with " - ".
876 * @param string $text new value of the "action text"
878 public function setPageTitleActionText( $text ) {
879 $this->mPageTitleActionText
= $text;
883 * Get the value of the "action text"
887 public function getPageTitleActionText() {
888 if ( isset( $this->mPageTitleActionText
) ) {
889 return $this->mPageTitleActionText
;
895 * "HTML title" means the contents of "<title>".
896 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
898 * @param string $name
900 public function setHTMLTitle( $name ) {
901 if ( $name instanceof Message
) {
902 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
904 $this->mHTMLtitle
= $name;
909 * Return the "HTML title", i.e. the content of the "<title>" tag.
913 public function getHTMLTitle() {
914 return $this->mHTMLtitle
;
918 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
922 public function setRedirectedFrom( $t ) {
923 $this->mRedirectedFrom
= $t;
927 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
928 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
929 * but not bad tags like \<script\>. This function automatically sets
930 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
931 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
932 * good tags like \<i\> will be dropped entirely.
934 * @param string|Message $name
936 public function setPageTitle( $name ) {
937 if ( $name instanceof Message
) {
938 $name = $name->setContext( $this->getContext() )->text();
941 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
942 # but leave "<i>foobar</i>" alone
943 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
944 $this->mPagetitle
= $nameWithTags;
946 # change "<i>foo&bar</i>" to "foo&bar"
948 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
949 ->inContentLanguage()
954 * Return the "page title", i.e. the content of the \<h1\> tag.
958 public function getPageTitle() {
959 return $this->mPagetitle
;
963 * Set the Title object to use
967 public function setTitle( Title
$t ) {
968 $this->getContext()->setTitle( $t );
972 * Replace the subtitle with $str
974 * @param string|Message $str new value of the subtitle. String should be safe HTML.
976 public function setSubtitle( $str ) {
977 $this->clearSubtitle();
978 $this->addSubtitle( $str );
982 * Add $str to the subtitle
984 * @deprecated since 1.19; use addSubtitle() instead
985 * @param string|Message $str to add to the subtitle
987 public function appendSubtitle( $str ) {
988 $this->addSubtitle( $str );
992 * Add $str to the subtitle
994 * @param string|Message $str to add to the subtitle. String should be safe HTML.
996 public function addSubtitle( $str ) {
997 if ( $str instanceof Message
) {
998 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1000 $this->mSubtitle
[] = $str;
1005 * Add a subtitle containing a backlink to a page
1007 * @param Title $title Title to link to
1009 public function addBacklinkSubtitle( Title
$title ) {
1011 if ( $title->isRedirect() ) {
1012 $query['redirect'] = 'no';
1014 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1015 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1019 * Clear the subtitles
1021 public function clearSubtitle() {
1022 $this->mSubtitle
= array();
1030 public function getSubtitle() {
1031 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1035 * Set the page as printable, i.e. it'll be displayed with with all
1036 * print styles included
1038 public function setPrintable() {
1039 $this->mPrintable
= true;
1043 * Return whether the page is "printable"
1047 public function isPrintable() {
1048 return $this->mPrintable
;
1052 * Disable output completely, i.e. calling output() will have no effect
1054 public function disable() {
1055 $this->mDoNothing
= true;
1059 * Return whether the output will be completely disabled
1063 public function isDisabled() {
1064 return $this->mDoNothing
;
1068 * Show an "add new section" link?
1072 public function showNewSectionLink() {
1073 return $this->mNewSectionLink
;
1077 * Forcibly hide the new section link?
1081 public function forceHideNewSectionLink() {
1082 return $this->mHideNewSectionLink
;
1086 * Add or remove feed links in the page header
1087 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1088 * for the new version
1089 * @see addFeedLink()
1091 * @param bool $show true: add default feeds, false: remove all feeds
1093 public function setSyndicated( $show = true ) {
1095 $this->setFeedAppendQuery( false );
1097 $this->mFeedLinks
= array();
1102 * Add default feeds to the page header
1103 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1104 * for the new version
1105 * @see addFeedLink()
1107 * @param string $val query to append to feed links or false to output
1110 public function setFeedAppendQuery( $val ) {
1111 global $wgAdvertisedFeedTypes;
1113 $this->mFeedLinks
= array();
1115 foreach ( $wgAdvertisedFeedTypes as $type ) {
1116 $query = "feed=$type";
1117 if ( is_string( $val ) ) {
1118 $query .= '&' . $val;
1120 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1125 * Add a feed link to the page header
1127 * @param string $format feed type, should be a key of $wgFeedClasses
1128 * @param string $href URL
1130 public function addFeedLink( $format, $href ) {
1131 global $wgAdvertisedFeedTypes;
1133 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1134 $this->mFeedLinks
[$format] = $href;
1139 * Should we output feed links for this page?
1142 public function isSyndicated() {
1143 return count( $this->mFeedLinks
) > 0;
1147 * Return URLs for each supported syndication format for this page.
1148 * @return array associating format keys with URLs
1150 public function getSyndicationLinks() {
1151 return $this->mFeedLinks
;
1155 * Will currently always return null
1159 public function getFeedAppendQuery() {
1160 return $this->mFeedLinksAppendQuery
;
1164 * Set whether the displayed content is related to the source of the
1165 * corresponding article on the wiki
1166 * Setting true will cause the change "article related" toggle to true
1170 public function setArticleFlag( $v ) {
1171 $this->mIsarticle
= $v;
1173 $this->mIsArticleRelated
= $v;
1178 * Return whether the content displayed page is related to the source of
1179 * the corresponding article on the wiki
1183 public function isArticle() {
1184 return $this->mIsarticle
;
1188 * Set whether this page is related an article on the wiki
1189 * Setting false will cause the change of "article flag" toggle to false
1193 public function setArticleRelated( $v ) {
1194 $this->mIsArticleRelated
= $v;
1196 $this->mIsarticle
= false;
1201 * Return whether this page is related an article on the wiki
1205 public function isArticleRelated() {
1206 return $this->mIsArticleRelated
;
1210 * Add new language links
1212 * @param array $newLinkArray Associative array mapping language code to the page
1215 public function addLanguageLinks( $newLinkArray ) {
1216 $this->mLanguageLinks +
= $newLinkArray;
1220 * Reset the language links and add new language links
1222 * @param array $newLinkArray Associative array mapping language code to the page
1225 public function setLanguageLinks( $newLinkArray ) {
1226 $this->mLanguageLinks
= $newLinkArray;
1230 * Get the list of language links
1232 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1234 public function getLanguageLinks() {
1235 return $this->mLanguageLinks
;
1239 * Add an array of categories, with names in the keys
1241 * @param array $categories mapping category name => sort key
1243 public function addCategoryLinks( $categories ) {
1246 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1250 # Add the links to a LinkBatch
1251 $arr = array( NS_CATEGORY
=> $categories );
1252 $lb = new LinkBatch
;
1253 $lb->setArray( $arr );
1255 # Fetch existence plus the hiddencat property
1256 $dbr = wfGetDB( DB_SLAVE
);
1257 $res = $dbr->select( array( 'page', 'page_props' ),
1258 array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1259 'page_is_redirect', 'page_latest', 'pp_value' ),
1260 $lb->constructSet( 'page', $dbr ),
1263 array( 'page_props' => array( 'LEFT JOIN', array(
1264 'pp_propname' => 'hiddencat',
1269 # Add the results to the link cache
1270 $lb->addResultToCache( LinkCache
::singleton(), $res );
1272 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1273 $categories = array_combine(
1274 array_keys( $categories ),
1275 array_fill( 0, count( $categories ), 'normal' )
1278 # Mark hidden categories
1279 foreach ( $res as $row ) {
1280 if ( isset( $row->pp_value
) ) {
1281 $categories[$row->page_title
] = 'hidden';
1285 # Add the remaining categories to the skin
1287 'OutputPageMakeCategoryLinks',
1288 array( &$this, $categories, &$this->mCategoryLinks
) )
1290 foreach ( $categories as $category => $type ) {
1291 $origcategory = $category;
1292 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1293 $wgContLang->findVariantLink( $category, $title, true );
1294 if ( $category != $origcategory ) {
1295 if ( array_key_exists( $category, $categories ) ) {
1299 $text = $wgContLang->convertHtml( $title->getText() );
1300 $this->mCategories
[] = $title->getText();
1301 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1307 * Reset the category links (but not the category list) and add $categories
1309 * @param array $categories mapping category name => sort key
1311 public function setCategoryLinks( $categories ) {
1312 $this->mCategoryLinks
= array();
1313 $this->addCategoryLinks( $categories );
1317 * Get the list of category links, in a 2-D array with the following format:
1318 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1319 * hidden categories) and $link a HTML fragment with a link to the category
1324 public function getCategoryLinks() {
1325 return $this->mCategoryLinks
;
1329 * Get the list of category names this page belongs to
1331 * @return array Array of strings
1333 public function getCategories() {
1334 return $this->mCategories
;
1338 * Do not allow scripts which can be modified by wiki users to load on this page;
1339 * only allow scripts bundled with, or generated by, the software.
1341 public function disallowUserJs() {
1342 $this->reduceAllowedModules(
1343 ResourceLoaderModule
::TYPE_SCRIPTS
,
1344 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1349 * Return whether user JavaScript is allowed for this page
1350 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1351 * trustworthiness is identified and enforced automagically.
1354 public function isUserJsAllowed() {
1355 wfDeprecated( __METHOD__
, '1.18' );
1356 return $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
) >=
1357 ResourceLoaderModule
::ORIGIN_USER_INDIVIDUAL
;
1361 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1362 * @see ResourceLoaderModule::$origin
1363 * @param string $type ResourceLoaderModule TYPE_ constant
1364 * @return int ResourceLoaderModule ORIGIN_ class constant
1366 public function getAllowedModules( $type ) {
1367 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1368 return min( array_values( $this->mAllowedModules
) );
1370 return isset( $this->mAllowedModules
[$type] )
1371 ?
$this->mAllowedModules
[$type]
1372 : ResourceLoaderModule
::ORIGIN_ALL
;
1377 * Set the highest level of CSS/JS untrustworthiness allowed
1378 * @param string $type ResourceLoaderModule TYPE_ constant
1379 * @param int $level ResourceLoaderModule class constant
1381 public function setAllowedModules( $type, $level ) {
1382 $this->mAllowedModules
[$type] = $level;
1386 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1387 * @param string $type
1388 * @param int $level ResourceLoaderModule class constant
1390 public function reduceAllowedModules( $type, $level ) {
1391 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1395 * Prepend $text to the body HTML
1397 * @param string $text HTML
1399 public function prependHTML( $text ) {
1400 $this->mBodytext
= $text . $this->mBodytext
;
1404 * Append $text to the body HTML
1406 * @param string $text HTML
1408 public function addHTML( $text ) {
1409 $this->mBodytext
.= $text;
1413 * Shortcut for adding an Html::element via addHTML.
1417 * @param string $element
1418 * @param array $attribs
1419 * @param string $contents
1421 public function addElement( $element, $attribs = array(), $contents = '' ) {
1422 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1426 * Clear the body HTML
1428 public function clearHTML() {
1429 $this->mBodytext
= '';
1435 * @return string HTML
1437 public function getHTML() {
1438 return $this->mBodytext
;
1442 * Get/set the ParserOptions object to use for wikitext parsing
1444 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1445 * current ParserOption object
1446 * @return ParserOptions
1448 public function parserOptions( $options = null ) {
1449 if ( !$this->mParserOptions
) {
1450 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1451 $this->mParserOptions
->setEditSection( false );
1453 return wfSetVar( $this->mParserOptions
, $options );
1457 * Set the revision ID which will be seen by the wiki text parser
1458 * for things such as embedded {{REVISIONID}} variable use.
1460 * @param int|null $revid An positive integer, or null
1461 * @return mixed Previous value
1463 public function setRevisionId( $revid ) {
1464 $val = is_null( $revid ) ?
null : intval( $revid );
1465 return wfSetVar( $this->mRevisionId
, $val );
1469 * Get the displayed revision ID
1473 public function getRevisionId() {
1474 return $this->mRevisionId
;
1478 * Set the timestamp of the revision which will be displayed. This is used
1479 * to avoid a extra DB call in Skin::lastModified().
1481 * @param string|null $timestamp
1482 * @return mixed Previous value
1484 public function setRevisionTimestamp( $timestamp ) {
1485 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1489 * Get the timestamp of displayed revision.
1490 * This will be null if not filled by setRevisionTimestamp().
1492 * @return string|null
1494 public function getRevisionTimestamp() {
1495 return $this->mRevisionTimestamp
;
1499 * Set the displayed file version
1501 * @param File|bool $file
1502 * @return mixed Previous value
1504 public function setFileVersion( $file ) {
1506 if ( $file instanceof File
&& $file->exists() ) {
1507 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1509 return wfSetVar( $this->mFileVersion
, $val, true );
1513 * Get the displayed file version
1515 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1517 public function getFileVersion() {
1518 return $this->mFileVersion
;
1522 * Get the templates used on this page
1524 * @return array (namespace => dbKey => revId)
1527 public function getTemplateIds() {
1528 return $this->mTemplateIds
;
1532 * Get the files used on this page
1534 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1537 public function getFileSearchOptions() {
1538 return $this->mImageTimeKeys
;
1542 * Convert wikitext to HTML and add it to the buffer
1543 * Default assumes that the current page title will be used.
1545 * @param string $text
1546 * @param bool $linestart Is this the start of a line?
1547 * @param bool $interface Is this text in the user interface language?
1549 public function addWikiText( $text, $linestart = true, $interface = true ) {
1550 $title = $this->getTitle(); // Work around E_STRICT
1552 throw new MWException( 'Title is null' );
1554 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1558 * Add wikitext with a custom Title object
1560 * @param string $text Wikitext
1561 * @param Title $title
1562 * @param bool $linestart Is this the start of a line?
1564 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1565 $this->addWikiTextTitle( $text, $title, $linestart );
1569 * Add wikitext with a custom Title object and tidy enabled.
1571 * @param string $text Wikitext
1572 * @param Title $title
1573 * @param bool $linestart Is this the start of a line?
1575 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1576 $this->addWikiTextTitle( $text, $title, $linestart, true );
1580 * Add wikitext with tidy enabled
1582 * @param string $text Wikitext
1583 * @param bool $linestart Is this the start of a line?
1585 public function addWikiTextTidy( $text, $linestart = true ) {
1586 $title = $this->getTitle();
1587 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1591 * Add wikitext with a custom Title object
1593 * @param string $text Wikitext
1594 * @param Title $title
1595 * @param bool $linestart Is this the start of a line?
1596 * @param bool $tidy Whether to use tidy
1597 * @param bool $interface Whether it is an interface message
1598 * (for example disables conversion)
1600 public function addWikiTextTitle( $text, Title
$title, $linestart,
1601 $tidy = false, $interface = false
1605 wfProfileIn( __METHOD__
);
1607 $popts = $this->parserOptions();
1608 $oldTidy = $popts->setTidy( $tidy );
1609 $popts->setInterfaceMessage( (bool)$interface );
1611 $parserOutput = $wgParser->parse(
1612 $text, $title, $popts,
1613 $linestart, true, $this->mRevisionId
1616 $popts->setTidy( $oldTidy );
1618 $this->addParserOutput( $parserOutput );
1620 wfProfileOut( __METHOD__
);
1624 * Add a ParserOutput object, but without Html
1626 * @param ParserOutput $parserOutput
1628 public function addParserOutputNoText( &$parserOutput ) {
1629 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1630 $this->addCategoryLinks( $parserOutput->getCategories() );
1631 $this->mNewSectionLink
= $parserOutput->getNewSection();
1632 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1634 $this->mParseWarnings
= $parserOutput->getWarnings();
1635 if ( !$parserOutput->isCacheable() ) {
1636 $this->enableClientCache( false );
1638 $this->mNoGallery
= $parserOutput->getNoGallery();
1639 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1640 $this->addModules( $parserOutput->getModules() );
1641 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1642 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1643 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1644 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1646 // Template versioning...
1647 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1648 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1649 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1651 $this->mTemplateIds
[$ns] = $dbks;
1654 // File versioning...
1655 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1656 $this->mImageTimeKeys
[$dbk] = $data;
1659 // Hooks registered in the object
1660 global $wgParserOutputHooks;
1661 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1662 list( $hookName, $data ) = $hookInfo;
1663 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1664 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1668 // Link flags are ignored for now, but may in the future be
1669 // used to mark individual language links.
1670 $linkFlags = array();
1671 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1672 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1676 * Add a ParserOutput object
1678 * @param ParserOutput $parserOutput
1680 function addParserOutput( &$parserOutput ) {
1681 $this->addParserOutputNoText( $parserOutput );
1682 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1684 // Touch section edit links only if not previously disabled
1685 if ( $parserOutput->getEditSectionTokens() ) {
1686 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1688 $text = $parserOutput->getText();
1689 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1690 $this->addHTML( $text );
1694 * Add the output of a QuickTemplate to the output buffer
1696 * @param QuickTemplate $template
1698 public function addTemplate( &$template ) {
1699 $this->addHTML( $template->getHTML() );
1703 * Parse wikitext and return the HTML.
1705 * @param string $text
1706 * @param bool $linestart Is this the start of a line?
1707 * @param bool $interface Use interface language ($wgLang instead of
1708 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1709 * This also disables LanguageConverter.
1710 * @param Language $language Target language object, will override $interface
1711 * @throws MWException
1712 * @return string HTML
1714 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1717 if ( is_null( $this->getTitle() ) ) {
1718 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1721 $popts = $this->parserOptions();
1723 $popts->setInterfaceMessage( true );
1725 if ( $language !== null ) {
1726 $oldLang = $popts->setTargetLanguage( $language );
1729 $parserOutput = $wgParser->parse(
1730 $text, $this->getTitle(), $popts,
1731 $linestart, true, $this->mRevisionId
1735 $popts->setInterfaceMessage( false );
1737 if ( $language !== null ) {
1738 $popts->setTargetLanguage( $oldLang );
1741 return $parserOutput->getText();
1745 * Parse wikitext, strip paragraphs, and return the HTML.
1747 * @param string $text
1748 * @param bool $linestart Is this the start of a line?
1749 * @param bool $interface Use interface language ($wgLang instead of
1750 * $wgContLang) while parsing language sensitive magic
1751 * words like GRAMMAR and PLURAL
1752 * @return string HTML
1754 public function parseInline( $text, $linestart = true, $interface = false ) {
1755 $parsed = $this->parse( $text, $linestart, $interface );
1756 return Parser
::stripOuterParagraph( $parsed );
1760 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1762 * @param int $maxage Maximum cache time on the Squid, in seconds.
1764 public function setSquidMaxage( $maxage ) {
1765 $this->mSquidMaxage
= $maxage;
1769 * Use enableClientCache(false) to force it to send nocache headers
1771 * @param bool $state
1775 public function enableClientCache( $state ) {
1776 return wfSetVar( $this->mEnableClientCache
, $state );
1780 * Get the list of cookies that will influence on the cache
1784 function getCacheVaryCookies() {
1785 global $wgCookiePrefix, $wgCacheVaryCookies;
1787 if ( $cookies === null ) {
1788 $cookies = array_merge(
1790 "{$wgCookiePrefix}Token",
1791 "{$wgCookiePrefix}LoggedOut",
1797 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1803 * Check if the request has a cache-varying cookie header
1804 * If it does, it's very important that we don't allow public caching
1808 function haveCacheVaryCookies() {
1809 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1810 if ( $cookieHeader === false ) {
1813 $cvCookies = $this->getCacheVaryCookies();
1814 foreach ( $cvCookies as $cookieName ) {
1815 # Check for a simple string match, like the way squid does it
1816 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1817 wfDebug( __METHOD__
. ": found $cookieName\n" );
1821 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1826 * Add an HTTP header that will influence on the cache
1828 * @param string $header header name
1829 * @param array|null $option
1830 * @todo FIXME: Document the $option parameter; it appears to be for
1831 * X-Vary-Options but what format is acceptable?
1833 public function addVaryHeader( $header, $option = null ) {
1834 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1835 $this->mVaryHeader
[$header] = (array)$option;
1836 } elseif ( is_array( $option ) ) {
1837 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1838 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1840 $this->mVaryHeader
[$header] = $option;
1843 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1847 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1848 * such as Accept-Encoding or Cookie
1852 public function getVaryHeader() {
1853 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1857 * Get a complete X-Vary-Options header
1861 public function getXVO() {
1862 $cvCookies = $this->getCacheVaryCookies();
1864 $cookiesOption = array();
1865 foreach ( $cvCookies as $cookieName ) {
1866 $cookiesOption[] = 'string-contains=' . $cookieName;
1868 $this->addVaryHeader( 'Cookie', $cookiesOption );
1871 foreach ( $this->mVaryHeader
as $header => $option ) {
1872 $newheader = $header;
1873 if ( is_array( $option ) && count( $option ) > 0 ) {
1874 $newheader .= ';' . implode( ';', $option );
1876 $headers[] = $newheader;
1878 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1884 * bug 21672: Add Accept-Language to Vary and XVO headers
1885 * if there's no 'variant' parameter existed in GET.
1888 * /w/index.php?title=Main_page should always be served; but
1889 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1891 function addAcceptLanguage() {
1892 $title = $this->getTitle();
1893 if ( !$title instanceof Title
) {
1897 $lang = $title->getPageLanguage();
1898 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1899 $variants = $lang->getVariants();
1900 $aloption = array();
1901 foreach ( $variants as $variant ) {
1902 if ( $variant === $lang->getCode() ) {
1905 $aloption[] = 'string-contains=' . $variant;
1907 // IE and some other browsers use BCP 47 standards in
1908 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1909 // We should handle these too.
1910 $variantBCP47 = wfBCP47( $variant );
1911 if ( $variantBCP47 !== $variant ) {
1912 $aloption[] = 'string-contains=' . $variantBCP47;
1916 $this->addVaryHeader( 'Accept-Language', $aloption );
1921 * Set a flag which will cause an X-Frame-Options header appropriate for
1922 * edit pages to be sent. The header value is controlled by
1923 * $wgEditPageFrameOptions.
1925 * This is the default for special pages. If you display a CSRF-protected
1926 * form on an ordinary view page, then you need to call this function.
1928 * @param bool $enable
1930 public function preventClickjacking( $enable = true ) {
1931 $this->mPreventClickjacking
= $enable;
1935 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1936 * This can be called from pages which do not contain any CSRF-protected
1939 public function allowClickjacking() {
1940 $this->mPreventClickjacking
= false;
1944 * Get the X-Frame-Options header value (without the name part), or false
1945 * if there isn't one. This is used by Skin to determine whether to enable
1946 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1950 public function getFrameOptions() {
1951 global $wgBreakFrames, $wgEditPageFrameOptions;
1952 if ( $wgBreakFrames ) {
1954 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1955 return $wgEditPageFrameOptions;
1961 * Send cache control HTTP headers
1963 public function sendCacheControl() {
1964 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1966 $response = $this->getRequest()->response();
1967 if ( $wgUseETag && $this->mETag
) {
1968 $response->header( "ETag: $this->mETag" );
1971 $this->addVaryHeader( 'Cookie' );
1972 $this->addAcceptLanguage();
1974 # don't serve compressed data to clients who can't handle it
1975 # maintain different caches for logged-in users and non-logged in ones
1976 $response->header( $this->getVaryHeader() );
1979 # Add an X-Vary-Options header for Squid with Wikimedia patches
1980 $response->header( $this->getXVO() );
1983 if ( $this->mEnableClientCache
) {
1985 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1986 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1989 # We'll purge the proxy cache explicitly, but require end user agents
1990 # to revalidate against the proxy on each visit.
1991 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1992 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
1993 # start with a shorter timeout for initial testing
1994 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1995 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
1996 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
1997 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1999 # We'll purge the proxy cache for anons explicitly, but require end user agents
2000 # to revalidate against the proxy on each visit.
2001 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2002 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2003 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2004 # start with a shorter timeout for initial testing
2005 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2006 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2007 . ', must-revalidate, max-age=0' );
2010 # We do want clients to cache if they can, but they *must* check for updates
2011 # on revisiting the page.
2012 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2013 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2014 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2016 if ( $this->mLastModified
) {
2017 $response->header( "Last-Modified: {$this->mLastModified}" );
2020 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2022 # In general, the absence of a last modified header should be enough to prevent
2023 # the client from using its cache. We send a few other things just to make sure.
2024 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2025 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2026 $response->header( 'Pragma: no-cache' );
2031 * Get the message associated with the HTTP response code $code
2033 * @param int $code Status code
2034 * @return string|null Message or null if $code is not in the list of messages
2036 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
2038 public static function getStatusMessage( $code ) {
2039 wfDeprecated( __METHOD__
, '1.18' );
2040 return HttpStatus
::getMessage( $code );
2044 * Finally, all the text has been munged and accumulated into
2045 * the object, let's actually output it:
2047 public function output() {
2048 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
2049 $wgUseAjax, $wgResponsiveImages;
2051 if ( $this->mDoNothing
) {
2055 wfProfileIn( __METHOD__
);
2057 $response = $this->getRequest()->response();
2059 if ( $this->mRedirect
!= '' ) {
2060 # Standards require redirect URLs to be absolute
2061 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2063 $redirect = $this->mRedirect
;
2064 $code = $this->mRedirectCode
;
2066 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2067 if ( $code == '301' ||
$code == '303' ) {
2068 if ( !$wgDebugRedirects ) {
2069 $message = HttpStatus
::getMessage( $code );
2070 $response->header( "HTTP/1.1 $code $message" );
2072 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2074 if ( $wgVaryOnXFP ) {
2075 $this->addVaryHeader( 'X-Forwarded-Proto' );
2077 $this->sendCacheControl();
2079 $response->header( "Content-Type: text/html; charset=utf-8" );
2080 if ( $wgDebugRedirects ) {
2081 $url = htmlspecialchars( $redirect );
2082 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2083 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2084 print "</body>\n</html>\n";
2086 $response->header( 'Location: ' . $redirect );
2090 wfProfileOut( __METHOD__
);
2092 } elseif ( $this->mStatusCode
) {
2093 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2095 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2099 # Buffer output; final headers may depend on later processing
2102 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2103 $response->header( 'Content-language: ' . $wgLanguageCode );
2105 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2106 // jQuery etc. can work correctly.
2107 $response->header( 'X-UA-Compatible: IE=Edge' );
2109 // Prevent framing, if requested
2110 $frameOptions = $this->getFrameOptions();
2111 if ( $frameOptions ) {
2112 $response->header( "X-Frame-Options: $frameOptions" );
2115 if ( $this->mArticleBodyOnly
) {
2116 echo $this->mBodytext
;
2119 $sk = $this->getSkin();
2120 // add skin specific modules
2121 $modules = $sk->getDefaultModules();
2123 // enforce various default modules for all skins
2124 $coreModules = array(
2125 // keep this list as small as possible
2126 'mediawiki.page.startup',
2130 // Support for high-density display images if enabled
2131 if ( $wgResponsiveImages ) {
2132 $coreModules[] = 'mediawiki.hidpi';
2135 $this->addModules( $coreModules );
2136 foreach ( $modules as $group ) {
2137 $this->addModules( $group );
2139 MWDebug
::addModules( $this );
2141 // FIXME: deprecate? - not clear why this is useful
2142 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2145 // Hook that allows last minute changes to the output page, e.g.
2146 // adding of CSS or Javascript by extensions.
2147 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2149 wfProfileIn( 'Output-skin' );
2151 wfProfileOut( 'Output-skin' );
2154 // This hook allows last minute changes to final overall output by modifying output buffer
2155 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2157 $this->sendCacheControl();
2161 wfProfileOut( __METHOD__
);
2165 * Actually output something with print.
2167 * @param string $ins the string to output
2168 * @deprecated since 1.22 Use echo yourself.
2170 public function out( $ins ) {
2171 wfDeprecated( __METHOD__
, '1.22' );
2176 * Produce a "user is blocked" page.
2177 * @deprecated since 1.18
2179 function blockedPage() {
2180 throw new UserBlockedError( $this->getUser()->mBlock
);
2184 * Prepare this object to display an error page; disable caching and
2185 * indexing, clear the current text and redirect, set the page's title
2186 * and optionally an custom HTML title (content of the "<title>" tag).
2188 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2189 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2190 * optional, if not passed the "<title>" attribute will be
2191 * based on $pageTitle
2193 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2194 $this->setPageTitle( $pageTitle );
2195 if ( $htmlTitle !== false ) {
2196 $this->setHTMLTitle( $htmlTitle );
2198 $this->setRobotPolicy( 'noindex,nofollow' );
2199 $this->setArticleRelated( false );
2200 $this->enableClientCache( false );
2201 $this->mRedirect
= '';
2202 $this->clearSubtitle();
2207 * Output a standard error page
2209 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2210 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2211 * showErrorPage( 'titlemsg', $messageObject );
2212 * showErrorPage( $titleMessageObject, $messageObject );
2214 * @param string|Message $title Message key (string) for page title, or a Message object
2215 * @param string|Message $msg Message key (string) for page text, or a Message object
2216 * @param array $params Message parameters; ignored if $msg is a Message object
2218 public function showErrorPage( $title, $msg, $params = array() ) {
2219 if ( !$title instanceof Message
) {
2220 $title = $this->msg( $title );
2223 $this->prepareErrorPage( $title );
2225 if ( $msg instanceof Message
) {
2226 if ( $params !== array() ) {
2227 trigger_error( 'Argument ignored: $params. The message parameters argument '
2228 . 'is discarded when the $msg argument is a Message object instead of '
2229 . 'a string.', E_USER_NOTICE
);
2231 $this->addHTML( $msg->parseAsBlock() );
2233 $this->addWikiMsgArray( $msg, $params );
2236 $this->returnToMain();
2240 * Output a standard permission error page
2242 * @param array $errors error message keys
2243 * @param string $action action that was denied or null if unknown
2245 public function showPermissionsErrorPage( $errors, $action = null ) {
2246 // For some action (read, edit, create and upload), display a "login to do this action"
2247 // error if all of the following conditions are met:
2248 // 1. the user is not logged in
2249 // 2. the only error is insufficient permissions (i.e. no block or something else)
2250 // 3. the error can be avoided simply by logging in
2251 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2252 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2253 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2254 && ( User
::groupHasPermission( 'user', $action )
2255 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2257 $displayReturnto = null;
2259 # Due to bug 32276, if a user does not have read permissions,
2260 # $this->getTitle() will just give Special:Badtitle, which is
2261 # not especially useful as a returnto parameter. Use the title
2262 # from the request instead, if there was one.
2263 $request = $this->getRequest();
2264 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2265 if ( $action == 'edit' ) {
2266 $msg = 'whitelistedittext';
2267 $displayReturnto = $returnto;
2268 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2269 $msg = 'nocreatetext';
2270 } elseif ( $action == 'upload' ) {
2271 $msg = 'uploadnologintext';
2273 $msg = 'loginreqpagetext';
2274 $displayReturnto = Title
::newMainPage();
2280 $query['returnto'] = $returnto->getPrefixedText();
2282 if ( !$request->wasPosted() ) {
2283 $returntoquery = $request->getValues();
2284 unset( $returntoquery['title'] );
2285 unset( $returntoquery['returnto'] );
2286 unset( $returntoquery['returntoquery'] );
2287 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2290 $loginLink = Linker
::linkKnown(
2291 SpecialPage
::getTitleFor( 'Userlogin' ),
2292 $this->msg( 'loginreqlink' )->escaped(),
2297 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2298 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2300 # Don't return to a page the user can't read otherwise
2301 # we'll end up in a pointless loop
2302 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2303 $this->returnToMain( null, $displayReturnto );
2306 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2307 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2312 * Display an error page indicating that a given version of MediaWiki is
2313 * required to use it
2315 * @param mixed $version The version of MediaWiki needed to use the page
2317 public function versionRequired( $version ) {
2318 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2320 $this->addWikiMsg( 'versionrequiredtext', $version );
2321 $this->returnToMain();
2325 * Display an error page noting that a given permission bit is required.
2326 * @deprecated since 1.18, just throw the exception directly
2327 * @param string $permission key required
2328 * @throws PermissionsError
2330 public function permissionRequired( $permission ) {
2331 throw new PermissionsError( $permission );
2335 * Produce the stock "please login to use the wiki" page
2337 * @deprecated since 1.19; throw the exception directly
2339 public function loginToUse() {
2340 throw new PermissionsError( 'read' );
2344 * Format a list of error messages
2346 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2347 * @param string $action Action that was denied or null if unknown
2348 * @return string The wikitext error-messages, formatted into a list.
2350 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2351 if ( $action == null ) {
2352 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2354 $action_desc = $this->msg( "action-$action" )->plain();
2356 'permissionserrorstext-withaction',
2359 )->plain() . "\n\n";
2362 if ( count( $errors ) > 1 ) {
2363 $text .= '<ul class="permissions-errors">' . "\n";
2365 foreach ( $errors as $error ) {
2367 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2372 $text .= "<div class=\"permissions-errors\">\n" .
2373 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2381 * Display a page stating that the Wiki is in read-only mode,
2382 * and optionally show the source of the page that the user
2383 * was trying to edit. Should only be called (for this
2384 * purpose) after wfReadOnly() has returned true.
2386 * For historical reasons, this function is _also_ used to
2387 * show the error message when a user tries to edit a page
2388 * they are not allowed to edit. (Unless it's because they're
2389 * blocked, then we show blockedPage() instead.) In this
2390 * case, the second parameter should be set to true and a list
2391 * of reasons supplied as the third parameter.
2393 * @todo Needs to be split into multiple functions.
2395 * @param string $source Source code to show (or null).
2396 * @param bool $protected Is this a permissions error?
2397 * @param array $reasons List of reasons for this error, as returned by
2398 * Title::getUserPermissionsErrors().
2399 * @param string $action Action that was denied or null if unknown
2400 * @throws ReadOnlyError
2402 public function readOnlyPage( $source = null, $protected = false,
2403 $reasons = array(), $action = null
2405 $this->setRobotPolicy( 'noindex,nofollow' );
2406 $this->setArticleRelated( false );
2408 // If no reason is given, just supply a default "I can't let you do
2409 // that, Dave" message. Should only occur if called by legacy code.
2410 if ( $protected && empty( $reasons ) ) {
2411 $reasons[] = array( 'badaccess-group0' );
2414 if ( !empty( $reasons ) ) {
2415 // Permissions error
2417 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2418 $this->addBacklinkSubtitle( $this->getTitle() );
2420 $this->setPageTitle( $this->msg( 'badaccess' ) );
2422 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2424 // Wiki is read only
2425 throw new ReadOnlyError
;
2428 // Show source, if supplied
2429 if ( is_string( $source ) ) {
2430 $this->addWikiMsg( 'viewsourcetext' );
2432 $pageLang = $this->getTitle()->getPageLanguage();
2434 'id' => 'wpTextbox1',
2435 'name' => 'wpTextbox1',
2436 'cols' => $this->getUser()->getOption( 'cols' ),
2437 'rows' => $this->getUser()->getOption( 'rows' ),
2438 'readonly' => 'readonly',
2439 'lang' => $pageLang->getHtmlCode(),
2440 'dir' => $pageLang->getDir(),
2442 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2444 // Show templates used by this article
2445 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2446 $this->addHTML( "<div class='templatesUsed'>
2452 # If the title doesn't exist, it's fairly pointless to print a return
2453 # link to it. After all, you just tried editing it and couldn't, so
2454 # what's there to do there?
2455 if ( $this->getTitle()->exists() ) {
2456 $this->returnToMain( null, $this->getTitle() );
2461 * Turn off regular page output and return an error response
2462 * for when rate limiting has triggered.
2464 public function rateLimited() {
2465 throw new ThrottledError
;
2469 * Show a warning about slave lag
2471 * If the lag is higher than $wgSlaveLagCritical seconds,
2472 * then the warning is a bit more obvious. If the lag is
2473 * lower than $wgSlaveLagWarning, then no warning is shown.
2475 * @param int $lag Slave lag
2477 public function showLagWarning( $lag ) {
2478 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2479 if ( $lag >= $wgSlaveLagWarning ) {
2480 $message = $lag < $wgSlaveLagCritical
2483 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2484 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2488 public function showFatalError( $message ) {
2489 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2491 $this->addHTML( $message );
2494 public function showUnexpectedValueError( $name, $val ) {
2495 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2498 public function showFileCopyError( $old, $new ) {
2499 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2502 public function showFileRenameError( $old, $new ) {
2503 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2506 public function showFileDeleteError( $name ) {
2507 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2510 public function showFileNotFoundError( $name ) {
2511 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2515 * Add a "return to" link pointing to a specified title
2517 * @param Title $title Title to link
2518 * @param array $query Query string parameters
2519 * @param string $text Text of the link (input is not escaped)
2520 * @param array $options Options array to pass to Linker
2522 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2523 $link = $this->msg( 'returnto' )->rawParams(
2524 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2525 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2529 * Add a "return to" link pointing to a specified title,
2530 * or the title indicated in the request, or else the main page
2532 * @param mixed $unused
2533 * @param Title|string $returnto Title or String to return to
2534 * @param string $returntoquery Query string for the return to link
2536 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2537 if ( $returnto == null ) {
2538 $returnto = $this->getRequest()->getText( 'returnto' );
2541 if ( $returntoquery == null ) {
2542 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2545 if ( $returnto === '' ) {
2546 $returnto = Title
::newMainPage();
2549 if ( is_object( $returnto ) ) {
2550 $titleObj = $returnto;
2552 $titleObj = Title
::newFromText( $returnto );
2554 if ( !is_object( $titleObj ) ) {
2555 $titleObj = Title
::newMainPage();
2558 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2562 * @param Skin $sk The given Skin
2563 * @param bool $includeStyle Unused
2564 * @return string The doctype, opening "<html>", and head element.
2566 public function headElement( Skin
$sk, $includeStyle = true ) {
2567 global $wgContLang, $wgMimeType;
2569 $userdir = $this->getLanguage()->getDir();
2570 $sitedir = $wgContLang->getDir();
2572 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2574 if ( $this->getHTMLTitle() == '' ) {
2575 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2578 $openHead = Html
::openElement( 'head' );
2580 # Don't bother with the newline if $head == ''
2581 $ret .= "$openHead\n";
2584 if ( !Html
::isXmlMimeType( $wgMimeType ) ) {
2585 // Add <meta charset="UTF-8">
2586 // This should be before <title> since it defines the charset used by
2587 // text including the text inside <title>.
2588 // The spec recommends defining XHTML5's charset using the XML declaration
2590 // Our XML declaration is output by Html::htmlHeader.
2591 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2592 // http://www.whatwg.org/html/semantics.html#charset
2593 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2596 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2598 foreach ( $this->getHeadLinksArray() as $item ) {
2599 $ret .= $item . "\n";
2602 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2603 $ret .= $this->buildCssLinks();
2605 $ret .= $this->getHeadScripts() . "\n";
2607 foreach ( $this->mHeadItems
as $item ) {
2608 $ret .= $item . "\n";
2611 $closeHead = Html
::closeElement( 'head' );
2613 $ret .= "$closeHead\n";
2616 $bodyClasses = array();
2617 $bodyClasses[] = 'mediawiki';
2619 # Classes for LTR/RTL directionality support
2620 $bodyClasses[] = $userdir;
2621 $bodyClasses[] = "sitedir-$sitedir";
2623 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2624 # A <body> class is probably not the best way to do this . . .
2625 $bodyClasses[] = 'capitalize-all-nouns';
2628 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2629 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2631 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2633 $bodyAttrs = array();
2634 // While the implode() is not strictly needed, it's used for backwards compatibility
2635 // (this used to be built as a string and hooks likely still expect that).
2636 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2638 // Allow skins and extensions to add body attributes they need
2639 $sk->addToBodyAttributes( $this, $bodyAttrs );
2640 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2642 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2648 * Get a ResourceLoader object associated with this OutputPage
2650 * @return ResourceLoader
2652 public function getResourceLoader() {
2653 if ( is_null( $this->mResourceLoader
) ) {
2654 $this->mResourceLoader
= new ResourceLoader();
2656 return $this->mResourceLoader
;
2661 * @param array|string $modules One or more module names
2662 * @param string $only ResourceLoaderModule TYPE_ class constant
2663 * @param bool $useESI
2664 * @param array $extraQuery Array with extra query parameters to add to each
2665 * request. array( param => value ).
2666 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2667 * call rather than a "<script src='...'>" tag.
2668 * @return string The html "<script>", "<link>" and "<style>" tags
2670 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2671 array $extraQuery = array(), $loadCall = false
2673 global $wgResourceLoaderUseESI;
2675 $modules = (array)$modules;
2679 'states' => array(),
2682 if ( !count( $modules ) ) {
2686 if ( count( $modules ) > 1 ) {
2687 // Remove duplicate module requests
2688 $modules = array_unique( $modules );
2689 // Sort module names so requests are more uniform
2692 if ( ResourceLoader
::inDebugMode() ) {
2693 // Recursively call us for every item
2694 foreach ( $modules as $name ) {
2695 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2696 $links['html'] .= $link['html'];
2697 $links['states'] +
= $link['states'];
2703 if ( !is_null( $this->mTarget
) ) {
2704 $extraQuery['target'] = $this->mTarget
;
2707 // Create keyed-by-group list of module objects from modules list
2709 $resourceLoader = $this->getResourceLoader();
2710 foreach ( $modules as $name ) {
2711 $module = $resourceLoader->getModule( $name );
2712 # Check that we're allowed to include this module on this page
2714 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2715 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2716 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2717 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2718 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2723 $group = $module->getGroup();
2724 if ( !isset( $groups[$group] ) ) {
2725 $groups[$group] = array();
2727 $groups[$group][$name] = $module;
2730 foreach ( $groups as $group => $grpModules ) {
2731 // Special handling for user-specific groups
2733 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2734 $user = $this->getUser()->getName();
2737 // Create a fake request based on the one we are about to make so modules return
2738 // correct timestamp and emptiness data
2739 $query = ResourceLoader
::makeLoaderQuery(
2740 array(), // modules; not determined yet
2741 $this->getLanguage()->getCode(),
2742 $this->getSkin()->getSkinName(),
2744 null, // version; not determined yet
2745 ResourceLoader
::inDebugMode(),
2746 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2747 $this->isPrintable(),
2748 $this->getRequest()->getBool( 'handheld' ),
2751 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2753 // Extract modules that know they're empty
2754 foreach ( $grpModules as $key => $module ) {
2755 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2756 // If we're only getting the styles, we don't need to do anything for empty modules.
2757 if ( $module->isKnownEmpty( $context ) ) {
2758 unset( $grpModules[$key] );
2759 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2760 $links['states'][$key] = 'ready';
2765 // If there are no non-empty modules, skip this group
2766 if ( count( $grpModules ) === 0 ) {
2770 // Inline private modules. These can't be loaded through load.php for security
2771 // reasons, see bug 34907. Note that these modules should be loaded from
2772 // getHeadScripts() before the first loader call. Otherwise other modules can't
2773 // properly use them as dependencies (bug 30914)
2774 if ( $group === 'private' ) {
2775 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2776 $links['html'] .= Html
::inlineStyle(
2777 $resourceLoader->makeModuleResponse( $context, $grpModules )
2780 $links['html'] .= Html
::inlineScript(
2781 ResourceLoader
::makeLoaderConditionalScript(
2782 $resourceLoader->makeModuleResponse( $context, $grpModules )
2786 $links['html'] .= "\n";
2790 // Special handling for the user group; because users might change their stuff
2791 // on-wiki like user pages, or user preferences; we need to find the highest
2792 // timestamp of these user-changeable modules so we can ensure cache misses on change
2793 // This should NOT be done for the site group (bug 27564) because anons get that too
2794 // and we shouldn't be putting timestamps in Squid-cached HTML
2796 if ( $group === 'user' ) {
2797 // Get the maximum timestamp
2799 foreach ( $grpModules as $module ) {
2800 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2802 // Add a version parameter so cache will break when things change
2803 $version = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2806 $url = ResourceLoader
::makeLoaderURL(
2807 array_keys( $grpModules ),
2808 $this->getLanguage()->getCode(),
2809 $this->getSkin()->getSkinName(),
2812 ResourceLoader
::inDebugMode(),
2813 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2814 $this->isPrintable(),
2815 $this->getRequest()->getBool( 'handheld' ),
2818 if ( $useESI && $wgResourceLoaderUseESI ) {
2819 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2820 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2821 $link = Html
::inlineStyle( $esi );
2823 $link = Html
::inlineScript( $esi );
2826 // Automatically select style/script elements
2827 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2828 $link = Html
::linkedStyle( $url );
2829 } elseif ( $loadCall ) {
2830 $link = Html
::inlineScript(
2831 ResourceLoader
::makeLoaderConditionalScript(
2832 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2836 $link = Html
::linkedScript( $url );
2838 // For modules requested directly in the html via <link> or <script>,
2839 // tell mw.loader they are being loading to prevent duplicate requests.
2840 foreach ( $grpModules as $key => $module ) {
2841 // Don't output state=loading for the startup module..
2842 if ( $key !== 'startup' ) {
2843 $links['states'][$key] = 'loading';
2849 if ( $group == 'noscript' ) {
2850 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2852 $links['html'] .= $link . "\n";
2860 * Build html output from an array of links from makeResourceLoaderLink.
2861 * @param array $links
2862 * @return string HTML
2864 protected static function getHtmlFromLoaderLinks( Array $links ) {
2867 foreach ( $links as $link ) {
2868 if ( !is_array( $link ) ) {
2871 $html .= $link['html'];
2872 $states +
= $link['states'];
2876 if ( count( $states ) ) {
2877 $html = Html
::inlineScript(
2878 ResourceLoader
::makeLoaderConditionalScript(
2879 ResourceLoader
::makeLoaderStateScript( $states )
2888 * JS stuff to put in the "<head>". This is the startup module, config
2889 * vars and modules marked with position 'top'
2891 * @return string HTML fragment
2893 function getHeadScripts() {
2894 global $wgResourceLoaderExperimentalAsyncLoading;
2896 // Startup - this will immediately load jquery and mediawiki modules
2898 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2900 // Load config before anything else
2901 $links[] = Html
::inlineScript(
2902 ResourceLoader
::makeLoaderConditionalScript(
2903 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2907 // Load embeddable private modules before any loader links
2908 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2909 // in mw.loader.implement() calls and deferred until mw.user is available
2910 $embedScripts = array( 'user.options', 'user.tokens' );
2911 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2913 // Scripts and messages "only" requests marked for top inclusion
2914 // Messages should go first
2915 $links[] = $this->makeResourceLoaderLink(
2916 $this->getModuleMessages( true, 'top' ),
2917 ResourceLoaderModule
::TYPE_MESSAGES
2919 $links[] = $this->makeResourceLoaderLink(
2920 $this->getModuleScripts( true, 'top' ),
2921 ResourceLoaderModule
::TYPE_SCRIPTS
2924 // Modules requests - let the client calculate dependencies and batch requests as it likes
2925 // Only load modules that have marked themselves for loading at the top
2926 $modules = $this->getModules( true, 'top' );
2928 $links[] = Html
::inlineScript(
2929 ResourceLoader
::makeLoaderConditionalScript(
2930 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2935 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2936 $links[] = $this->getScriptsForBottomQueue( true );
2939 return self
::getHtmlFromLoaderLinks( $links );
2943 * JS stuff to put at the 'bottom', which can either be the bottom of the
2944 * "<body>" or the bottom of the "<head>" depending on
2945 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2946 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2949 * @param bool $inHead If true, this HTML goes into the "<head>",
2950 * if false it goes into the "<body>".
2953 function getScriptsForBottomQueue( $inHead ) {
2954 global $wgUseSiteJs, $wgAllowUserJs;
2956 // Scripts and messages "only" requests marked for bottom inclusion
2957 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2958 // Messages should go first
2960 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2961 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2962 /* $loadCall = */ $inHead
2964 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2965 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2966 /* $loadCall = */ $inHead
2969 // Modules requests - let the client calculate dependencies and batch requests as it likes
2970 // Only load modules that have marked themselves for loading at the bottom
2971 $modules = $this->getModules( true, 'bottom' );
2973 $links[] = Html
::inlineScript(
2974 ResourceLoader
::makeLoaderConditionalScript(
2975 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2981 $links[] = "\n" . $this->mScripts
;
2983 // Add site JS if enabled
2984 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2985 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2988 // Add user JS if enabled
2990 && $this->getUser()->isLoggedIn()
2991 && $this->getTitle()
2992 && $this->getTitle()->isJsSubpage()
2993 && $this->userCanPreview()
2995 # XXX: additional security check/prompt?
2996 // We're on a preview of a JS subpage
2997 // Exclude this page from the user module in case it's in there (bug 26283)
2998 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
2999 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3001 // Load the previewed JS
3002 $links[] = Html
::inlineScript( "\n"
3003 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3005 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3006 // asynchronously and may arrive *after* the inline script here. So the previewed code
3007 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3009 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3010 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3011 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3015 // Group JS is only enabled if site JS is enabled.
3016 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3017 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3020 return self
::getHtmlFromLoaderLinks( $links );
3024 * JS stuff to put at the bottom of the "<body>"
3027 function getBottomScripts() {
3028 global $wgResourceLoaderExperimentalAsyncLoading;
3030 // Optimise jQuery ready event cross-browser.
3031 // This also enforces $.isReady to be true at </body> which fixes the
3032 // mw.loader bug in Firefox with using document.write between </body>
3033 // and the DOMContentReady event (bug 47457).
3034 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3036 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
3037 $html .= $this->getScriptsForBottomQueue( false );
3044 * Get the javascript config vars to include on this page
3046 * @return array Array of javascript config vars
3049 public function getJsConfigVars() {
3050 return $this->mJsConfigVars
;
3054 * Add one or more variables to be set in mw.config in JavaScript
3056 * @param string|array $keys Key or array of key/value pairs
3057 * @param mixed $value [optional] Value of the configuration variable
3059 public function addJsConfigVars( $keys, $value = null ) {
3060 if ( is_array( $keys ) ) {
3061 foreach ( $keys as $key => $value ) {
3062 $this->mJsConfigVars
[$key] = $value;
3067 $this->mJsConfigVars
[$keys] = $value;
3071 * Get an array containing the variables to be set in mw.config in JavaScript.
3073 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
3074 * This is only public until that function is removed. You have been warned.
3076 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3077 * - in other words, page-independent/site-wide variables (without state).
3078 * You will only be adding bloat to the html page and causing page caches to
3079 * have to be purged on configuration changes.
3082 public function getJSVars() {
3087 $canonicalSpecialPageName = false; # bug 21115
3089 $title = $this->getTitle();
3090 $ns = $title->getNamespace();
3091 $canonicalNamespace = MWNamespace
::exists( $ns )
3092 ? MWNamespace
::getCanonicalName( $ns )
3093 : $title->getNsText();
3095 $sk = $this->getSkin();
3096 // Get the relevant title so that AJAX features can use the correct page name
3097 // when making API requests from certain special pages (bug 34972).
3098 $relevantTitle = $sk->getRelevantTitle();
3099 $relevantUser = $sk->getRelevantUser();
3101 if ( $ns == NS_SPECIAL
) {
3102 list( $canonicalSpecialPageName, /*...*/ ) =
3103 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3104 } elseif ( $this->canUseWikiPage() ) {
3105 $wikiPage = $this->getWikiPage();
3106 $curRevisionId = $wikiPage->getLatest();
3107 $articleId = $wikiPage->getId();
3110 $lang = $title->getPageLanguage();
3112 // Pre-process information
3113 $separatorTransTable = $lang->separatorTransformTable();
3114 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3115 $compactSeparatorTransTable = array(
3116 implode( "\t", array_keys( $separatorTransTable ) ),
3117 implode( "\t", $separatorTransTable ),
3119 $digitTransTable = $lang->digitTransformTable();
3120 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3121 $compactDigitTransTable = array(
3122 implode( "\t", array_keys( $digitTransTable ) ),
3123 implode( "\t", $digitTransTable ),
3126 $user = $this->getUser();
3129 'wgCanonicalNamespace' => $canonicalNamespace,
3130 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3131 'wgNamespaceNumber' => $title->getNamespace(),
3132 'wgPageName' => $title->getPrefixedDBkey(),
3133 'wgTitle' => $title->getText(),
3134 'wgCurRevisionId' => $curRevisionId,
3135 'wgRevisionId' => (int)$this->getRevisionId(),
3136 'wgArticleId' => $articleId,
3137 'wgIsArticle' => $this->isArticle(),
3138 'wgIsRedirect' => $title->isRedirect(),
3139 'wgAction' => Action
::getActionName( $this->getContext() ),
3140 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3141 'wgUserGroups' => $user->getEffectiveGroups(),
3142 'wgCategories' => $this->getCategories(),
3143 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3144 'wgPageContentLanguage' => $lang->getCode(),
3145 'wgPageContentModel' => $title->getContentModel(),
3146 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3147 'wgDigitTransformTable' => $compactDigitTransTable,
3148 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3149 'wgMonthNames' => $lang->getMonthNamesArray(),
3150 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3151 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3154 if ( $user->isLoggedIn() ) {
3155 $vars['wgUserId'] = $user->getId();
3156 $vars['wgUserEditCount'] = $user->getEditCount();
3157 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3158 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3159 // Get the revision ID of the oldest new message on the user's talk
3160 // page. This can be used for constructing new message alerts on
3162 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3165 if ( $wgContLang->hasVariants() ) {
3166 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3168 // Same test as SkinTemplate
3169 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3170 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3172 foreach ( $title->getRestrictionTypes() as $type ) {
3173 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3176 if ( $title->isMainPage() ) {
3177 $vars['wgIsMainPage'] = true;
3180 if ( $this->mRedirectedFrom
) {
3181 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3184 if ( $relevantUser ) {
3185 $vars['wgRelevantUserName'] = $relevantUser->getName();
3188 // Allow extensions to add their custom variables to the mw.config map.
3189 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3190 // page-dependant but site-wide (without state).
3191 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3192 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3194 // Merge in variables from addJsConfigVars last
3195 return array_merge( $vars, $this->getJsConfigVars() );
3199 * To make it harder for someone to slip a user a fake
3200 * user-JavaScript or user-CSS preview, a random token
3201 * is associated with the login session. If it's not
3202 * passed back with the preview request, we won't render
3207 public function userCanPreview() {
3208 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3209 ||
!$this->getRequest()->wasPosted()
3210 ||
!$this->getUser()->matchEditToken(
3211 $this->getRequest()->getVal( 'wpEditToken' ) )
3215 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3219 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3223 * @return array in format "link name or number => 'link html'".
3225 public function getHeadLinksArray() {
3226 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3227 $wgSitename, $wgVersion,
3228 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3229 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3230 $wgRightsPage, $wgRightsUrl;
3234 $canonicalUrl = $this->mCanonicalUrl
;
3236 $tags['meta-generator'] = Html
::element( 'meta', array(
3237 'name' => 'generator',
3238 'content' => "MediaWiki $wgVersion",
3241 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3242 if ( $p !== 'index,follow' ) {
3243 // http://www.robotstxt.org/wc/meta-user.html
3244 // Only show if it's different from the default robots policy
3245 $tags['meta-robots'] = Html
::element( 'meta', array(
3251 foreach ( $this->mMetatags
as $tag ) {
3252 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3254 $tag[0] = substr( $tag[0], 5 );
3258 $tagName = "meta-{$tag[0]}";
3259 if ( isset( $tags[$tagName] ) ) {
3260 $tagName .= $tag[1];
3262 $tags[$tagName] = Html
::element( 'meta',
3265 'content' => $tag[1]
3270 foreach ( $this->mLinktags
as $tag ) {
3271 $tags[] = Html
::element( 'link', $tag );
3274 # Universal edit button
3275 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3276 $user = $this->getUser();
3277 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3278 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3279 // Original UniversalEditButton
3280 $msg = $this->msg( 'edit' )->text();
3281 $tags['universal-edit-button'] = Html
::element( 'link', array(
3282 'rel' => 'alternate',
3283 'type' => 'application/x-wiki',
3285 'href' => $this->getTitle()->getEditURL(),
3287 // Alternate edit link
3288 $tags['alternative-edit'] = Html
::element( 'link', array(
3291 'href' => $this->getTitle()->getEditURL(),
3296 # Generally the order of the favicon and apple-touch-icon links
3297 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3298 # uses whichever one appears later in the HTML source. Make sure
3299 # apple-touch-icon is specified first to avoid this.
3300 if ( $wgAppleTouchIcon !== false ) {
3301 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3302 'rel' => 'apple-touch-icon',
3303 'href' => $wgAppleTouchIcon
3307 if ( $wgFavicon !== false ) {
3308 $tags['favicon'] = Html
::element( 'link', array(
3309 'rel' => 'shortcut icon',
3310 'href' => $wgFavicon
3314 # OpenSearch description link
3315 $tags['opensearch'] = Html
::element( 'link', array(
3317 'type' => 'application/opensearchdescription+xml',
3318 'href' => wfScript( 'opensearch_desc' ),
3319 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3322 if ( $wgEnableAPI ) {
3323 # Real Simple Discovery link, provides auto-discovery information
3324 # for the MediaWiki API (and potentially additional custom API
3325 # support such as WordPress or Twitter-compatible APIs for a
3326 # blogging extension, etc)
3327 $tags['rsd'] = Html
::element( 'link', array(
3329 'type' => 'application/rsd+xml',
3330 // Output a protocol-relative URL here if $wgServer is protocol-relative
3331 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3332 'href' => wfExpandUrl( wfAppendQuery(
3334 array( 'action' => 'rsd' ) ),
3341 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3342 $lang = $this->getTitle()->getPageLanguage();
3343 if ( $lang->hasVariants() ) {
3345 $urlvar = $lang->getURLVariant();
3348 $variants = $lang->getVariants();
3349 foreach ( $variants as $_v ) {
3350 $tags["variant-$_v"] = Html
::element( 'link', array(
3351 'rel' => 'alternate',
3352 'hreflang' => wfBCP47( $_v ),
3353 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3357 $canonicalUrl = $this->getTitle()->getLocalURL();
3364 if ( $wgRightsPage ) {
3365 $copy = Title
::newFromText( $wgRightsPage );
3368 $copyright = $copy->getLocalURL();
3372 if ( !$copyright && $wgRightsUrl ) {
3373 $copyright = $wgRightsUrl;
3377 $tags['copyright'] = Html
::element( 'link', array(
3378 'rel' => 'copyright',
3379 'href' => $copyright )
3385 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3386 # Use the page name for the title. In principle, this could
3387 # lead to issues with having the same name for different feeds
3388 # corresponding to the same page, but we can't avoid that at
3391 $tags[] = $this->feedLink(
3394 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3395 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3399 # Recent changes feed should appear on every page (except recentchanges,
3400 # that would be redundant). Put it after the per-page feed to avoid
3401 # changing existing behavior. It's still available, probably via a
3402 # menu in your browser. Some sites might have a different feed they'd
3403 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3404 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3405 # If so, use it instead.
3406 if ( $wgOverrideSiteFeed ) {
3407 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3408 // Note, this->feedLink escapes the url.
3409 $tags[] = $this->feedLink(
3412 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3415 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3416 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3417 foreach ( $wgAdvertisedFeedTypes as $format ) {
3418 $tags[] = $this->feedLink(
3420 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3421 # For grep: 'site-rss-feed', 'site-atom-feed'
3422 $this->msg( "site-{$format}-feed", $wgSitename )->text()
3429 global $wgEnableCanonicalServerLink;
3430 if ( $wgEnableCanonicalServerLink ) {
3431 if ( $canonicalUrl !== false ) {
3432 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3434 $reqUrl = $this->getRequest()->getRequestURL();
3435 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3438 if ( $canonicalUrl !== false ) {
3439 $tags[] = Html
::element( 'link', array(
3440 'rel' => 'canonical',
3441 'href' => $canonicalUrl
3449 * @return string HTML tag links to be put in the header.
3450 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3451 * OutputPage::getHeadLinksArray directly.
3453 public function getHeadLinks() {
3454 wfDeprecated( __METHOD__
, '1.24' );
3455 return implode( "\n", $this->getHeadLinksArray() );
3459 * Generate a "<link rel/>" for a feed.
3461 * @param string $type Feed type
3462 * @param string $url URL to the feed
3463 * @param string $text Value of the "title" attribute
3464 * @return string HTML fragment
3466 private function feedLink( $type, $url, $text ) {
3467 return Html
::element( 'link', array(
3468 'rel' => 'alternate',
3469 'type' => "application/$type+xml",
3476 * Add a local or specified stylesheet, with the given media options.
3477 * Meant primarily for internal use...
3479 * @param string $style URL to the file
3480 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3481 * @param string $condition for IE conditional comments, specifying an IE version
3482 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3484 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3486 // Even though we expect the media type to be lowercase, but here we
3487 // force it to lowercase to be safe.
3489 $options['media'] = $media;
3492 $options['condition'] = $condition;
3495 $options['dir'] = $dir;
3497 $this->styles
[$style] = $options;
3501 * Adds inline CSS styles
3502 * @param mixed $style_css Inline CSS
3503 * @param string $flip Set to 'flip' to flip the CSS if needed
3505 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3506 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3507 # If wanted, and the interface is right-to-left, flip the CSS
3508 $style_css = CSSJanus
::transform( $style_css, true, false );
3510 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3514 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3515 * These will be applied to various media & IE conditionals.
3519 public function buildCssLinks() {
3520 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3522 $this->getSkin()->setupSkinUserCss( $this );
3524 // Add ResourceLoader styles
3525 // Split the styles into these groups
3530 'private' => array(),
3531 'noscript' => array()
3534 $otherTags = ''; // Tags to append after the normal <link> tags
3535 $resourceLoader = $this->getResourceLoader();
3537 $moduleStyles = $this->getModuleStyles();
3539 // Per-site custom styles
3540 $moduleStyles[] = 'site';
3541 $moduleStyles[] = 'noscript';
3542 $moduleStyles[] = 'user.groups';
3544 // Per-user custom styles
3545 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3546 // We're on a preview of a CSS subpage
3547 // Exclude this page from the user module in case it's in there (bug 26283)
3548 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3549 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3551 $otherTags .= $link['html'];
3553 // Load the previewed CSS
3554 // If needed, Janus it first. This is user-supplied CSS, so it's
3555 // assumed to be right for the content language directionality.
3556 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3557 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3558 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3560 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3562 // Load the user styles normally
3563 $moduleStyles[] = 'user';
3566 // Per-user preference styles
3567 $moduleStyles[] = 'user.cssprefs';
3569 foreach ( $moduleStyles as $name ) {
3570 $module = $resourceLoader->getModule( $name );
3574 $group = $module->getGroup();
3575 // Modules in groups different than the ones listed on top (see $styles assignment)
3576 // will be placed in the "other" group
3577 $styles[ isset( $styles[$group] ) ?
$group : 'other' ][] = $name;
3580 // We want site, private and user styles to override dynamically added
3581 // styles from modules, but we want dynamically added styles to override
3582 // statically added styles from other modules. So the order has to be
3583 // other, dynamic, site, private, user. Add statically added styles for
3585 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3586 // Add normal styles added through addStyle()/addInlineStyle() here
3587 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3588 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3589 // We use a <meta> tag with a made-up name for this because that's valid HTML
3590 $links[] = Html
::element(
3592 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3595 // Add site, private and user styles
3596 // 'private' at present only contains user.options, so put that before 'user'
3597 // Any future private modules will likely have a similar user-specific character
3598 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3599 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3600 ResourceLoaderModule
::TYPE_STYLES
3604 // Add stuff in $otherTags (previewed user CSS if applicable)
3605 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3611 public function buildCssLinksArray() {
3614 // Add any extension CSS
3615 foreach ( $this->mExtStyles
as $url ) {
3616 $this->addStyle( $url );
3618 $this->mExtStyles
= array();
3620 foreach ( $this->styles
as $file => $options ) {
3621 $link = $this->styleLink( $file, $options );
3623 $links[$file] = $link;
3630 * Generate \<link\> tags for stylesheets
3632 * @param string $style URL to the file
3633 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3634 * @return string HTML fragment
3636 protected function styleLink( $style, $options ) {
3637 if ( isset( $options['dir'] ) ) {
3638 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3643 if ( isset( $options['media'] ) ) {
3644 $media = self
::transformCssMedia( $options['media'] );
3645 if ( is_null( $media ) ) {
3652 if ( substr( $style, 0, 1 ) == '/' ||
3653 substr( $style, 0, 5 ) == 'http:' ||
3654 substr( $style, 0, 6 ) == 'https:' ) {
3657 global $wgStylePath, $wgStyleVersion;
3658 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3661 $link = Html
::linkedStyle( $url, $media );
3663 if ( isset( $options['condition'] ) ) {
3664 $condition = htmlspecialchars( $options['condition'] );
3665 $link = "<!--[if $condition]>$link<![endif]-->";
3671 * Transform "media" attribute based on request parameters
3673 * @param string $media Current value of the "media" attribute
3674 * @return string Modified value of the "media" attribute, or null to skip
3677 public static function transformCssMedia( $media ) {
3680 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3681 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3683 // Switch in on-screen display for media testing
3685 'printable' => 'print',
3686 'handheld' => 'handheld',
3688 foreach ( $switches as $switch => $targetMedia ) {
3689 if ( $wgRequest->getBool( $switch ) ) {
3690 if ( $media == $targetMedia ) {
3692 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3693 // This regex will not attempt to understand a comma-separated media_query_list
3695 // Example supported values for $media:
3696 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3697 // Example NOT supported value for $media:
3698 // '3d-glasses, screen, print and resolution > 90dpi'
3700 // If it's a print request, we never want any kind of screen stylesheets
3701 // If it's a handheld request (currently the only other choice with a switch),
3702 // we don't want simple 'screen' but we might want screen queries that
3703 // have a max-width or something, so we'll pass all others on and let the
3704 // client do the query.
3705 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3716 * Add a wikitext-formatted message to the output.
3717 * This is equivalent to:
3719 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3721 public function addWikiMsg( /*...*/ ) {
3722 $args = func_get_args();
3723 $name = array_shift( $args );
3724 $this->addWikiMsgArray( $name, $args );
3728 * Add a wikitext-formatted message to the output.
3729 * Like addWikiMsg() except the parameters are taken as an array
3730 * instead of a variable argument list.
3732 * @param string $name
3733 * @param array $args
3735 public function addWikiMsgArray( $name, $args ) {
3736 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3740 * This function takes a number of message/argument specifications, wraps them in
3741 * some overall structure, and then parses the result and adds it to the output.
3743 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3744 * on. The subsequent arguments may either be strings, in which case they are the
3745 * message names, or arrays, in which case the first element is the message name,
3746 * and subsequent elements are the parameters to that message.
3748 * Don't use this for messages that are not in users interface language.
3752 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3756 * $wgOut->addWikiText( "<div class='error'>\n"
3757 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3759 * The newline after opening div is needed in some wikitext. See bug 19226.
3761 * @param string $wrap
3763 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3764 $msgSpecs = func_get_args();
3765 array_shift( $msgSpecs );
3766 $msgSpecs = array_values( $msgSpecs );
3768 foreach ( $msgSpecs as $n => $spec ) {
3769 if ( is_array( $spec ) ) {
3771 $name = array_shift( $args );
3772 if ( isset( $args['options'] ) ) {
3773 unset( $args['options'] );
3775 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3783 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3785 $this->addWikiText( $s );
3789 * Include jQuery core. Use this to avoid loading it multiple times
3790 * before we get a usable script loader.
3792 * @param array $modules List of jQuery modules which should be loaded
3793 * @return array The list of modules which were not loaded.
3795 * @deprecated since 1.17
3797 public function includeJQuery( $modules = array() ) {
3802 * Enables/disables TOC, doesn't override __NOTOC__
3806 public function enableTOC( $flag = true ) {
3807 $this->mEnableTOC
= $flag;
3814 public function isTOCEnabled() {
3815 return $this->mEnableTOC
;
3819 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3823 public function enableSectionEditLinks( $flag = true ) {
3824 $this->mEnableSectionEditLinks
= $flag;
3831 public function sectionEditLinksEnabled() {
3832 return $this->mEnableSectionEditLinks
;