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 Variable 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();
126 protected $mIndicators = array();
128 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
129 private $mLanguageLinks = array();
132 * Used for JavaScript (pre resource loader)
133 * @todo We should split JS / CSS.
134 * mScripts content is inserted as is in "<head>" by Skin. This might
135 * contain either a link to a stylesheet or inline CSS.
137 private $mScripts = '';
139 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
140 protected $mInlineStyles = '';
143 private $mLinkColours;
146 * @var string Used by skin template.
147 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
149 public $mPageLinkTitle = '';
151 /** @var array Array of elements in "<head>". Parser might add its own headers! */
152 protected $mHeadItems = array();
154 // @todo FIXME: Next 5 variables probably come from the resource loader
157 protected $mModules = array();
160 protected $mModuleScripts = array();
163 protected $mModuleStyles = array();
166 protected $mModuleMessages = array();
168 /** @var ResourceLoader */
169 protected $mResourceLoader;
172 protected $mJsConfigVars = array();
175 protected $mTemplateIds = array();
178 protected $mImageTimeKeys = array();
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = array(
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
203 private $mContainsOldMagic = 0;
206 protected $mContainsNewMagic = 0;
209 * lazy initialised, use parserOptions()
212 protected $mParserOptions = null;
215 * Handles the Atom / RSS links.
216 * We probably only support Atom in 2011.
217 * @see $wgAdvertisedFeedTypes
219 private $mFeedLinks = array();
221 // Gwicke work on squid caching? Roughly from 2003.
222 protected $mEnableClientCache = true;
224 /** @var bool Flag if output should only contain the body of the article. */
225 private $mArticleBodyOnly = false;
228 protected $mNewSectionLink = false;
231 protected $mHideNewSectionLink = false;
234 * @var bool Comes from the parser. This was probably made to load CSS/JS
235 * only if we had "<gallery>". Used directly in CategoryPage.php.
236 * Looks like resource loader can replace this.
238 public $mNoGallery = false;
241 private $mPageTitleActionText = '';
244 private $mParseWarnings = array();
246 /** @var int Cache stuff. Looks like mEnableClientCache */
247 protected $mSquidMaxage = 0;
250 * @var bool Controls if anti-clickjacking / frame-breaking headers will
251 * be sent. This should be done for pages where edit actions are possible.
252 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
254 protected $mPreventClickjacking = true;
256 /** @var int To include the variable {{REVISIONID}} */
257 private $mRevisionId = null;
260 private $mRevisionTimestamp = null;
263 protected $mFileVersion = null;
266 * @var array An array of stylesheet filenames (relative from skins path),
267 * with options for CSS media, IE conditions, and RTL/LTR direction.
268 * For internal use; add settings in the skin via $this->addStyle()
270 * Style again! This seems like a code duplication since we already have
271 * mStyles. This is what makes Open Source amazing.
273 protected $styles = array();
276 * Whether jQuery is already handled.
278 protected $mJQueryDone = false;
280 private $mIndexPolicy = 'index';
281 private $mFollowPolicy = 'follow';
282 private $mVaryHeader = array(
283 'Accept-Encoding' => array( 'list-contains=gzip' ),
287 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
292 private $mRedirectedFrom = null;
295 * Additional key => value data
297 private $mProperties = array();
300 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
302 private $mTarget = null;
305 * @var bool Whether parser output should contain table of contents
307 private $mEnableTOC = true;
310 * @var bool Whether parser output should contain section edit links
312 private $mEnableSectionEditLinks = true;
315 * Constructor for OutputPage. This should not be called directly.
316 * Instead a new RequestContext should be created and it will implicitly create
317 * a OutputPage tied to that context.
318 * @param IContextSource|null $context
320 function __construct( IContextSource
$context = null ) {
321 if ( $context === null ) {
322 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
323 wfDeprecated( __METHOD__
, '1.18' );
325 $this->setContext( $context );
330 * Redirect to $url rather than displaying the normal page
332 * @param string $url URL
333 * @param string $responsecode HTTP status code
335 public function redirect( $url, $responsecode = '302' ) {
336 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
337 $this->mRedirect
= str_replace( "\n", '', $url );
338 $this->mRedirectCode
= $responsecode;
342 * Get the URL to redirect to, or an empty string if not redirect URL set
346 public function getRedirect() {
347 return $this->mRedirect
;
351 * Set the HTTP status code to send with the output.
353 * @param int $statusCode
355 public function setStatusCode( $statusCode ) {
356 $this->mStatusCode
= $statusCode;
360 * Add a new "<meta>" tag
361 * To add an http-equiv meta tag, precede the name with "http:"
363 * @param string $name Tag name
364 * @param string $val Tag value
366 function addMeta( $name, $val ) {
367 array_push( $this->mMetatags
, array( $name, $val ) );
371 * Returns the current <meta> tags
376 public function getMetaTags() {
377 return $this->mMetatags
;
381 * Add a new \<link\> tag to the page header.
383 * Note: use setCanonicalUrl() for rel=canonical.
385 * @param array $linkarr Associative array of attributes.
387 function addLink( array $linkarr ) {
388 array_push( $this->mLinktags
, $linkarr );
392 * Returns the current <link> tags
397 public function getLinkTags() {
398 return $this->mLinktags
;
402 * Add a new \<link\> with "rel" attribute set to "meta"
404 * @param array $linkarr Associative array mapping attribute names to their
405 * values, both keys and values will be escaped, and the
406 * "rel" attribute will be automatically added
408 function addMetadataLink( array $linkarr ) {
409 $linkarr['rel'] = $this->getMetadataAttribute();
410 $this->addLink( $linkarr );
414 * Set the URL to be used for the <link rel=canonical>. This should be used
415 * in preference to addLink(), to avoid duplicate link tags.
418 function setCanonicalUrl( $url ) {
419 $this->mCanonicalUrl
= $url;
423 * Returns the URL to be used for the <link rel=canonical> if
427 * @return bool|string
429 public function getCanonicalUrl() {
430 return $this->mCanonicalUrl
;
434 * Get the value of the "rel" attribute for metadata links
438 public function getMetadataAttribute() {
439 # note: buggy CC software only reads first "meta" link
440 static $haveMeta = false;
442 return 'alternate meta';
450 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
452 * @param string $script Raw HTML
454 function addScript( $script ) {
455 $this->mScripts
.= $script . "\n";
459 * Register and add a stylesheet from an extension directory.
461 * @param string $url Path to sheet. Provide either a full url (beginning
462 * with 'http', etc) or a relative path from the document root
463 * (beginning with '/'). Otherwise it behaves identically to
464 * addStyle() and draws from the /skins folder.
466 public function addExtensionStyle( $url ) {
467 array_push( $this->mExtStyles
, $url );
471 * Get all styles added by extensions
475 function getExtStyle() {
476 return $this->mExtStyles
;
480 * Add a JavaScript file out of skins/common, or a given relative path.
482 * @param string $file Filename in skins/common or complete on-server path
484 * @param string $version Style version of the file. Defaults to $wgStyleVersion
486 public function addScriptFile( $file, $version = null ) {
487 // See if $file parameter is an absolute URL or begins with a slash
488 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
491 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
493 if ( is_null( $version ) ) {
494 $version = $this->getConfig()->get( 'StyleVersion' );
496 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
500 * Add a self-contained script tag with the given contents
502 * @param string $script JavaScript text, no "<script>" tags
504 public function addInlineScript( $script ) {
505 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
509 * Get all registered JS and CSS tags for the header.
512 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
514 function getScript() {
515 wfDeprecated( __METHOD__
, '1.24' );
516 return $this->mScripts
. $this->getHeadItems();
520 * Filter an array of modules to remove insufficiently trustworthy members, and modules
521 * which are no longer registered (eg a page is cached before an extension is disabled)
522 * @param array $modules
523 * @param string|null $position If not null, only return modules with this position
524 * @param string $type
527 protected function filterModules( array $modules, $position = null,
528 $type = ResourceLoaderModule
::TYPE_COMBINED
530 $resourceLoader = $this->getResourceLoader();
531 $filteredModules = array();
532 foreach ( $modules as $val ) {
533 $module = $resourceLoader->getModule( $val );
534 if ( $module instanceof ResourceLoaderModule
535 && $module->getOrigin() <= $this->getAllowedModules( $type )
536 && ( is_null( $position ) ||
$module->getPosition() == $position )
537 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
539 $filteredModules[] = $val;
542 return $filteredModules;
546 * Get the list of modules to include on this page
548 * @param bool $filter Whether to filter out insufficiently trustworthy modules
549 * @param string|null $position If not null, only return modules with this position
550 * @param string $param
551 * @return array Array of module names
553 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
554 $modules = array_values( array_unique( $this->$param ) );
556 ?
$this->filterModules( $modules, $position )
561 * Add one or more modules recognized by the resource loader. Modules added
562 * through this function will be loaded by the resource loader when the
565 * @param string|array $modules Module name (string) or array of module names
567 public function addModules( $modules ) {
568 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
572 * Get the list of module JS to include on this page
574 * @param bool $filter
575 * @param string|null $position
577 * @return array Array of module names
579 public function getModuleScripts( $filter = false, $position = null ) {
580 return $this->getModules( $filter, $position, 'mModuleScripts' );
584 * Add only JS of one or more modules recognized by the resource loader. Module
585 * scripts added through this function will be loaded by the resource loader when
588 * @param string|array $modules Module name (string) or array of module names
590 public function addModuleScripts( $modules ) {
591 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
595 * Get the list of module CSS to include on this page
597 * @param bool $filter
598 * @param string|null $position
600 * @return array Array of module names
602 public function getModuleStyles( $filter = false, $position = null ) {
603 return $this->getModules( $filter, $position, 'mModuleStyles' );
607 * Add only CSS of one or more modules recognized by the resource loader.
609 * Module styles added through this function will be added using standard link CSS
610 * tags, rather than as a combined Javascript and CSS package. Thus, they will
611 * load when JavaScript is disabled (unless CSS also happens to be disabled).
613 * @param string|array $modules Module name (string) or array of module names
615 public function addModuleStyles( $modules ) {
616 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
620 * Get the list of module messages to include on this page
622 * @param bool $filter
623 * @param string|null $position
625 * @return array Array of module names
627 public function getModuleMessages( $filter = false, $position = null ) {
628 return $this->getModules( $filter, $position, 'mModuleMessages' );
632 * Add only messages of one or more modules recognized by the resource loader.
633 * Module messages added through this function will be loaded by the resource
634 * loader when the page loads.
636 * @param string|array $modules Module name (string) or array of module names
638 public function addModuleMessages( $modules ) {
639 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
643 * @return null|string ResourceLoader target
645 public function getTarget() {
646 return $this->mTarget
;
650 * Sets ResourceLoader target for load.php links. If null, will be omitted
652 * @param string|null $target
654 public function setTarget( $target ) {
655 $this->mTarget
= $target;
659 * Get an array of head items
663 function getHeadItemsArray() {
664 return $this->mHeadItems
;
668 * Get all header items in a string
671 * @deprecated since 1.24 Use OutputPage::headElement or
672 * if absolutely necessary use OutputPage::getHeadItemsArray
674 function getHeadItems() {
675 wfDeprecated( __METHOD__
, '1.24' );
677 foreach ( $this->mHeadItems
as $item ) {
684 * Add or replace an header item to the output
686 * @param string $name Item name
687 * @param string $value Raw HTML
689 public function addHeadItem( $name, $value ) {
690 $this->mHeadItems
[$name] = $value;
694 * Check if the header item $name is already set
696 * @param string $name Item name
699 public function hasHeadItem( $name ) {
700 return isset( $this->mHeadItems
[$name] );
704 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
706 * @param string $tag Value of "ETag" header
708 function setETag( $tag ) {
713 * Set whether the output should only contain the body of the article,
714 * without any skin, sidebar, etc.
715 * Used e.g. when calling with "action=render".
717 * @param bool $only Whether to output only the body of the article
719 public function setArticleBodyOnly( $only ) {
720 $this->mArticleBodyOnly
= $only;
724 * Return whether the output will contain only the body of the article
728 public function getArticleBodyOnly() {
729 return $this->mArticleBodyOnly
;
733 * Set an additional output property
736 * @param string $name
737 * @param mixed $value
739 public function setProperty( $name, $value ) {
740 $this->mProperties
[$name] = $value;
744 * Get an additional output property
747 * @param string $name
748 * @return mixed Property value or null if not found
750 public function getProperty( $name ) {
751 if ( isset( $this->mProperties
[$name] ) ) {
752 return $this->mProperties
[$name];
759 * checkLastModified tells the client to use the client-cached page if
760 * possible. If successful, the OutputPage is disabled so that
761 * any future call to OutputPage->output() have no effect.
763 * Side effect: sets mLastModified for Last-Modified header
765 * @param string $timestamp
767 * @return bool True if cache-ok headers was sent.
769 public function checkLastModified( $timestamp ) {
770 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
771 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
774 $config = $this->getConfig();
775 if ( !$config->get( 'CachePages' ) ) {
776 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
780 $timestamp = wfTimestamp( TS_MW
, $timestamp );
781 $modifiedTimes = array(
782 'page' => $timestamp,
783 'user' => $this->getUser()->getTouched(),
784 'epoch' => $config->get( 'CacheEpoch' )
786 if ( $config->get( 'UseSquid' ) ) {
787 // bug 44570: the core page itself may not change, but resources might
788 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
790 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
792 $maxModified = max( $modifiedTimes );
793 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
795 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
796 if ( $clientHeader === false ) {
797 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
801 # IE sends sizes after the date like this:
802 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
803 # this breaks strtotime().
804 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
806 wfSuppressWarnings(); // E_STRICT system time bitching
807 $clientHeaderTime = strtotime( $clientHeader );
809 if ( !$clientHeaderTime ) {
811 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
814 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
818 foreach ( $modifiedTimes as $name => $value ) {
819 if ( $info !== '' ) {
822 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
825 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
826 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
827 wfDebug( __METHOD__
. ": effective Last-Modified: " .
828 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
829 if ( $clientHeaderTime < $maxModified ) {
830 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
835 # Give a 304 response code and disable body output
836 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
837 ini_set( 'zlib.output_compression', 0 );
838 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
839 $this->sendCacheControl();
842 // Don't output a compressed blob when using ob_gzhandler;
843 // it's technically against HTTP spec and seems to confuse
844 // Firefox when the response gets split over two packets.
845 wfClearOutputBuffers();
851 * Override the last modified timestamp
853 * @param string $timestamp New timestamp, in a format readable by
856 public function setLastModified( $timestamp ) {
857 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
861 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
863 * @param string $policy The literal string to output as the contents of
864 * the meta tag. Will be parsed according to the spec and output in
868 public function setRobotPolicy( $policy ) {
869 $policy = Article
::formatRobotPolicy( $policy );
871 if ( isset( $policy['index'] ) ) {
872 $this->setIndexPolicy( $policy['index'] );
874 if ( isset( $policy['follow'] ) ) {
875 $this->setFollowPolicy( $policy['follow'] );
880 * Set the index policy for the page, but leave the follow policy un-
883 * @param string $policy Either 'index' or 'noindex'.
886 public function setIndexPolicy( $policy ) {
887 $policy = trim( $policy );
888 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
889 $this->mIndexPolicy
= $policy;
894 * Set the follow policy for the page, but leave the index policy un-
897 * @param string $policy Either 'follow' or 'nofollow'.
900 public function setFollowPolicy( $policy ) {
901 $policy = trim( $policy );
902 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
903 $this->mFollowPolicy
= $policy;
908 * Set the new value of the "action text", this will be added to the
909 * "HTML title", separated from it with " - ".
911 * @param string $text New value of the "action text"
913 public function setPageTitleActionText( $text ) {
914 $this->mPageTitleActionText
= $text;
918 * Get the value of the "action text"
922 public function getPageTitleActionText() {
923 return $this->mPageTitleActionText
;
927 * "HTML title" means the contents of "<title>".
928 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
930 * @param string|Message $name
932 public function setHTMLTitle( $name ) {
933 if ( $name instanceof Message
) {
934 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
936 $this->mHTMLtitle
= $name;
941 * Return the "HTML title", i.e. the content of the "<title>" tag.
945 public function getHTMLTitle() {
946 return $this->mHTMLtitle
;
950 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
954 public function setRedirectedFrom( $t ) {
955 $this->mRedirectedFrom
= $t;
959 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
960 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
961 * but not bad tags like \<script\>. This function automatically sets
962 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
963 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
964 * good tags like \<i\> will be dropped entirely.
966 * @param string|Message $name
968 public function setPageTitle( $name ) {
969 if ( $name instanceof Message
) {
970 $name = $name->setContext( $this->getContext() )->text();
973 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
974 # but leave "<i>foobar</i>" alone
975 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
976 $this->mPagetitle
= $nameWithTags;
978 # change "<i>foo&bar</i>" to "foo&bar"
980 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
981 ->inContentLanguage()
986 * Return the "page title", i.e. the content of the \<h1\> tag.
990 public function getPageTitle() {
991 return $this->mPagetitle
;
995 * Set the Title object to use
999 public function setTitle( Title
$t ) {
1000 $this->getContext()->setTitle( $t );
1004 * Replace the subtitle with $str
1006 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1008 public function setSubtitle( $str ) {
1009 $this->clearSubtitle();
1010 $this->addSubtitle( $str );
1014 * Add $str to the subtitle
1016 * @deprecated since 1.19; use addSubtitle() instead
1017 * @param string|Message $str String or Message to add to the subtitle
1019 public function appendSubtitle( $str ) {
1020 $this->addSubtitle( $str );
1024 * Add $str to the subtitle
1026 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1028 public function addSubtitle( $str ) {
1029 if ( $str instanceof Message
) {
1030 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1032 $this->mSubtitle
[] = $str;
1037 * Build message object for a subtitle containing a backlink to a page
1039 * @param Title $title Title to link to
1040 * @param array $query Array of additional parameters to include in the link
1044 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1045 if ( $title->isRedirect() ) {
1046 $query['redirect'] = 'no';
1048 return wfMessage( 'backlinksubtitle' )
1049 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1053 * Add a subtitle containing a backlink to a page
1055 * @param Title $title Title to link to
1056 * @param array $query Array of additional parameters to include in the link
1058 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1059 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1063 * Clear the subtitles
1065 public function clearSubtitle() {
1066 $this->mSubtitle
= array();
1074 public function getSubtitle() {
1075 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1079 * Set the page as printable, i.e. it'll be displayed with all
1080 * print styles included
1082 public function setPrintable() {
1083 $this->mPrintable
= true;
1087 * Return whether the page is "printable"
1091 public function isPrintable() {
1092 return $this->mPrintable
;
1096 * Disable output completely, i.e. calling output() will have no effect
1098 public function disable() {
1099 $this->mDoNothing
= true;
1103 * Return whether the output will be completely disabled
1107 public function isDisabled() {
1108 return $this->mDoNothing
;
1112 * Show an "add new section" link?
1116 public function showNewSectionLink() {
1117 return $this->mNewSectionLink
;
1121 * Forcibly hide the new section link?
1125 public function forceHideNewSectionLink() {
1126 return $this->mHideNewSectionLink
;
1130 * Add or remove feed links in the page header
1131 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1132 * for the new version
1133 * @see addFeedLink()
1135 * @param bool $show True: add default feeds, false: remove all feeds
1137 public function setSyndicated( $show = true ) {
1139 $this->setFeedAppendQuery( false );
1141 $this->mFeedLinks
= array();
1146 * Add default feeds to the page header
1147 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1148 * for the new version
1149 * @see addFeedLink()
1151 * @param string $val Query to append to feed links or false to output
1154 public function setFeedAppendQuery( $val ) {
1155 $this->mFeedLinks
= array();
1157 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1158 $query = "feed=$type";
1159 if ( is_string( $val ) ) {
1160 $query .= '&' . $val;
1162 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1167 * Add a feed link to the page header
1169 * @param string $format Feed type, should be a key of $wgFeedClasses
1170 * @param string $href URL
1172 public function addFeedLink( $format, $href ) {
1173 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1174 $this->mFeedLinks
[$format] = $href;
1179 * Should we output feed links for this page?
1182 public function isSyndicated() {
1183 return count( $this->mFeedLinks
) > 0;
1187 * Return URLs for each supported syndication format for this page.
1188 * @return array Associating format keys with URLs
1190 public function getSyndicationLinks() {
1191 return $this->mFeedLinks
;
1195 * Will currently always return null
1199 public function getFeedAppendQuery() {
1200 return $this->mFeedLinksAppendQuery
;
1204 * Set whether the displayed content is related to the source of the
1205 * corresponding article on the wiki
1206 * Setting true will cause the change "article related" toggle to true
1210 public function setArticleFlag( $v ) {
1211 $this->mIsarticle
= $v;
1213 $this->mIsArticleRelated
= $v;
1218 * Return whether the content displayed page is related to the source of
1219 * the corresponding article on the wiki
1223 public function isArticle() {
1224 return $this->mIsarticle
;
1228 * Set whether this page is related an article on the wiki
1229 * Setting false will cause the change of "article flag" toggle to false
1233 public function setArticleRelated( $v ) {
1234 $this->mIsArticleRelated
= $v;
1236 $this->mIsarticle
= false;
1241 * Return whether this page is related an article on the wiki
1245 public function isArticleRelated() {
1246 return $this->mIsArticleRelated
;
1250 * Add new language links
1252 * @param array $newLinkArray Associative array mapping language code to the page
1255 public function addLanguageLinks( array $newLinkArray ) {
1256 $this->mLanguageLinks +
= $newLinkArray;
1260 * Reset the language links and add new language links
1262 * @param array $newLinkArray Associative array mapping language code to the page
1265 public function setLanguageLinks( array $newLinkArray ) {
1266 $this->mLanguageLinks
= $newLinkArray;
1270 * Get the list of language links
1272 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1274 public function getLanguageLinks() {
1275 return $this->mLanguageLinks
;
1279 * Add an array of categories, with names in the keys
1281 * @param array $categories Mapping category name => sort key
1283 public function addCategoryLinks( array $categories ) {
1286 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1290 # Add the links to a LinkBatch
1291 $arr = array( NS_CATEGORY
=> $categories );
1292 $lb = new LinkBatch
;
1293 $lb->setArray( $arr );
1295 # Fetch existence plus the hiddencat property
1296 $dbr = wfGetDB( DB_SLAVE
);
1297 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1298 'page_is_redirect', 'page_latest', 'pp_value' );
1300 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1301 $fields[] = 'page_content_model';
1304 $res = $dbr->select( array( 'page', 'page_props' ),
1306 $lb->constructSet( 'page', $dbr ),
1309 array( 'page_props' => array( 'LEFT JOIN', array(
1310 'pp_propname' => 'hiddencat',
1315 # Add the results to the link cache
1316 $lb->addResultToCache( LinkCache
::singleton(), $res );
1318 # Set all the values to 'normal'.
1319 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1321 # Mark hidden categories
1322 foreach ( $res as $row ) {
1323 if ( isset( $row->pp_value
) ) {
1324 $categories[$row->page_title
] = 'hidden';
1328 # Add the remaining categories to the skin
1330 'OutputPageMakeCategoryLinks',
1331 array( &$this, $categories, &$this->mCategoryLinks
) )
1333 foreach ( $categories as $category => $type ) {
1334 $origcategory = $category;
1335 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1339 $wgContLang->findVariantLink( $category, $title, true );
1340 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1343 $text = $wgContLang->convertHtml( $title->getText() );
1344 $this->mCategories
[] = $title->getText();
1345 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1351 * Reset the category links (but not the category list) and add $categories
1353 * @param array $categories Mapping category name => sort key
1355 public function setCategoryLinks( array $categories ) {
1356 $this->mCategoryLinks
= array();
1357 $this->addCategoryLinks( $categories );
1361 * Get the list of category links, in a 2-D array with the following format:
1362 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1363 * hidden categories) and $link a HTML fragment with a link to the category
1368 public function getCategoryLinks() {
1369 return $this->mCategoryLinks
;
1373 * Get the list of category names this page belongs to
1375 * @return array Array of strings
1377 public function getCategories() {
1378 return $this->mCategories
;
1382 * Add an array of indicators, with their identifiers as array keys and HTML contents as values.
1384 * In case of duplicate keys, existing values are overwritten.
1386 * @param array $indicators
1389 public function setIndicators( array $indicators ) {
1390 $this->mIndicators
= $indicators +
$this->mIndicators
;
1391 // Keep ordered by key
1392 ksort( $this->mIndicators
);
1396 * Get the indicators associated with this page.
1398 * The array will be internally ordered by item keys.
1400 * @return array Keys: identifiers, values: HTML contents
1403 public function getIndicators() {
1404 return $this->mIndicators
;
1408 * Do not allow scripts which can be modified by wiki users to load on this page;
1409 * only allow scripts bundled with, or generated by, the software.
1410 * Site-wide styles are controlled by a config setting, since they can be
1411 * used to create a custom skin/theme, but not user-specific ones.
1413 * @todo this should be given a more accurate name
1415 public function disallowUserJs() {
1416 $this->reduceAllowedModules(
1417 ResourceLoaderModule
::TYPE_SCRIPTS
,
1418 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1421 // Site-wide styles are controlled by a config setting, see bug 71621
1422 // for background on why. User styles are never allowed.
1423 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1424 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1426 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1428 $this->reduceAllowedModules(
1429 ResourceLoaderModule
::TYPE_STYLES
,
1435 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1436 * @see ResourceLoaderModule::$origin
1437 * @param string $type ResourceLoaderModule TYPE_ constant
1438 * @return int ResourceLoaderModule ORIGIN_ class constant
1440 public function getAllowedModules( $type ) {
1441 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1442 return min( array_values( $this->mAllowedModules
) );
1444 return isset( $this->mAllowedModules
[$type] )
1445 ?
$this->mAllowedModules
[$type]
1446 : ResourceLoaderModule
::ORIGIN_ALL
;
1451 * Set the highest level of CSS/JS untrustworthiness allowed
1453 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1454 * Use reduceAllowedModules() instead
1455 * @param string $type ResourceLoaderModule TYPE_ constant
1456 * @param int $level ResourceLoaderModule class constant
1458 public function setAllowedModules( $type, $level ) {
1459 wfDeprecated( __METHOD__
, '1.24' );
1460 $this->reduceAllowedModules( $type, $level );
1464 * Limit the highest level of CSS/JS untrustworthiness allowed.
1466 * If passed the same or a higher level than the current level of untrustworthiness set, the
1467 * level will remain unchanged.
1469 * @param string $type
1470 * @param int $level ResourceLoaderModule class constant
1472 public function reduceAllowedModules( $type, $level ) {
1473 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1477 * Prepend $text to the body HTML
1479 * @param string $text HTML
1481 public function prependHTML( $text ) {
1482 $this->mBodytext
= $text . $this->mBodytext
;
1486 * Append $text to the body HTML
1488 * @param string $text HTML
1490 public function addHTML( $text ) {
1491 $this->mBodytext
.= $text;
1495 * Shortcut for adding an Html::element via addHTML.
1499 * @param string $element
1500 * @param array $attribs
1501 * @param string $contents
1503 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1504 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1508 * Clear the body HTML
1510 public function clearHTML() {
1511 $this->mBodytext
= '';
1517 * @return string HTML
1519 public function getHTML() {
1520 return $this->mBodytext
;
1524 * Get/set the ParserOptions object to use for wikitext parsing
1526 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1527 * current ParserOption object
1528 * @return ParserOptions
1530 public function parserOptions( $options = null ) {
1531 if ( !$this->mParserOptions
) {
1532 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1533 $this->mParserOptions
->setEditSection( false );
1535 return wfSetVar( $this->mParserOptions
, $options );
1539 * Set the revision ID which will be seen by the wiki text parser
1540 * for things such as embedded {{REVISIONID}} variable use.
1542 * @param int|null $revid An positive integer, or null
1543 * @return mixed Previous value
1545 public function setRevisionId( $revid ) {
1546 $val = is_null( $revid ) ?
null : intval( $revid );
1547 return wfSetVar( $this->mRevisionId
, $val );
1551 * Get the displayed revision ID
1555 public function getRevisionId() {
1556 return $this->mRevisionId
;
1560 * Set the timestamp of the revision which will be displayed. This is used
1561 * to avoid a extra DB call in Skin::lastModified().
1563 * @param string|null $timestamp
1564 * @return mixed Previous value
1566 public function setRevisionTimestamp( $timestamp ) {
1567 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1571 * Get the timestamp of displayed revision.
1572 * This will be null if not filled by setRevisionTimestamp().
1574 * @return string|null
1576 public function getRevisionTimestamp() {
1577 return $this->mRevisionTimestamp
;
1581 * Set the displayed file version
1583 * @param File|bool $file
1584 * @return mixed Previous value
1586 public function setFileVersion( $file ) {
1588 if ( $file instanceof File
&& $file->exists() ) {
1589 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1591 return wfSetVar( $this->mFileVersion
, $val, true );
1595 * Get the displayed file version
1597 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1599 public function getFileVersion() {
1600 return $this->mFileVersion
;
1604 * Get the templates used on this page
1606 * @return array (namespace => dbKey => revId)
1609 public function getTemplateIds() {
1610 return $this->mTemplateIds
;
1614 * Get the files used on this page
1616 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1619 public function getFileSearchOptions() {
1620 return $this->mImageTimeKeys
;
1624 * Convert wikitext to HTML and add it to the buffer
1625 * Default assumes that the current page title will be used.
1627 * @param string $text
1628 * @param bool $linestart Is this the start of a line?
1629 * @param bool $interface Is this text in the user interface language?
1630 * @throws MWException
1632 public function addWikiText( $text, $linestart = true, $interface = true ) {
1633 $title = $this->getTitle(); // Work around E_STRICT
1635 throw new MWException( 'Title is null' );
1637 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1641 * Add wikitext with a custom Title object
1643 * @param string $text Wikitext
1644 * @param Title $title
1645 * @param bool $linestart Is this the start of a line?
1647 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1648 $this->addWikiTextTitle( $text, $title, $linestart );
1652 * Add wikitext with a custom Title object and tidy enabled.
1654 * @param string $text Wikitext
1655 * @param Title $title
1656 * @param bool $linestart Is this the start of a line?
1658 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1659 $this->addWikiTextTitle( $text, $title, $linestart, true );
1663 * Add wikitext with tidy enabled
1665 * @param string $text Wikitext
1666 * @param bool $linestart Is this the start of a line?
1668 public function addWikiTextTidy( $text, $linestart = true ) {
1669 $title = $this->getTitle();
1670 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1674 * Add wikitext with a custom Title object
1676 * @param string $text Wikitext
1677 * @param Title $title
1678 * @param bool $linestart Is this the start of a line?
1679 * @param bool $tidy Whether to use tidy
1680 * @param bool $interface Whether it is an interface message
1681 * (for example disables conversion)
1683 public function addWikiTextTitle( $text, Title
$title, $linestart,
1684 $tidy = false, $interface = false
1689 $popts = $this->parserOptions();
1690 $oldTidy = $popts->setTidy( $tidy );
1691 $popts->setInterfaceMessage( (bool)$interface );
1693 $parserOutput = $wgParser->getFreshParser()->parse(
1694 $text, $title, $popts,
1695 $linestart, true, $this->mRevisionId
1698 $popts->setTidy( $oldTidy );
1700 $this->addParserOutput( $parserOutput );
1705 * Add a ParserOutput object, but without Html.
1707 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1708 * @param ParserOutput $parserOutput
1710 public function addParserOutputNoText( $parserOutput ) {
1711 $this->addParserOutputMetadata( $parserOutput );
1715 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1716 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1720 * @param ParserOutput $parserOutput
1722 public function addParserOutputMetadata( $parserOutput ) {
1723 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1724 $this->addCategoryLinks( $parserOutput->getCategories() );
1725 $this->setIndicators( $parserOutput->getIndicators() );
1726 $this->mNewSectionLink
= $parserOutput->getNewSection();
1727 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1729 $this->mParseWarnings
= $parserOutput->getWarnings();
1730 if ( !$parserOutput->isCacheable() ) {
1731 $this->enableClientCache( false );
1733 $this->mNoGallery
= $parserOutput->getNoGallery();
1734 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1735 $this->addModules( $parserOutput->getModules() );
1736 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1737 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1738 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1739 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1740 $this->mPreventClickjacking
= $this->mPreventClickjacking
1741 ||
$parserOutput->preventClickjacking();
1743 // Template versioning...
1744 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1745 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1746 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1748 $this->mTemplateIds
[$ns] = $dbks;
1751 // File versioning...
1752 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1753 $this->mImageTimeKeys
[$dbk] = $data;
1756 // Hooks registered in the object
1757 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1758 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1759 list( $hookName, $data ) = $hookInfo;
1760 if ( isset( $parserOutputHooks[$hookName] ) ) {
1761 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1765 // Link flags are ignored for now, but may in the future be
1766 // used to mark individual language links.
1767 $linkFlags = array();
1768 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1769 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1773 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1774 * ParserOutput object, without any other metadata.
1777 * @param ParserOutput $parserOutput
1779 public function addParserOutputContent( $parserOutput ) {
1780 $this->addParserOutputText( $parserOutput );
1782 $this->addModules( $parserOutput->getModules() );
1783 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1784 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1785 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1787 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1791 * Add the HTML associated with a ParserOutput object, without any metadata.
1794 * @param ParserOutput $parserOutput
1796 public function addParserOutputText( $parserOutput ) {
1797 $text = $parserOutput->getText();
1798 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1799 $this->addHTML( $text );
1803 * Add everything from a ParserOutput object.
1805 * @param ParserOutput $parserOutput
1807 function addParserOutput( $parserOutput ) {
1808 $this->addParserOutputMetadata( $parserOutput );
1809 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1811 // Touch section edit links only if not previously disabled
1812 if ( $parserOutput->getEditSectionTokens() ) {
1813 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1816 $this->addParserOutputText( $parserOutput );
1820 * Add the output of a QuickTemplate to the output buffer
1822 * @param QuickTemplate $template
1824 public function addTemplate( &$template ) {
1825 $this->addHTML( $template->getHTML() );
1829 * Parse wikitext and return the HTML.
1831 * @param string $text
1832 * @param bool $linestart Is this the start of a line?
1833 * @param bool $interface Use interface language ($wgLang instead of
1834 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1835 * This also disables LanguageConverter.
1836 * @param Language $language Target language object, will override $interface
1837 * @throws MWException
1838 * @return string HTML
1840 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1843 if ( is_null( $this->getTitle() ) ) {
1844 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1847 $popts = $this->parserOptions();
1849 $popts->setInterfaceMessage( true );
1851 if ( $language !== null ) {
1852 $oldLang = $popts->setTargetLanguage( $language );
1855 $parserOutput = $wgParser->getFreshParser()->parse(
1856 $text, $this->getTitle(), $popts,
1857 $linestart, true, $this->mRevisionId
1861 $popts->setInterfaceMessage( false );
1863 if ( $language !== null ) {
1864 $popts->setTargetLanguage( $oldLang );
1867 return $parserOutput->getText();
1871 * Parse wikitext, strip paragraphs, and return the HTML.
1873 * @param string $text
1874 * @param bool $linestart Is this the start of a line?
1875 * @param bool $interface Use interface language ($wgLang instead of
1876 * $wgContLang) while parsing language sensitive magic
1877 * words like GRAMMAR and PLURAL
1878 * @return string HTML
1880 public function parseInline( $text, $linestart = true, $interface = false ) {
1881 $parsed = $this->parse( $text, $linestart, $interface );
1882 return Parser
::stripOuterParagraph( $parsed );
1886 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1888 * @param int $maxage Maximum cache time on the Squid, in seconds.
1890 public function setSquidMaxage( $maxage ) {
1891 $this->mSquidMaxage
= $maxage;
1895 * Use enableClientCache(false) to force it to send nocache headers
1897 * @param bool $state
1901 public function enableClientCache( $state ) {
1902 return wfSetVar( $this->mEnableClientCache
, $state );
1906 * Get the list of cookies that will influence on the cache
1910 function getCacheVaryCookies() {
1912 if ( $cookies === null ) {
1913 $config = $this->getConfig();
1914 $cookies = array_merge(
1916 $config->get( 'CookiePrefix' ) . 'Token',
1917 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1921 $config->get( 'CacheVaryCookies' )
1923 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1929 * Check if the request has a cache-varying cookie header
1930 * If it does, it's very important that we don't allow public caching
1934 function haveCacheVaryCookies() {
1935 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1936 if ( $cookieHeader === false ) {
1939 $cvCookies = $this->getCacheVaryCookies();
1940 foreach ( $cvCookies as $cookieName ) {
1941 # Check for a simple string match, like the way squid does it
1942 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1943 wfDebug( __METHOD__
. ": found $cookieName\n" );
1947 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1952 * Add an HTTP header that will influence on the cache
1954 * @param string $header Header name
1955 * @param array|null $option
1956 * @todo FIXME: Document the $option parameter; it appears to be for
1957 * X-Vary-Options but what format is acceptable?
1959 public function addVaryHeader( $header, $option = null ) {
1960 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1961 $this->mVaryHeader
[$header] = (array)$option;
1962 } elseif ( is_array( $option ) ) {
1963 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1964 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1966 $this->mVaryHeader
[$header] = $option;
1969 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1973 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1974 * such as Accept-Encoding or Cookie
1978 public function getVaryHeader() {
1979 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1983 * Get a complete X-Vary-Options header
1987 public function getXVO() {
1988 $cvCookies = $this->getCacheVaryCookies();
1990 $cookiesOption = array();
1991 foreach ( $cvCookies as $cookieName ) {
1992 $cookiesOption[] = 'string-contains=' . $cookieName;
1994 $this->addVaryHeader( 'Cookie', $cookiesOption );
1997 foreach ( $this->mVaryHeader
as $header => $option ) {
1998 $newheader = $header;
1999 if ( is_array( $option ) && count( $option ) > 0 ) {
2000 $newheader .= ';' . implode( ';', $option );
2002 $headers[] = $newheader;
2004 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2010 * bug 21672: Add Accept-Language to Vary and XVO headers
2011 * if there's no 'variant' parameter existed in GET.
2014 * /w/index.php?title=Main_page should always be served; but
2015 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2017 function addAcceptLanguage() {
2018 $title = $this->getTitle();
2019 if ( !$title instanceof Title
) {
2023 $lang = $title->getPageLanguage();
2024 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2025 $variants = $lang->getVariants();
2026 $aloption = array();
2027 foreach ( $variants as $variant ) {
2028 if ( $variant === $lang->getCode() ) {
2031 $aloption[] = 'string-contains=' . $variant;
2033 // IE and some other browsers use BCP 47 standards in
2034 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2035 // We should handle these too.
2036 $variantBCP47 = wfBCP47( $variant );
2037 if ( $variantBCP47 !== $variant ) {
2038 $aloption[] = 'string-contains=' . $variantBCP47;
2042 $this->addVaryHeader( 'Accept-Language', $aloption );
2047 * Set a flag which will cause an X-Frame-Options header appropriate for
2048 * edit pages to be sent. The header value is controlled by
2049 * $wgEditPageFrameOptions.
2051 * This is the default for special pages. If you display a CSRF-protected
2052 * form on an ordinary view page, then you need to call this function.
2054 * @param bool $enable
2056 public function preventClickjacking( $enable = true ) {
2057 $this->mPreventClickjacking
= $enable;
2061 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2062 * This can be called from pages which do not contain any CSRF-protected
2065 public function allowClickjacking() {
2066 $this->mPreventClickjacking
= false;
2070 * Get the prevent-clickjacking flag
2075 public function getPreventClickjacking() {
2076 return $this->mPreventClickjacking
;
2080 * Get the X-Frame-Options header value (without the name part), or false
2081 * if there isn't one. This is used by Skin to determine whether to enable
2082 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2086 public function getFrameOptions() {
2087 $config = $this->getConfig();
2088 if ( $config->get( 'BreakFrames' ) ) {
2090 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2091 return $config->get( 'EditPageFrameOptions' );
2097 * Send cache control HTTP headers
2099 public function sendCacheControl() {
2100 $response = $this->getRequest()->response();
2101 $config = $this->getConfig();
2102 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2103 $response->header( "ETag: $this->mETag" );
2106 $this->addVaryHeader( 'Cookie' );
2107 $this->addAcceptLanguage();
2109 # don't serve compressed data to clients who can't handle it
2110 # maintain different caches for logged-in users and non-logged in ones
2111 $response->header( $this->getVaryHeader() );
2113 if ( $config->get( 'UseXVO' ) ) {
2114 # Add an X-Vary-Options header for Squid with Wikimedia patches
2115 $response->header( $this->getXVO() );
2118 if ( $this->mEnableClientCache
) {
2120 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2121 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2123 if ( $config->get( 'UseESI' ) ) {
2124 # We'll purge the proxy cache explicitly, but require end user agents
2125 # to revalidate against the proxy on each visit.
2126 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2127 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2128 # start with a shorter timeout for initial testing
2129 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2130 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2131 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2132 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2134 # We'll purge the proxy cache for anons explicitly, but require end user agents
2135 # to revalidate against the proxy on each visit.
2136 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2137 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2138 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2139 # start with a shorter timeout for initial testing
2140 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2141 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2142 . ', must-revalidate, max-age=0' );
2145 # We do want clients to cache if they can, but they *must* check for updates
2146 # on revisiting the page.
2147 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2148 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2149 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2151 if ( $this->mLastModified
) {
2152 $response->header( "Last-Modified: {$this->mLastModified}" );
2155 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2157 # In general, the absence of a last modified header should be enough to prevent
2158 # the client from using its cache. We send a few other things just to make sure.
2159 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2160 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2161 $response->header( 'Pragma: no-cache' );
2166 * Finally, all the text has been munged and accumulated into
2167 * the object, let's actually output it:
2169 public function output() {
2170 if ( $this->mDoNothing
) {
2175 $response = $this->getRequest()->response();
2176 $config = $this->getConfig();
2178 if ( $this->mRedirect
!= '' ) {
2179 # Standards require redirect URLs to be absolute
2180 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2182 $redirect = $this->mRedirect
;
2183 $code = $this->mRedirectCode
;
2185 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2186 if ( $code == '301' ||
$code == '303' ) {
2187 if ( !$config->get( 'DebugRedirects' ) ) {
2188 $message = HttpStatus
::getMessage( $code );
2189 $response->header( "HTTP/1.1 $code $message" );
2191 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2193 if ( $config->get( 'VaryOnXFP' ) ) {
2194 $this->addVaryHeader( 'X-Forwarded-Proto' );
2196 $this->sendCacheControl();
2198 $response->header( "Content-Type: text/html; charset=utf-8" );
2199 if ( $config->get( 'DebugRedirects' ) ) {
2200 $url = htmlspecialchars( $redirect );
2201 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2202 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2203 print "</body>\n</html>\n";
2205 $response->header( 'Location: ' . $redirect );
2210 } elseif ( $this->mStatusCode
) {
2211 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2213 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2217 # Buffer output; final headers may depend on later processing
2220 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2221 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2223 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2224 // jQuery etc. can work correctly.
2225 $response->header( 'X-UA-Compatible: IE=Edge' );
2227 // Prevent framing, if requested
2228 $frameOptions = $this->getFrameOptions();
2229 if ( $frameOptions ) {
2230 $response->header( "X-Frame-Options: $frameOptions" );
2233 if ( $this->mArticleBodyOnly
) {
2234 echo $this->mBodytext
;
2237 $sk = $this->getSkin();
2238 // add skin specific modules
2239 $modules = $sk->getDefaultModules();
2241 // enforce various default modules for all skins
2242 $coreModules = array(
2243 // keep this list as small as possible
2244 'mediawiki.page.startup',
2248 // Support for high-density display images if enabled
2249 if ( $config->get( 'ResponsiveImages' ) ) {
2250 $coreModules[] = 'mediawiki.hidpi';
2253 $this->addModules( $coreModules );
2254 foreach ( $modules as $group ) {
2255 $this->addModules( $group );
2257 MWDebug
::addModules( $this );
2259 // Hook that allows last minute changes to the output page, e.g.
2260 // adding of CSS or Javascript by extensions.
2261 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2266 // This hook allows last minute changes to final overall output by modifying output buffer
2267 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2269 $this->sendCacheControl();
2276 * Actually output something with print.
2278 * @param string $ins The string to output
2279 * @deprecated since 1.22 Use echo yourself.
2281 public function out( $ins ) {
2282 wfDeprecated( __METHOD__
, '1.22' );
2287 * Produce a "user is blocked" page.
2288 * @deprecated since 1.18
2290 function blockedPage() {
2291 throw new UserBlockedError( $this->getUser()->mBlock
);
2295 * Prepare this object to display an error page; disable caching and
2296 * indexing, clear the current text and redirect, set the page's title
2297 * and optionally an custom HTML title (content of the "<title>" tag).
2299 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2300 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2301 * optional, if not passed the "<title>" attribute will be
2302 * based on $pageTitle
2304 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2305 $this->setPageTitle( $pageTitle );
2306 if ( $htmlTitle !== false ) {
2307 $this->setHTMLTitle( $htmlTitle );
2309 $this->setRobotPolicy( 'noindex,nofollow' );
2310 $this->setArticleRelated( false );
2311 $this->enableClientCache( false );
2312 $this->mRedirect
= '';
2313 $this->clearSubtitle();
2318 * Output a standard error page
2320 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2321 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2322 * showErrorPage( 'titlemsg', $messageObject );
2323 * showErrorPage( $titleMessageObject, $messageObject );
2325 * @param string|Message $title Message key (string) for page title, or a Message object
2326 * @param string|Message $msg Message key (string) for page text, or a Message object
2327 * @param array $params Message parameters; ignored if $msg is a Message object
2329 public function showErrorPage( $title, $msg, $params = array() ) {
2330 if ( !$title instanceof Message
) {
2331 $title = $this->msg( $title );
2334 $this->prepareErrorPage( $title );
2336 if ( $msg instanceof Message
) {
2337 if ( $params !== array() ) {
2338 trigger_error( 'Argument ignored: $params. The message parameters argument '
2339 . 'is discarded when the $msg argument is a Message object instead of '
2340 . 'a string.', E_USER_NOTICE
);
2342 $this->addHTML( $msg->parseAsBlock() );
2344 $this->addWikiMsgArray( $msg, $params );
2347 $this->returnToMain();
2351 * Output a standard permission error page
2353 * @param array $errors Error message keys
2354 * @param string $action Action that was denied or null if unknown
2356 public function showPermissionsErrorPage( array $errors, $action = null ) {
2357 // For some action (read, edit, create and upload), display a "login to do this action"
2358 // error if all of the following conditions are met:
2359 // 1. the user is not logged in
2360 // 2. the only error is insufficient permissions (i.e. no block or something else)
2361 // 3. the error can be avoided simply by logging in
2362 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2363 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2364 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2365 && ( User
::groupHasPermission( 'user', $action )
2366 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2368 $displayReturnto = null;
2370 # Due to bug 32276, if a user does not have read permissions,
2371 # $this->getTitle() will just give Special:Badtitle, which is
2372 # not especially useful as a returnto parameter. Use the title
2373 # from the request instead, if there was one.
2374 $request = $this->getRequest();
2375 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2376 if ( $action == 'edit' ) {
2377 $msg = 'whitelistedittext';
2378 $displayReturnto = $returnto;
2379 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2380 $msg = 'nocreatetext';
2381 } elseif ( $action == 'upload' ) {
2382 $msg = 'uploadnologintext';
2384 $msg = 'loginreqpagetext';
2385 $displayReturnto = Title
::newMainPage();
2391 $query['returnto'] = $returnto->getPrefixedText();
2393 if ( !$request->wasPosted() ) {
2394 $returntoquery = $request->getValues();
2395 unset( $returntoquery['title'] );
2396 unset( $returntoquery['returnto'] );
2397 unset( $returntoquery['returntoquery'] );
2398 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2401 $loginLink = Linker
::linkKnown(
2402 SpecialPage
::getTitleFor( 'Userlogin' ),
2403 $this->msg( 'loginreqlink' )->escaped(),
2408 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2409 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2411 # Don't return to a page the user can't read otherwise
2412 # we'll end up in a pointless loop
2413 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2414 $this->returnToMain( null, $displayReturnto );
2417 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2418 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2423 * Display an error page indicating that a given version of MediaWiki is
2424 * required to use it
2426 * @param mixed $version The version of MediaWiki needed to use the page
2428 public function versionRequired( $version ) {
2429 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2431 $this->addWikiMsg( 'versionrequiredtext', $version );
2432 $this->returnToMain();
2436 * Display an error page noting that a given permission bit is required.
2437 * @deprecated since 1.18, just throw the exception directly
2438 * @param string $permission Key required
2439 * @throws PermissionsError
2441 public function permissionRequired( $permission ) {
2442 throw new PermissionsError( $permission );
2446 * Produce the stock "please login to use the wiki" page
2448 * @deprecated since 1.19; throw the exception directly
2450 public function loginToUse() {
2451 throw new PermissionsError( 'read' );
2455 * Format a list of error messages
2457 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2458 * @param string $action Action that was denied or null if unknown
2459 * @return string The wikitext error-messages, formatted into a list.
2461 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2462 if ( $action == null ) {
2463 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2465 $action_desc = $this->msg( "action-$action" )->plain();
2467 'permissionserrorstext-withaction',
2470 )->plain() . "\n\n";
2473 if ( count( $errors ) > 1 ) {
2474 $text .= '<ul class="permissions-errors">' . "\n";
2476 foreach ( $errors as $error ) {
2478 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2483 $text .= "<div class=\"permissions-errors\">\n" .
2484 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2492 * Display a page stating that the Wiki is in read-only mode.
2493 * Should only be called after wfReadOnly() has returned true.
2495 * Historically, this function was used to show the source of the page that the user
2496 * was trying to edit and _also_ permissions error messages. The relevant code was
2497 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2499 * @deprecated since 1.25; throw the exception directly
2500 * @throws ReadOnlyError
2502 public function readOnlyPage() {
2503 if ( func_num_args() > 0 ) {
2504 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2507 throw new ReadOnlyError
;
2511 * Turn off regular page output and return an error response
2512 * for when rate limiting has triggered.
2514 * @deprecated since 1.25; throw the exception directly
2516 public function rateLimited() {
2517 wfDeprecated( __METHOD__
, '1.25' );
2518 throw new ThrottledError
;
2522 * Show a warning about slave lag
2524 * If the lag is higher than $wgSlaveLagCritical seconds,
2525 * then the warning is a bit more obvious. If the lag is
2526 * lower than $wgSlaveLagWarning, then no warning is shown.
2528 * @param int $lag Slave lag
2530 public function showLagWarning( $lag ) {
2531 $config = $this->getConfig();
2532 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2533 $message = $lag < $config->get( 'SlaveLagCritical' )
2536 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2537 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2541 public function showFatalError( $message ) {
2542 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2544 $this->addHTML( $message );
2547 public function showUnexpectedValueError( $name, $val ) {
2548 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2551 public function showFileCopyError( $old, $new ) {
2552 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2555 public function showFileRenameError( $old, $new ) {
2556 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2559 public function showFileDeleteError( $name ) {
2560 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2563 public function showFileNotFoundError( $name ) {
2564 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2568 * Add a "return to" link pointing to a specified title
2570 * @param Title $title Title to link
2571 * @param array $query Query string parameters
2572 * @param string $text Text of the link (input is not escaped)
2573 * @param array $options Options array to pass to Linker
2575 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2576 $link = $this->msg( 'returnto' )->rawParams(
2577 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2578 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2582 * Add a "return to" link pointing to a specified title,
2583 * or the title indicated in the request, or else the main page
2585 * @param mixed $unused
2586 * @param Title|string $returnto Title or String to return to
2587 * @param string $returntoquery Query string for the return to link
2589 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2590 if ( $returnto == null ) {
2591 $returnto = $this->getRequest()->getText( 'returnto' );
2594 if ( $returntoquery == null ) {
2595 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2598 if ( $returnto === '' ) {
2599 $returnto = Title
::newMainPage();
2602 if ( is_object( $returnto ) ) {
2603 $titleObj = $returnto;
2605 $titleObj = Title
::newFromText( $returnto );
2607 if ( !is_object( $titleObj ) ) {
2608 $titleObj = Title
::newMainPage();
2611 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2615 * @param Skin $sk The given Skin
2616 * @param bool $includeStyle Unused
2617 * @return string The doctype, opening "<html>", and head element.
2619 public function headElement( Skin
$sk, $includeStyle = true ) {
2623 $userdir = $this->getLanguage()->getDir();
2624 $sitedir = $wgContLang->getDir();
2626 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2628 if ( $this->getHTMLTitle() == '' ) {
2629 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2632 $openHead = Html
::openElement( 'head' );
2634 # Don't bother with the newline if $head == ''
2635 $ret .= "$openHead\n";
2638 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2639 // Add <meta charset="UTF-8">
2640 // This should be before <title> since it defines the charset used by
2641 // text including the text inside <title>.
2642 // The spec recommends defining XHTML5's charset using the XML declaration
2644 // Our XML declaration is output by Html::htmlHeader.
2645 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2646 // http://www.whatwg.org/html/semantics.html#charset
2647 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2650 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2652 foreach ( $this->getHeadLinksArray() as $item ) {
2653 $ret .= $item . "\n";
2656 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2657 $ret .= $this->buildCssLinks();
2659 $ret .= $this->getHeadScripts() . "\n";
2661 foreach ( $this->mHeadItems
as $item ) {
2662 $ret .= $item . "\n";
2665 $closeHead = Html
::closeElement( 'head' );
2667 $ret .= "$closeHead\n";
2670 $bodyClasses = array();
2671 $bodyClasses[] = 'mediawiki';
2673 # Classes for LTR/RTL directionality support
2674 $bodyClasses[] = $userdir;
2675 $bodyClasses[] = "sitedir-$sitedir";
2677 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2678 # A <body> class is probably not the best way to do this . . .
2679 $bodyClasses[] = 'capitalize-all-nouns';
2682 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2683 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2685 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2687 $bodyAttrs = array();
2688 // While the implode() is not strictly needed, it's used for backwards compatibility
2689 // (this used to be built as a string and hooks likely still expect that).
2690 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2692 // Allow skins and extensions to add body attributes they need
2693 $sk->addToBodyAttributes( $this, $bodyAttrs );
2694 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2696 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2702 * Get a ResourceLoader object associated with this OutputPage
2704 * @return ResourceLoader
2706 public function getResourceLoader() {
2707 if ( is_null( $this->mResourceLoader
) ) {
2708 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2710 return $this->mResourceLoader
;
2715 * @param array|string $modules One or more module names
2716 * @param string $only ResourceLoaderModule TYPE_ class constant
2717 * @param bool $useESI
2718 * @param array $extraQuery Array with extra query parameters to add to each
2719 * request. array( param => value ).
2720 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2721 * call rather than a "<script src='...'>" tag.
2722 * @return string The html "<script>", "<link>" and "<style>" tags
2724 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2725 array $extraQuery = array(), $loadCall = false
2727 $modules = (array)$modules;
2731 'states' => array(),
2734 if ( !count( $modules ) ) {
2738 if ( count( $modules ) > 1 ) {
2739 // Remove duplicate module requests
2740 $modules = array_unique( $modules );
2741 // Sort module names so requests are more uniform
2744 if ( ResourceLoader
::inDebugMode() ) {
2745 // Recursively call us for every item
2746 foreach ( $modules as $name ) {
2747 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2748 $links['html'] .= $link['html'];
2749 $links['states'] +
= $link['states'];
2755 if ( !is_null( $this->mTarget
) ) {
2756 $extraQuery['target'] = $this->mTarget
;
2759 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2760 $sortedModules = array();
2761 $resourceLoader = $this->getResourceLoader();
2762 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2763 foreach ( $modules as $name ) {
2764 $module = $resourceLoader->getModule( $name );
2765 # Check that we're allowed to include this module on this page
2767 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2768 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2769 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2770 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2771 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2772 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2773 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2778 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2781 foreach ( $sortedModules as $source => $groups ) {
2782 foreach ( $groups as $group => $grpModules ) {
2783 // Special handling for user-specific groups
2785 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2786 $user = $this->getUser()->getName();
2789 // Create a fake request based on the one we are about to make so modules return
2790 // correct timestamp and emptiness data
2791 $query = ResourceLoader
::makeLoaderQuery(
2792 array(), // modules; not determined yet
2793 $this->getLanguage()->getCode(),
2794 $this->getSkin()->getSkinName(),
2796 null, // version; not determined yet
2797 ResourceLoader
::inDebugMode(),
2798 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2799 $this->isPrintable(),
2800 $this->getRequest()->getBool( 'handheld' ),
2803 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2805 // Extract modules that know they're empty and see if we have one or more
2808 foreach ( $grpModules as $key => $module ) {
2809 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2810 // If we're only getting the styles, we don't need to do anything for empty modules.
2811 if ( $module->isKnownEmpty( $context ) ) {
2812 unset( $grpModules[$key] );
2813 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2814 $links['states'][$key] = 'ready';
2818 $isRaw |
= $module->isRaw();
2821 // If there are no non-empty modules, skip this group
2822 if ( count( $grpModules ) === 0 ) {
2826 // Inline private modules. These can't be loaded through load.php for security
2827 // reasons, see bug 34907. Note that these modules should be loaded from
2828 // getHeadScripts() before the first loader call. Otherwise other modules can't
2829 // properly use them as dependencies (bug 30914)
2830 if ( $group === 'private' ) {
2831 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2832 $links['html'] .= Html
::inlineStyle(
2833 $resourceLoader->makeModuleResponse( $context, $grpModules )
2836 $links['html'] .= Html
::inlineScript(
2837 ResourceLoader
::makeLoaderConditionalScript(
2838 $resourceLoader->makeModuleResponse( $context, $grpModules )
2842 $links['html'] .= "\n";
2846 // Special handling for the user group; because users might change their stuff
2847 // on-wiki like user pages, or user preferences; we need to find the highest
2848 // timestamp of these user-changeable modules so we can ensure cache misses on change
2849 // This should NOT be done for the site group (bug 27564) because anons get that too
2850 // and we shouldn't be putting timestamps in Squid-cached HTML
2852 if ( $group === 'user' ) {
2853 // Get the maximum timestamp
2855 foreach ( $grpModules as $module ) {
2856 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2858 // Add a version parameter so cache will break when things change
2859 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2862 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2863 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2864 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2866 if ( $useESI && $resourceLoaderUseESI ) {
2867 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2868 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2869 $link = Html
::inlineStyle( $esi );
2871 $link = Html
::inlineScript( $esi );
2874 // Automatically select style/script elements
2875 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2876 $link = Html
::linkedStyle( $url );
2877 } elseif ( $loadCall ) {
2878 $link = Html
::inlineScript(
2879 ResourceLoader
::makeLoaderConditionalScript(
2880 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2884 $link = Html
::linkedScript( $url );
2885 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2886 // Wrap only=script requests in a conditional as browsers not supported
2887 // by the startup module would unconditionally execute this module.
2888 // Otherwise users will get "ReferenceError: mw is undefined" or
2889 // "jQuery is undefined" from e.g. a "site" module.
2890 $link = Html
::inlineScript(
2891 ResourceLoader
::makeLoaderConditionalScript(
2892 Xml
::encodeJsCall( 'document.write', array( $link ) )
2897 // For modules requested directly in the html via <link> or <script>,
2898 // tell mw.loader they are being loading to prevent duplicate requests.
2899 foreach ( $grpModules as $key => $module ) {
2900 // Don't output state=loading for the startup module..
2901 if ( $key !== 'startup' ) {
2902 $links['states'][$key] = 'loading';
2908 if ( $group == 'noscript' ) {
2909 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2911 $links['html'] .= $link . "\n";
2920 * Build html output from an array of links from makeResourceLoaderLink.
2921 * @param array $links
2922 * @return string HTML
2924 protected static function getHtmlFromLoaderLinks( array $links ) {
2927 foreach ( $links as $link ) {
2928 if ( !is_array( $link ) ) {
2931 $html .= $link['html'];
2932 $states +
= $link['states'];
2936 if ( count( $states ) ) {
2937 $html = Html
::inlineScript(
2938 ResourceLoader
::makeLoaderConditionalScript(
2939 ResourceLoader
::makeLoaderStateScript( $states )
2948 * JS stuff to put in the "<head>". This is the startup module, config
2949 * vars and modules marked with position 'top'
2951 * @return string HTML fragment
2953 function getHeadScripts() {
2954 // Startup - this will immediately load jquery and mediawiki modules
2956 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2958 // Load config before anything else
2959 $links[] = Html
::inlineScript(
2960 ResourceLoader
::makeLoaderConditionalScript(
2961 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2965 // Load embeddable private modules before any loader links
2966 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2967 // in mw.loader.implement() calls and deferred until mw.user is available
2968 $embedScripts = array( 'user.options', 'user.tokens' );
2969 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2971 // Scripts and messages "only" requests marked for top inclusion
2972 // Messages should go first
2973 $links[] = $this->makeResourceLoaderLink(
2974 $this->getModuleMessages( true, 'top' ),
2975 ResourceLoaderModule
::TYPE_MESSAGES
2977 $links[] = $this->makeResourceLoaderLink(
2978 $this->getModuleScripts( true, 'top' ),
2979 ResourceLoaderModule
::TYPE_SCRIPTS
2982 // Modules requests - let the client calculate dependencies and batch requests as it likes
2983 // Only load modules that have marked themselves for loading at the top
2984 $modules = $this->getModules( true, 'top' );
2986 $links[] = Html
::inlineScript(
2987 ResourceLoader
::makeLoaderConditionalScript(
2988 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2993 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2994 $links[] = $this->getScriptsForBottomQueue( true );
2997 return self
::getHtmlFromLoaderLinks( $links );
3001 * JS stuff to put at the 'bottom', which can either be the bottom of the
3002 * "<body>" or the bottom of the "<head>" depending on
3003 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3004 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3007 * @param bool $inHead If true, this HTML goes into the "<head>",
3008 * if false it goes into the "<body>".
3011 function getScriptsForBottomQueue( $inHead ) {
3012 // Scripts and messages "only" requests marked for bottom inclusion
3013 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3014 // Messages should go first
3016 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
3017 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
3018 /* $loadCall = */ $inHead
3020 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3021 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
3022 /* $loadCall = */ $inHead
3025 // Modules requests - let the client calculate dependencies and batch requests as it likes
3026 // Only load modules that have marked themselves for loading at the bottom
3027 $modules = $this->getModules( true, 'bottom' );
3029 $links[] = Html
::inlineScript(
3030 ResourceLoader
::makeLoaderConditionalScript(
3031 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3037 $links[] = "\n" . $this->mScripts
;
3039 // Add site JS if enabled
3040 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3041 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3044 // Add user JS if enabled
3045 if ( $this->getConfig()->get( 'AllowUserJs' )
3046 && $this->getUser()->isLoggedIn()
3047 && $this->getTitle()
3048 && $this->getTitle()->isJsSubpage()
3049 && $this->userCanPreview()
3051 # XXX: additional security check/prompt?
3052 // We're on a preview of a JS subpage
3053 // Exclude this page from the user module in case it's in there (bug 26283)
3054 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3055 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3057 // Load the previewed JS
3058 $links[] = Html
::inlineScript( "\n"
3059 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3061 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3062 // asynchronously and may arrive *after* the inline script here. So the previewed code
3063 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3065 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3066 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3067 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3071 // Group JS is only enabled if site JS is enabled.
3072 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3073 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3076 return self
::getHtmlFromLoaderLinks( $links );
3080 * JS stuff to put at the bottom of the "<body>"
3083 function getBottomScripts() {
3084 // Optimise jQuery ready event cross-browser.
3085 // This also enforces $.isReady to be true at </body> which fixes the
3086 // mw.loader bug in Firefox with using document.write between </body>
3087 // and the DOMContentReady event (bug 47457).
3088 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3090 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3091 $html .= $this->getScriptsForBottomQueue( false );
3098 * Get the javascript config vars to include on this page
3100 * @return array Array of javascript config vars
3103 public function getJsConfigVars() {
3104 return $this->mJsConfigVars
;
3108 * Add one or more variables to be set in mw.config in JavaScript
3110 * @param string|array $keys Key or array of key/value pairs
3111 * @param mixed $value [optional] Value of the configuration variable
3113 public function addJsConfigVars( $keys, $value = null ) {
3114 if ( is_array( $keys ) ) {
3115 foreach ( $keys as $key => $value ) {
3116 $this->mJsConfigVars
[$key] = $value;
3121 $this->mJsConfigVars
[$keys] = $value;
3125 * Get an array containing the variables to be set in mw.config in JavaScript.
3127 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3128 * - in other words, page-independent/site-wide variables (without state).
3129 * You will only be adding bloat to the html page and causing page caches to
3130 * have to be purged on configuration changes.
3133 public function getJSVars() {
3138 $canonicalSpecialPageName = false; # bug 21115
3140 $title = $this->getTitle();
3141 $ns = $title->getNamespace();
3142 $canonicalNamespace = MWNamespace
::exists( $ns )
3143 ? MWNamespace
::getCanonicalName( $ns )
3144 : $title->getNsText();
3146 $sk = $this->getSkin();
3147 // Get the relevant title so that AJAX features can use the correct page name
3148 // when making API requests from certain special pages (bug 34972).
3149 $relevantTitle = $sk->getRelevantTitle();
3150 $relevantUser = $sk->getRelevantUser();
3152 if ( $ns == NS_SPECIAL
) {
3153 list( $canonicalSpecialPageName, /*...*/ ) =
3154 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3155 } elseif ( $this->canUseWikiPage() ) {
3156 $wikiPage = $this->getWikiPage();
3157 $curRevisionId = $wikiPage->getLatest();
3158 $articleId = $wikiPage->getId();
3161 $lang = $title->getPageLanguage();
3163 // Pre-process information
3164 $separatorTransTable = $lang->separatorTransformTable();
3165 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3166 $compactSeparatorTransTable = array(
3167 implode( "\t", array_keys( $separatorTransTable ) ),
3168 implode( "\t", $separatorTransTable ),
3170 $digitTransTable = $lang->digitTransformTable();
3171 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3172 $compactDigitTransTable = array(
3173 implode( "\t", array_keys( $digitTransTable ) ),
3174 implode( "\t", $digitTransTable ),
3177 $user = $this->getUser();
3180 'wgCanonicalNamespace' => $canonicalNamespace,
3181 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3182 'wgNamespaceNumber' => $title->getNamespace(),
3183 'wgPageName' => $title->getPrefixedDBkey(),
3184 'wgTitle' => $title->getText(),
3185 'wgCurRevisionId' => $curRevisionId,
3186 'wgRevisionId' => (int)$this->getRevisionId(),
3187 'wgArticleId' => $articleId,
3188 'wgIsArticle' => $this->isArticle(),
3189 'wgIsRedirect' => $title->isRedirect(),
3190 'wgAction' => Action
::getActionName( $this->getContext() ),
3191 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3192 'wgUserGroups' => $user->getEffectiveGroups(),
3193 'wgCategories' => $this->getCategories(),
3194 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3195 'wgPageContentLanguage' => $lang->getCode(),
3196 'wgPageContentModel' => $title->getContentModel(),
3197 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3198 'wgDigitTransformTable' => $compactDigitTransTable,
3199 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3200 'wgMonthNames' => $lang->getMonthNamesArray(),
3201 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3202 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3203 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3206 if ( $user->isLoggedIn() ) {
3207 $vars['wgUserId'] = $user->getId();
3208 $vars['wgUserEditCount'] = $user->getEditCount();
3209 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3210 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3211 // Get the revision ID of the oldest new message on the user's talk
3212 // page. This can be used for constructing new message alerts on
3214 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3217 if ( $wgContLang->hasVariants() ) {
3218 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3220 // Same test as SkinTemplate
3221 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3222 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3224 foreach ( $title->getRestrictionTypes() as $type ) {
3225 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3228 if ( $title->isMainPage() ) {
3229 $vars['wgIsMainPage'] = true;
3232 if ( $this->mRedirectedFrom
) {
3233 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3236 if ( $relevantUser ) {
3237 $vars['wgRelevantUserName'] = $relevantUser->getName();
3240 // Allow extensions to add their custom variables to the mw.config map.
3241 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3242 // page-dependant but site-wide (without state).
3243 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3244 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3246 // Merge in variables from addJsConfigVars last
3247 return array_merge( $vars, $this->getJsConfigVars() );
3251 * To make it harder for someone to slip a user a fake
3252 * user-JavaScript or user-CSS preview, a random token
3253 * is associated with the login session. If it's not
3254 * passed back with the preview request, we won't render
3259 public function userCanPreview() {
3260 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3261 ||
!$this->getRequest()->wasPosted()
3262 ||
!$this->getUser()->matchEditToken(
3263 $this->getRequest()->getVal( 'wpEditToken' ) )
3267 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3271 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3275 * @return array Array in format "link name or number => 'link html'".
3277 public function getHeadLinksArray() {
3281 $config = $this->getConfig();
3283 $canonicalUrl = $this->mCanonicalUrl
;
3285 $tags['meta-generator'] = Html
::element( 'meta', array(
3286 'name' => 'generator',
3287 'content' => "MediaWiki $wgVersion",
3290 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3291 if ( $p !== 'index,follow' ) {
3292 // http://www.robotstxt.org/wc/meta-user.html
3293 // Only show if it's different from the default robots policy
3294 $tags['meta-robots'] = Html
::element( 'meta', array(
3300 foreach ( $this->mMetatags
as $tag ) {
3301 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3303 $tag[0] = substr( $tag[0], 5 );
3307 $tagName = "meta-{$tag[0]}";
3308 if ( isset( $tags[$tagName] ) ) {
3309 $tagName .= $tag[1];
3311 $tags[$tagName] = Html
::element( 'meta',
3314 'content' => $tag[1]
3319 foreach ( $this->mLinktags
as $tag ) {
3320 $tags[] = Html
::element( 'link', $tag );
3323 # Universal edit button
3324 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3325 $user = $this->getUser();
3326 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3327 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3328 // Original UniversalEditButton
3329 $msg = $this->msg( 'edit' )->text();
3330 $tags['universal-edit-button'] = Html
::element( 'link', array(
3331 'rel' => 'alternate',
3332 'type' => 'application/x-wiki',
3334 'href' => $this->getTitle()->getEditURL(),
3336 // Alternate edit link
3337 $tags['alternative-edit'] = Html
::element( 'link', array(
3340 'href' => $this->getTitle()->getEditURL(),
3345 # Generally the order of the favicon and apple-touch-icon links
3346 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3347 # uses whichever one appears later in the HTML source. Make sure
3348 # apple-touch-icon is specified first to avoid this.
3349 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3350 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3351 'rel' => 'apple-touch-icon',
3352 'href' => $config->get( 'AppleTouchIcon' )
3356 if ( $config->get( 'Favicon' ) !== false ) {
3357 $tags['favicon'] = Html
::element( 'link', array(
3358 'rel' => 'shortcut icon',
3359 'href' => $config->get( 'Favicon' )
3363 # OpenSearch description link
3364 $tags['opensearch'] = Html
::element( 'link', array(
3366 'type' => 'application/opensearchdescription+xml',
3367 'href' => wfScript( 'opensearch_desc' ),
3368 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3371 if ( $config->get( 'EnableAPI' ) ) {
3372 # Real Simple Discovery link, provides auto-discovery information
3373 # for the MediaWiki API (and potentially additional custom API
3374 # support such as WordPress or Twitter-compatible APIs for a
3375 # blogging extension, etc)
3376 $tags['rsd'] = Html
::element( 'link', array(
3378 'type' => 'application/rsd+xml',
3379 // Output a protocol-relative URL here if $wgServer is protocol-relative
3380 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3381 'href' => wfExpandUrl( wfAppendQuery(
3383 array( 'action' => 'rsd' ) ),
3390 if ( !$config->get( 'DisableLangConversion' ) ) {
3391 $lang = $this->getTitle()->getPageLanguage();
3392 if ( $lang->hasVariants() ) {
3393 $variants = $lang->getVariants();
3394 foreach ( $variants as $_v ) {
3395 $tags["variant-$_v"] = Html
::element( 'link', array(
3396 'rel' => 'alternate',
3397 'hreflang' => wfBCP47( $_v ),
3398 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3402 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3403 $tags["variant-x-default"] = Html
::element( 'link', array(
3404 'rel' => 'alternate',
3405 'hreflang' => 'x-default',
3406 'href' => $this->getTitle()->getLocalURL() ) );
3411 if ( $config->get( 'RightsPage' ) ) {
3412 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3415 $copyright = $copy->getLocalURL();
3419 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3420 $copyright = $config->get( 'RightsUrl' );
3424 $tags['copyright'] = Html
::element( 'link', array(
3425 'rel' => 'copyright',
3426 'href' => $copyright )
3431 if ( $config->get( 'Feed' ) ) {
3432 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3433 # Use the page name for the title. In principle, this could
3434 # lead to issues with having the same name for different feeds
3435 # corresponding to the same page, but we can't avoid that at
3438 $tags[] = $this->feedLink(
3441 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3442 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3446 # Recent changes feed should appear on every page (except recentchanges,
3447 # that would be redundant). Put it after the per-page feed to avoid
3448 # changing existing behavior. It's still available, probably via a
3449 # menu in your browser. Some sites might have a different feed they'd
3450 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3451 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3452 # If so, use it instead.
3453 $sitename = $config->get( 'Sitename' );
3454 if ( $config->get( 'OverrideSiteFeed' ) ) {
3455 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3456 // Note, this->feedLink escapes the url.
3457 $tags[] = $this->feedLink(
3460 $this->msg( "site-{$type}-feed", $sitename )->text()
3463 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3464 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3465 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3466 $tags[] = $this->feedLink(
3468 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3469 # For grep: 'site-rss-feed', 'site-atom-feed'
3470 $this->msg( "site-{$format}-feed", $sitename )->text()
3477 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3478 if ( $canonicalUrl !== false ) {
3479 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3481 $reqUrl = $this->getRequest()->getRequestURL();
3482 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3485 if ( $canonicalUrl !== false ) {
3486 $tags[] = Html
::element( 'link', array(
3487 'rel' => 'canonical',
3488 'href' => $canonicalUrl
3496 * @return string HTML tag links to be put in the header.
3497 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3498 * OutputPage::getHeadLinksArray directly.
3500 public function getHeadLinks() {
3501 wfDeprecated( __METHOD__
, '1.24' );
3502 return implode( "\n", $this->getHeadLinksArray() );
3506 * Generate a "<link rel/>" for a feed.
3508 * @param string $type Feed type
3509 * @param string $url URL to the feed
3510 * @param string $text Value of the "title" attribute
3511 * @return string HTML fragment
3513 private function feedLink( $type, $url, $text ) {
3514 return Html
::element( 'link', array(
3515 'rel' => 'alternate',
3516 'type' => "application/$type+xml",
3523 * Add a local or specified stylesheet, with the given media options.
3524 * Meant primarily for internal use...
3526 * @param string $style URL to the file
3527 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3528 * @param string $condition For IE conditional comments, specifying an IE version
3529 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3531 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3533 // Even though we expect the media type to be lowercase, but here we
3534 // force it to lowercase to be safe.
3536 $options['media'] = $media;
3539 $options['condition'] = $condition;
3542 $options['dir'] = $dir;
3544 $this->styles
[$style] = $options;
3548 * Adds inline CSS styles
3549 * @param mixed $style_css Inline CSS
3550 * @param string $flip Set to 'flip' to flip the CSS if needed
3552 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3553 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3554 # If wanted, and the interface is right-to-left, flip the CSS
3555 $style_css = CSSJanus
::transform( $style_css, true, false );
3557 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3561 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3562 * These will be applied to various media & IE conditionals.
3566 public function buildCssLinks() {
3569 $this->getSkin()->setupSkinUserCss( $this );
3571 // Add ResourceLoader styles
3572 // Split the styles into these groups
3577 'private' => array(),
3578 'noscript' => array()
3581 $otherTags = ''; // Tags to append after the normal <link> tags
3582 $resourceLoader = $this->getResourceLoader();
3584 $moduleStyles = $this->getModuleStyles();
3586 // Per-site custom styles
3587 $moduleStyles[] = 'site';
3588 $moduleStyles[] = 'noscript';
3589 $moduleStyles[] = 'user.groups';
3591 // Per-user custom styles
3592 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3593 && $this->userCanPreview()
3595 // We're on a preview of a CSS subpage
3596 // Exclude this page from the user module in case it's in there (bug 26283)
3597 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3598 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3600 $otherTags .= $link['html'];
3602 // Load the previewed CSS
3603 // If needed, Janus it first. This is user-supplied CSS, so it's
3604 // assumed to be right for the content language directionality.
3605 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3606 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3607 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3609 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3611 // Load the user styles normally
3612 $moduleStyles[] = 'user';
3615 // Per-user preference styles
3616 $moduleStyles[] = 'user.cssprefs';
3618 foreach ( $moduleStyles as $name ) {
3619 $module = $resourceLoader->getModule( $name );
3623 $group = $module->getGroup();
3624 // Modules in groups different than the ones listed on top (see $styles assignment)
3625 // will be placed in the "other" group
3626 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3629 // We want site, private and user styles to override dynamically added
3630 // styles from modules, but we want dynamically added styles to override
3631 // statically added styles from other modules. So the order has to be
3632 // other, dynamic, site, private, user. Add statically added styles for
3634 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3635 // Add normal styles added through addStyle()/addInlineStyle() here
3636 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3637 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3638 // We use a <meta> tag with a made-up name for this because that's valid HTML
3639 $links[] = Html
::element(
3641 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3644 // Add site, private and user styles
3645 // 'private' at present only contains user.options, so put that before 'user'
3646 // Any future private modules will likely have a similar user-specific character
3647 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3648 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3649 ResourceLoaderModule
::TYPE_STYLES
3653 // Add stuff in $otherTags (previewed user CSS if applicable)
3654 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3660 public function buildCssLinksArray() {
3663 // Add any extension CSS
3664 foreach ( $this->mExtStyles
as $url ) {
3665 $this->addStyle( $url );
3667 $this->mExtStyles
= array();
3669 foreach ( $this->styles
as $file => $options ) {
3670 $link = $this->styleLink( $file, $options );
3672 $links[$file] = $link;
3679 * Generate \<link\> tags for stylesheets
3681 * @param string $style URL to the file
3682 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3683 * @return string HTML fragment
3685 protected function styleLink( $style, array $options ) {
3686 if ( isset( $options['dir'] ) ) {
3687 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3692 if ( isset( $options['media'] ) ) {
3693 $media = self
::transformCssMedia( $options['media'] );
3694 if ( is_null( $media ) ) {
3701 if ( substr( $style, 0, 1 ) == '/' ||
3702 substr( $style, 0, 5 ) == 'http:' ||
3703 substr( $style, 0, 6 ) == 'https:' ) {
3706 $config = $this->getConfig();
3707 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3710 $link = Html
::linkedStyle( $url, $media );
3712 if ( isset( $options['condition'] ) ) {
3713 $condition = htmlspecialchars( $options['condition'] );
3714 $link = "<!--[if $condition]>$link<![endif]-->";
3720 * Transform "media" attribute based on request parameters
3722 * @param string $media Current value of the "media" attribute
3723 * @return string Modified value of the "media" attribute, or null to skip
3726 public static function transformCssMedia( $media ) {
3729 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3730 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3732 // Switch in on-screen display for media testing
3734 'printable' => 'print',
3735 'handheld' => 'handheld',
3737 foreach ( $switches as $switch => $targetMedia ) {
3738 if ( $wgRequest->getBool( $switch ) ) {
3739 if ( $media == $targetMedia ) {
3741 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3742 // This regex will not attempt to understand a comma-separated media_query_list
3744 // Example supported values for $media:
3745 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3746 // Example NOT supported value for $media:
3747 // '3d-glasses, screen, print and resolution > 90dpi'
3749 // If it's a print request, we never want any kind of screen stylesheets
3750 // If it's a handheld request (currently the only other choice with a switch),
3751 // we don't want simple 'screen' but we might want screen queries that
3752 // have a max-width or something, so we'll pass all others on and let the
3753 // client do the query.
3754 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3765 * Add a wikitext-formatted message to the output.
3766 * This is equivalent to:
3768 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3770 public function addWikiMsg( /*...*/ ) {
3771 $args = func_get_args();
3772 $name = array_shift( $args );
3773 $this->addWikiMsgArray( $name, $args );
3777 * Add a wikitext-formatted message to the output.
3778 * Like addWikiMsg() except the parameters are taken as an array
3779 * instead of a variable argument list.
3781 * @param string $name
3782 * @param array $args
3784 public function addWikiMsgArray( $name, $args ) {
3785 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3789 * This function takes a number of message/argument specifications, wraps them in
3790 * some overall structure, and then parses the result and adds it to the output.
3792 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3793 * on. The subsequent arguments may either be strings, in which case they are the
3794 * message names, or arrays, in which case the first element is the message name,
3795 * and subsequent elements are the parameters to that message.
3797 * Don't use this for messages that are not in users interface language.
3801 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3805 * $wgOut->addWikiText( "<div class='error'>\n"
3806 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3808 * The newline after opening div is needed in some wikitext. See bug 19226.
3810 * @param string $wrap
3812 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3813 $msgSpecs = func_get_args();
3814 array_shift( $msgSpecs );
3815 $msgSpecs = array_values( $msgSpecs );
3817 foreach ( $msgSpecs as $n => $spec ) {
3818 if ( is_array( $spec ) ) {
3820 $name = array_shift( $args );
3821 if ( isset( $args['options'] ) ) {
3822 unset( $args['options'] );
3824 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3832 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3834 $this->addWikiText( $s );
3838 * Include jQuery core. Use this to avoid loading it multiple times
3839 * before we get a usable script loader.
3841 * @param array $modules List of jQuery modules which should be loaded
3842 * @return array The list of modules which were not loaded.
3844 * @deprecated since 1.17
3846 public function includeJQuery( array $modules = array() ) {
3851 * Enables/disables TOC, doesn't override __NOTOC__
3855 public function enableTOC( $flag = true ) {
3856 $this->mEnableTOC
= $flag;
3863 public function isTOCEnabled() {
3864 return $this->mEnableTOC
;
3868 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3872 public function enableSectionEditLinks( $flag = true ) {
3873 $this->mEnableSectionEditLinks
= $flag;
3880 public function sectionEditLinksEnabled() {
3881 return $this->mEnableSectionEditLinks
;