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();
125 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
126 private $mLanguageLinks = array();
129 * Used for JavaScript (pre resource loader)
130 * @todo We should split JS / CSS.
131 * mScripts content is inserted as is in "<head>" by Skin. This might
132 * contain either a link to a stylesheet or inline CSS.
134 private $mScripts = '';
136 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
137 protected $mInlineStyles = '';
140 private $mLinkColours;
143 * @var string Used by skin template.
144 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
146 public $mPageLinkTitle = '';
148 /** @var array Array of elements in "<head>". Parser might add its own headers! */
149 protected $mHeadItems = array();
151 // @todo FIXME: Next 5 variables probably come from the resource loader
154 protected $mModules = array();
157 protected $mModuleScripts = array();
160 protected $mModuleStyles = array();
163 protected $mModuleMessages = array();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
200 private $mContainsOldMagic = 0;
203 protected $mContainsNewMagic = 0;
206 * lazy initialised, use parserOptions()
209 protected $mParserOptions = null;
212 * Handles the Atom / RSS links.
213 * We probably only support Atom in 2011.
214 * @see $wgAdvertisedFeedTypes
216 private $mFeedLinks = array();
218 // Gwicke work on squid caching? Roughly from 2003.
219 protected $mEnableClientCache = true;
221 /** @var bool Flag if output should only contain the body of the article. */
222 private $mArticleBodyOnly = false;
225 protected $mNewSectionLink = false;
228 protected $mHideNewSectionLink = false;
231 * @var bool Comes from the parser. This was probably made to load CSS/JS
232 * only if we had "<gallery>". Used directly in CategoryPage.php.
233 * Looks like resource loader can replace this.
235 public $mNoGallery = false;
238 private $mPageTitleActionText = '';
241 private $mParseWarnings = array();
243 /** @var int Cache stuff. Looks like mEnableClientCache */
244 protected $mSquidMaxage = 0;
250 protected $mPreventClickjacking = true;
252 /** @var int To include the variable {{REVISIONID}} */
253 private $mRevisionId = null;
256 private $mRevisionTimestamp = null;
259 protected $mFileVersion = null;
262 * @var array An array of stylesheet filenames (relative from skins path),
263 * with options for CSS media, IE conditions, and RTL/LTR direction.
264 * For internal use; add settings in the skin via $this->addStyle()
266 * Style again! This seems like a code duplication since we already have
267 * mStyles. This is what makes Open Source amazing.
269 protected $styles = array();
272 * Whether jQuery is already handled.
274 protected $mJQueryDone = false;
276 private $mIndexPolicy = 'index';
277 private $mFollowPolicy = 'follow';
278 private $mVaryHeader = array(
279 'Accept-Encoding' => array( 'list-contains=gzip' ),
283 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
288 private $mRedirectedFrom = null;
291 * Additional key => value data
293 private $mProperties = array();
296 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
298 private $mTarget = null;
301 * @var bool Whether parser output should contain table of contents
303 private $mEnableTOC = true;
306 * @var bool Whether parser output should contain section edit links
308 private $mEnableSectionEditLinks = true;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
315 function __construct( IContextSource
$context = null ) {
316 if ( $context === null ) {
317 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
318 wfDeprecated( __METHOD__
, '1.18' );
320 $this->setContext( $context );
325 * Redirect to $url rather than displaying the normal page
327 * @param string $url URL
328 * @param string $responsecode HTTP status code
330 public function redirect( $url, $responsecode = '302' ) {
331 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
332 $this->mRedirect
= str_replace( "\n", '', $url );
333 $this->mRedirectCode
= $responsecode;
337 * Get the URL to redirect to, or an empty string if not redirect URL set
341 public function getRedirect() {
342 return $this->mRedirect
;
346 * Set the HTTP status code to send with the output.
348 * @param int $statusCode
350 public function setStatusCode( $statusCode ) {
351 $this->mStatusCode
= $statusCode;
355 * Add a new "<meta>" tag
356 * To add an http-equiv meta tag, precede the name with "http:"
358 * @param string $name Tag name
359 * @param string $val Tag value
361 function addMeta( $name, $val ) {
362 array_push( $this->mMetatags
, array( $name, $val ) );
366 * Add a new \<link\> tag to the page header.
368 * Note: use setCanonicalUrl() for rel=canonical.
370 * @param array $linkarr Associative array of attributes.
372 function addLink( $linkarr ) {
373 array_push( $this->mLinktags
, $linkarr );
377 * Add a new \<link\> with "rel" attribute set to "meta"
379 * @param array $linkarr Associative array mapping attribute names to their
380 * values, both keys and values will be escaped, and the
381 * "rel" attribute will be automatically added
383 function addMetadataLink( $linkarr ) {
384 $linkarr['rel'] = $this->getMetadataAttribute();
385 $this->addLink( $linkarr );
389 * Set the URL to be used for the <link rel=canonical>. This should be used
390 * in preference to addLink(), to avoid duplicate link tags.
392 function setCanonicalUrl( $url ) {
393 $this->mCanonicalUrl
= $url;
397 * Get the value of the "rel" attribute for metadata links
401 public function getMetadataAttribute() {
402 # note: buggy CC software only reads first "meta" link
403 static $haveMeta = false;
405 return 'alternate meta';
413 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
415 * @param string $script Raw HTML
417 function addScript( $script ) {
418 $this->mScripts
.= $script . "\n";
422 * Register and add a stylesheet from an extension directory.
424 * @param string $url Path to sheet. Provide either a full url (beginning
425 * with 'http', etc) or a relative path from the document root
426 * (beginning with '/'). Otherwise it behaves identically to
427 * addStyle() and draws from the /skins folder.
429 public function addExtensionStyle( $url ) {
430 array_push( $this->mExtStyles
, $url );
434 * Get all styles added by extensions
438 function getExtStyle() {
439 return $this->mExtStyles
;
443 * Add a JavaScript file out of skins/common, or a given relative path.
445 * @param string $file Filename in skins/common or complete on-server path
447 * @param string $version Style version of the file. Defaults to $wgStyleVersion
449 public function addScriptFile( $file, $version = null ) {
450 global $wgStylePath, $wgStyleVersion;
451 // See if $file parameter is an absolute URL or begins with a slash
452 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
455 $path = "{$wgStylePath}/common/{$file}";
457 if ( is_null( $version ) ) {
458 $version = $wgStyleVersion;
460 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
464 * Add a self-contained script tag with the given contents
466 * @param string $script JavaScript text, no "<script>" tags
468 public function addInlineScript( $script ) {
469 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
473 * Get all registered JS and CSS tags for the header.
476 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
478 function getScript() {
479 wfDeprecated( __METHOD__
, '1.24' );
480 return $this->mScripts
. $this->getHeadItems();
484 * Filter an array of modules to remove insufficiently trustworthy members, and modules
485 * which are no longer registered (eg a page is cached before an extension is disabled)
486 * @param array $modules
487 * @param string|null $position If not null, only return modules with this position
488 * @param string $type
491 protected function filterModules( $modules, $position = null,
492 $type = ResourceLoaderModule
::TYPE_COMBINED
494 $resourceLoader = $this->getResourceLoader();
495 $filteredModules = array();
496 foreach ( $modules as $val ) {
497 $module = $resourceLoader->getModule( $val );
498 if ( $module instanceof ResourceLoaderModule
499 && $module->getOrigin() <= $this->getAllowedModules( $type )
500 && ( is_null( $position ) ||
$module->getPosition() == $position )
501 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
503 $filteredModules[] = $val;
506 return $filteredModules;
510 * Get the list of modules to include on this page
512 * @param bool $filter Whether to filter out insufficiently trustworthy modules
513 * @param string|null $position If not null, only return modules with this position
514 * @param string $param
515 * @return array Array of module names
517 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
518 $modules = array_values( array_unique( $this->$param ) );
520 ?
$this->filterModules( $modules, $position )
525 * Add one or more modules recognized by the resource loader. Modules added
526 * through this function will be loaded by the resource loader when the
529 * @param string|array $modules Module name (string) or array of module names
531 public function addModules( $modules ) {
532 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
536 * Get the list of module JS to include on this page
538 * @param bool $filter
539 * @param string|null $position
541 * @return array Array of module names
543 public function getModuleScripts( $filter = false, $position = null ) {
544 return $this->getModules( $filter, $position, 'mModuleScripts' );
548 * Add only JS of one or more modules recognized by the resource loader. Module
549 * scripts added through this function will be loaded by the resource loader when
552 * @param string|array $modules Module name (string) or array of module names
554 public function addModuleScripts( $modules ) {
555 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
559 * Get the list of module CSS to include on this page
561 * @param bool $filter
562 * @param string|null $position
564 * @return array Array of module names
566 public function getModuleStyles( $filter = false, $position = null ) {
567 return $this->getModules( $filter, $position, 'mModuleStyles' );
571 * Add only CSS of one or more modules recognized by the resource loader.
573 * Module styles added through this function will be added using standard link CSS
574 * tags, rather than as a combined Javascript and CSS package. Thus, they will
575 * load when JavaScript is disabled (unless CSS also happens to be disabled).
577 * @param string|array $modules Module name (string) or array of module names
579 public function addModuleStyles( $modules ) {
580 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
584 * Get the list of module messages to include on this page
586 * @param bool $filter
587 * @param string|null $position
589 * @return array Array of module names
591 public function getModuleMessages( $filter = false, $position = null ) {
592 return $this->getModules( $filter, $position, 'mModuleMessages' );
596 * Add only messages of one or more modules recognized by the resource loader.
597 * Module messages added through this function will be loaded by the resource
598 * loader when the page loads.
600 * @param string|array $modules Module name (string) or array of module names
602 public function addModuleMessages( $modules ) {
603 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
607 * @return null|string ResourceLoader target
609 public function getTarget() {
610 return $this->mTarget
;
614 * Sets ResourceLoader target for load.php links. If null, will be omitted
616 * @param string|null $target
618 public function setTarget( $target ) {
619 $this->mTarget
= $target;
623 * Get an array of head items
627 function getHeadItemsArray() {
628 return $this->mHeadItems
;
632 * Get all header items in a string
635 * @deprecated since 1.24 Use OutputPage::headElement or
636 * if absolutely necessary use OutputPage::getHeadItemsArray
638 function getHeadItems() {
639 wfDeprecated( __METHOD__
, '1.24' );
641 foreach ( $this->mHeadItems
as $item ) {
648 * Add or replace an header item to the output
650 * @param string $name Item name
651 * @param string $value Raw HTML
653 public function addHeadItem( $name, $value ) {
654 $this->mHeadItems
[$name] = $value;
658 * Check if the header item $name is already set
660 * @param string $name Item name
663 public function hasHeadItem( $name ) {
664 return isset( $this->mHeadItems
[$name] );
668 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
670 * @param string $tag Value of "ETag" header
672 function setETag( $tag ) {
677 * Set whether the output should only contain the body of the article,
678 * without any skin, sidebar, etc.
679 * Used e.g. when calling with "action=render".
681 * @param bool $only Whether to output only the body of the article
683 public function setArticleBodyOnly( $only ) {
684 $this->mArticleBodyOnly
= $only;
688 * Return whether the output will contain only the body of the article
692 public function getArticleBodyOnly() {
693 return $this->mArticleBodyOnly
;
697 * Set an additional output property
700 * @param string $name
701 * @param mixed $value
703 public function setProperty( $name, $value ) {
704 $this->mProperties
[$name] = $value;
708 * Get an additional output property
711 * @param string $name
712 * @return mixed Property value or null if not found
714 public function getProperty( $name ) {
715 if ( isset( $this->mProperties
[$name] ) ) {
716 return $this->mProperties
[$name];
723 * checkLastModified tells the client to use the client-cached page if
724 * possible. If successful, the OutputPage is disabled so that
725 * any future call to OutputPage->output() have no effect.
727 * Side effect: sets mLastModified for Last-Modified header
729 * @param string $timestamp
731 * @return bool True if cache-ok headers was sent.
733 public function checkLastModified( $timestamp ) {
734 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
736 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
737 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
740 if ( !$wgCachePages ) {
741 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
745 $timestamp = wfTimestamp( TS_MW
, $timestamp );
746 $modifiedTimes = array(
747 'page' => $timestamp,
748 'user' => $this->getUser()->getTouched(),
749 'epoch' => $wgCacheEpoch
752 // bug 44570: the core page itself may not change, but resources might
753 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $wgSquidMaxage );
755 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
757 $maxModified = max( $modifiedTimes );
758 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
760 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
761 if ( $clientHeader === false ) {
762 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
766 # IE sends sizes after the date like this:
767 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
768 # this breaks strtotime().
769 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
771 wfSuppressWarnings(); // E_STRICT system time bitching
772 $clientHeaderTime = strtotime( $clientHeader );
774 if ( !$clientHeaderTime ) {
776 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
779 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
783 foreach ( $modifiedTimes as $name => $value ) {
784 if ( $info !== '' ) {
787 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
790 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
791 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
792 wfDebug( __METHOD__
. ": effective Last-Modified: " .
793 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
794 if ( $clientHeaderTime < $maxModified ) {
795 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
800 # Give a 304 response code and disable body output
801 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
802 ini_set( 'zlib.output_compression', 0 );
803 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
804 $this->sendCacheControl();
807 // Don't output a compressed blob when using ob_gzhandler;
808 // it's technically against HTTP spec and seems to confuse
809 // Firefox when the response gets split over two packets.
810 wfClearOutputBuffers();
816 * Override the last modified timestamp
818 * @param string $timestamp New timestamp, in a format readable by
821 public function setLastModified( $timestamp ) {
822 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
826 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
828 * @param string $policy The literal string to output as the contents of
829 * the meta tag. Will be parsed according to the spec and output in
833 public function setRobotPolicy( $policy ) {
834 $policy = Article
::formatRobotPolicy( $policy );
836 if ( isset( $policy['index'] ) ) {
837 $this->setIndexPolicy( $policy['index'] );
839 if ( isset( $policy['follow'] ) ) {
840 $this->setFollowPolicy( $policy['follow'] );
845 * Set the index policy for the page, but leave the follow policy un-
848 * @param string $policy Either 'index' or 'noindex'.
851 public function setIndexPolicy( $policy ) {
852 $policy = trim( $policy );
853 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
854 $this->mIndexPolicy
= $policy;
859 * Set the follow policy for the page, but leave the index policy un-
862 * @param string $policy Either 'follow' or 'nofollow'.
865 public function setFollowPolicy( $policy ) {
866 $policy = trim( $policy );
867 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
868 $this->mFollowPolicy
= $policy;
873 * Set the new value of the "action text", this will be added to the
874 * "HTML title", separated from it with " - ".
876 * @param string $text New value of the "action text"
878 public function setPageTitleActionText( $text ) {
879 $this->mPageTitleActionText
= $text;
883 * Get the value of the "action text"
887 public function getPageTitleActionText() {
888 return $this->mPageTitleActionText
;
892 * "HTML title" means the contents of "<title>".
893 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
895 * @param string $name
897 public function setHTMLTitle( $name ) {
898 if ( $name instanceof Message
) {
899 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
901 $this->mHTMLtitle
= $name;
906 * Return the "HTML title", i.e. the content of the "<title>" tag.
910 public function getHTMLTitle() {
911 return $this->mHTMLtitle
;
915 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
919 public function setRedirectedFrom( $t ) {
920 $this->mRedirectedFrom
= $t;
924 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
925 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
926 * but not bad tags like \<script\>. This function automatically sets
927 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
928 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
929 * good tags like \<i\> will be dropped entirely.
931 * @param string|Message $name
933 public function setPageTitle( $name ) {
934 if ( $name instanceof Message
) {
935 $name = $name->setContext( $this->getContext() )->text();
938 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
939 # but leave "<i>foobar</i>" alone
940 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
941 $this->mPagetitle
= $nameWithTags;
943 # change "<i>foo&bar</i>" to "foo&bar"
945 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
946 ->inContentLanguage()
951 * Return the "page title", i.e. the content of the \<h1\> tag.
955 public function getPageTitle() {
956 return $this->mPagetitle
;
960 * Set the Title object to use
964 public function setTitle( Title
$t ) {
965 $this->getContext()->setTitle( $t );
969 * Replace the subtitle with $str
971 * @param string|Message $str New value of the subtitle. String should be safe HTML.
973 public function setSubtitle( $str ) {
974 $this->clearSubtitle();
975 $this->addSubtitle( $str );
979 * Add $str to the subtitle
981 * @deprecated since 1.19; use addSubtitle() instead
982 * @param string|Message $str String or Message to add to the subtitle
984 public function appendSubtitle( $str ) {
985 $this->addSubtitle( $str );
989 * Add $str to the subtitle
991 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
993 public function addSubtitle( $str ) {
994 if ( $str instanceof Message
) {
995 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
997 $this->mSubtitle
[] = $str;
1002 * Add a subtitle containing a backlink to a page
1004 * @param Title $title Title to link to
1006 public function addBacklinkSubtitle( Title
$title ) {
1008 if ( $title->isRedirect() ) {
1009 $query['redirect'] = 'no';
1011 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1012 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1016 * Clear the subtitles
1018 public function clearSubtitle() {
1019 $this->mSubtitle
= array();
1027 public function getSubtitle() {
1028 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1032 * Set the page as printable, i.e. it'll be displayed with with all
1033 * print styles included
1035 public function setPrintable() {
1036 $this->mPrintable
= true;
1040 * Return whether the page is "printable"
1044 public function isPrintable() {
1045 return $this->mPrintable
;
1049 * Disable output completely, i.e. calling output() will have no effect
1051 public function disable() {
1052 $this->mDoNothing
= true;
1056 * Return whether the output will be completely disabled
1060 public function isDisabled() {
1061 return $this->mDoNothing
;
1065 * Show an "add new section" link?
1069 public function showNewSectionLink() {
1070 return $this->mNewSectionLink
;
1074 * Forcibly hide the new section link?
1078 public function forceHideNewSectionLink() {
1079 return $this->mHideNewSectionLink
;
1083 * Add or remove feed links in the page header
1084 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1085 * for the new version
1086 * @see addFeedLink()
1088 * @param bool $show True: add default feeds, false: remove all feeds
1090 public function setSyndicated( $show = true ) {
1092 $this->setFeedAppendQuery( false );
1094 $this->mFeedLinks
= array();
1099 * Add default feeds to the page header
1100 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1101 * for the new version
1102 * @see addFeedLink()
1104 * @param string $val Query to append to feed links or false to output
1107 public function setFeedAppendQuery( $val ) {
1108 global $wgAdvertisedFeedTypes;
1110 $this->mFeedLinks
= array();
1112 foreach ( $wgAdvertisedFeedTypes as $type ) {
1113 $query = "feed=$type";
1114 if ( is_string( $val ) ) {
1115 $query .= '&' . $val;
1117 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1122 * Add a feed link to the page header
1124 * @param string $format Feed type, should be a key of $wgFeedClasses
1125 * @param string $href URL
1127 public function addFeedLink( $format, $href ) {
1128 global $wgAdvertisedFeedTypes;
1130 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1131 $this->mFeedLinks
[$format] = $href;
1136 * Should we output feed links for this page?
1139 public function isSyndicated() {
1140 return count( $this->mFeedLinks
) > 0;
1144 * Return URLs for each supported syndication format for this page.
1145 * @return array Associating format keys with URLs
1147 public function getSyndicationLinks() {
1148 return $this->mFeedLinks
;
1152 * Will currently always return null
1156 public function getFeedAppendQuery() {
1157 return $this->mFeedLinksAppendQuery
;
1161 * Set whether the displayed content is related to the source of the
1162 * corresponding article on the wiki
1163 * Setting true will cause the change "article related" toggle to true
1167 public function setArticleFlag( $v ) {
1168 $this->mIsarticle
= $v;
1170 $this->mIsArticleRelated
= $v;
1175 * Return whether the content displayed page is related to the source of
1176 * the corresponding article on the wiki
1180 public function isArticle() {
1181 return $this->mIsarticle
;
1185 * Set whether this page is related an article on the wiki
1186 * Setting false will cause the change of "article flag" toggle to false
1190 public function setArticleRelated( $v ) {
1191 $this->mIsArticleRelated
= $v;
1193 $this->mIsarticle
= false;
1198 * Return whether this page is related an article on the wiki
1202 public function isArticleRelated() {
1203 return $this->mIsArticleRelated
;
1207 * Add new language links
1209 * @param array $newLinkArray Associative array mapping language code to the page
1212 public function addLanguageLinks( $newLinkArray ) {
1213 $this->mLanguageLinks +
= $newLinkArray;
1217 * Reset the language links and add new language links
1219 * @param array $newLinkArray Associative array mapping language code to the page
1222 public function setLanguageLinks( $newLinkArray ) {
1223 $this->mLanguageLinks
= $newLinkArray;
1227 * Get the list of language links
1229 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1231 public function getLanguageLinks() {
1232 return $this->mLanguageLinks
;
1236 * Add an array of categories, with names in the keys
1238 * @param array $categories Mapping category name => sort key
1240 public function addCategoryLinks( $categories ) {
1243 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1247 # Add the links to a LinkBatch
1248 $arr = array( NS_CATEGORY
=> $categories );
1249 $lb = new LinkBatch
;
1250 $lb->setArray( $arr );
1252 # Fetch existence plus the hiddencat property
1253 $dbr = wfGetDB( DB_SLAVE
);
1254 $res = $dbr->select( array( 'page', 'page_props' ),
1255 array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1256 'page_is_redirect', 'page_latest', 'pp_value' ),
1257 $lb->constructSet( 'page', $dbr ),
1260 array( 'page_props' => array( 'LEFT JOIN', array(
1261 'pp_propname' => 'hiddencat',
1266 # Add the results to the link cache
1267 $lb->addResultToCache( LinkCache
::singleton(), $res );
1269 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1270 $categories = array_combine(
1271 array_keys( $categories ),
1272 array_fill( 0, count( $categories ), 'normal' )
1275 # Mark hidden categories
1276 foreach ( $res as $row ) {
1277 if ( isset( $row->pp_value
) ) {
1278 $categories[$row->page_title
] = 'hidden';
1282 # Add the remaining categories to the skin
1284 'OutputPageMakeCategoryLinks',
1285 array( &$this, $categories, &$this->mCategoryLinks
) )
1287 foreach ( $categories as $category => $type ) {
1288 $origcategory = $category;
1289 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1293 $wgContLang->findVariantLink( $category, $title, true );
1294 if ( $category != $origcategory ) {
1295 if ( array_key_exists( $category, $categories ) ) {
1299 $text = $wgContLang->convertHtml( $title->getText() );
1300 $this->mCategories
[] = $title->getText();
1301 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1307 * Reset the category links (but not the category list) and add $categories
1309 * @param array $categories Mapping category name => sort key
1311 public function setCategoryLinks( $categories ) {
1312 $this->mCategoryLinks
= array();
1313 $this->addCategoryLinks( $categories );
1317 * Get the list of category links, in a 2-D array with the following format:
1318 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1319 * hidden categories) and $link a HTML fragment with a link to the category
1324 public function getCategoryLinks() {
1325 return $this->mCategoryLinks
;
1329 * Get the list of category names this page belongs to
1331 * @return array Array of strings
1333 public function getCategories() {
1334 return $this->mCategories
;
1338 * Do not allow scripts which can be modified by wiki users to load on this page;
1339 * only allow scripts bundled with, or generated by, the software.
1341 public function disallowUserJs() {
1342 $this->reduceAllowedModules(
1343 ResourceLoaderModule
::TYPE_SCRIPTS
,
1344 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1349 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1350 * @see ResourceLoaderModule::$origin
1351 * @param string $type ResourceLoaderModule TYPE_ constant
1352 * @return int ResourceLoaderModule ORIGIN_ class constant
1354 public function getAllowedModules( $type ) {
1355 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1356 return min( array_values( $this->mAllowedModules
) );
1358 return isset( $this->mAllowedModules
[$type] )
1359 ?
$this->mAllowedModules
[$type]
1360 : ResourceLoaderModule
::ORIGIN_ALL
;
1365 * Set the highest level of CSS/JS untrustworthiness allowed
1366 * @param string $type ResourceLoaderModule TYPE_ constant
1367 * @param int $level ResourceLoaderModule class constant
1369 public function setAllowedModules( $type, $level ) {
1370 $this->mAllowedModules
[$type] = $level;
1374 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1375 * @param string $type
1376 * @param int $level ResourceLoaderModule class constant
1378 public function reduceAllowedModules( $type, $level ) {
1379 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1383 * Prepend $text to the body HTML
1385 * @param string $text HTML
1387 public function prependHTML( $text ) {
1388 $this->mBodytext
= $text . $this->mBodytext
;
1392 * Append $text to the body HTML
1394 * @param string $text HTML
1396 public function addHTML( $text ) {
1397 $this->mBodytext
.= $text;
1401 * Shortcut for adding an Html::element via addHTML.
1405 * @param string $element
1406 * @param array $attribs
1407 * @param string $contents
1409 public function addElement( $element, $attribs = array(), $contents = '' ) {
1410 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1414 * Clear the body HTML
1416 public function clearHTML() {
1417 $this->mBodytext
= '';
1423 * @return string HTML
1425 public function getHTML() {
1426 return $this->mBodytext
;
1430 * Get/set the ParserOptions object to use for wikitext parsing
1432 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1433 * current ParserOption object
1434 * @return ParserOptions
1436 public function parserOptions( $options = null ) {
1437 if ( !$this->mParserOptions
) {
1438 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1439 $this->mParserOptions
->setEditSection( false );
1441 return wfSetVar( $this->mParserOptions
, $options );
1445 * Set the revision ID which will be seen by the wiki text parser
1446 * for things such as embedded {{REVISIONID}} variable use.
1448 * @param int|null $revid An positive integer, or null
1449 * @return mixed Previous value
1451 public function setRevisionId( $revid ) {
1452 $val = is_null( $revid ) ?
null : intval( $revid );
1453 return wfSetVar( $this->mRevisionId
, $val );
1457 * Get the displayed revision ID
1461 public function getRevisionId() {
1462 return $this->mRevisionId
;
1466 * Set the timestamp of the revision which will be displayed. This is used
1467 * to avoid a extra DB call in Skin::lastModified().
1469 * @param string|null $timestamp
1470 * @return mixed Previous value
1472 public function setRevisionTimestamp( $timestamp ) {
1473 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1477 * Get the timestamp of displayed revision.
1478 * This will be null if not filled by setRevisionTimestamp().
1480 * @return string|null
1482 public function getRevisionTimestamp() {
1483 return $this->mRevisionTimestamp
;
1487 * Set the displayed file version
1489 * @param File|bool $file
1490 * @return mixed Previous value
1492 public function setFileVersion( $file ) {
1494 if ( $file instanceof File
&& $file->exists() ) {
1495 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1497 return wfSetVar( $this->mFileVersion
, $val, true );
1501 * Get the displayed file version
1503 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1505 public function getFileVersion() {
1506 return $this->mFileVersion
;
1510 * Get the templates used on this page
1512 * @return array (namespace => dbKey => revId)
1515 public function getTemplateIds() {
1516 return $this->mTemplateIds
;
1520 * Get the files used on this page
1522 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1525 public function getFileSearchOptions() {
1526 return $this->mImageTimeKeys
;
1530 * Convert wikitext to HTML and add it to the buffer
1531 * Default assumes that the current page title will be used.
1533 * @param string $text
1534 * @param bool $linestart Is this the start of a line?
1535 * @param bool $interface Is this text in the user interface language?
1537 public function addWikiText( $text, $linestart = true, $interface = true ) {
1538 $title = $this->getTitle(); // Work around E_STRICT
1540 throw new MWException( 'Title is null' );
1542 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1546 * Add wikitext with a custom Title object
1548 * @param string $text Wikitext
1549 * @param Title $title
1550 * @param bool $linestart Is this the start of a line?
1552 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1553 $this->addWikiTextTitle( $text, $title, $linestart );
1557 * Add wikitext with a custom Title object and tidy enabled.
1559 * @param string $text Wikitext
1560 * @param Title $title
1561 * @param bool $linestart Is this the start of a line?
1563 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1564 $this->addWikiTextTitle( $text, $title, $linestart, true );
1568 * Add wikitext with tidy enabled
1570 * @param string $text Wikitext
1571 * @param bool $linestart Is this the start of a line?
1573 public function addWikiTextTidy( $text, $linestart = true ) {
1574 $title = $this->getTitle();
1575 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1579 * Add wikitext with a custom Title object
1581 * @param string $text Wikitext
1582 * @param Title $title
1583 * @param bool $linestart Is this the start of a line?
1584 * @param bool $tidy Whether to use tidy
1585 * @param bool $interface Whether it is an interface message
1586 * (for example disables conversion)
1588 public function addWikiTextTitle( $text, Title
$title, $linestart,
1589 $tidy = false, $interface = false
1593 wfProfileIn( __METHOD__
);
1595 $popts = $this->parserOptions();
1596 $oldTidy = $popts->setTidy( $tidy );
1597 $popts->setInterfaceMessage( (bool)$interface );
1599 $parserOutput = $wgParser->getFreshParser()->parse(
1600 $text, $title, $popts,
1601 $linestart, true, $this->mRevisionId
1604 $popts->setTidy( $oldTidy );
1606 $this->addParserOutput( $parserOutput );
1608 wfProfileOut( __METHOD__
);
1612 * Add a ParserOutput object, but without Html.
1614 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1615 * @param ParserOutput $parserOutput
1617 public function addParserOutputNoText( &$parserOutput ) {
1618 $this->addParserOutputMetadata( $parserOutput );
1622 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1623 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1627 * @param ParserOutput $parserOutput
1629 public function addParserOutputMetadata( &$parserOutput ) {
1630 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1631 $this->addCategoryLinks( $parserOutput->getCategories() );
1632 $this->mNewSectionLink
= $parserOutput->getNewSection();
1633 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1635 $this->mParseWarnings
= $parserOutput->getWarnings();
1636 if ( !$parserOutput->isCacheable() ) {
1637 $this->enableClientCache( false );
1639 $this->mNoGallery
= $parserOutput->getNoGallery();
1640 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1641 $this->addModules( $parserOutput->getModules() );
1642 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1643 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1644 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1645 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1647 // Template versioning...
1648 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1649 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1650 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1652 $this->mTemplateIds
[$ns] = $dbks;
1655 // File versioning...
1656 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1657 $this->mImageTimeKeys
[$dbk] = $data;
1660 // Hooks registered in the object
1661 global $wgParserOutputHooks;
1662 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1663 list( $hookName, $data ) = $hookInfo;
1664 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1665 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1669 // Link flags are ignored for now, but may in the future be
1670 // used to mark individual language links.
1671 $linkFlags = array();
1672 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1673 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1677 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1678 * ParserOutput object, without any other metadata.
1681 * @param ParserOutput $parserOutput
1683 public function addParserOutputContent( &$parserOutput ) {
1684 $this->addParserOutputText( $parserOutput );
1686 $this->addModules( $parserOutput->getModules() );
1687 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1688 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1689 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1691 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1695 * Add the HTML associated with a ParserOutput object, without any metadata.
1698 * @param ParserOutput $parserOutput
1700 public function addParserOutputText( &$parserOutput ) {
1701 $text = $parserOutput->getText();
1702 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1703 $this->addHTML( $text );
1707 * Add everything from a ParserOutput object.
1709 * @param ParserOutput $parserOutput
1711 function addParserOutput( &$parserOutput ) {
1712 $this->addParserOutputMetadata( $parserOutput );
1713 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1715 // Touch section edit links only if not previously disabled
1716 if ( $parserOutput->getEditSectionTokens() ) {
1717 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1720 $this->addParserOutputText( $parserOutput );
1724 * Add the output of a QuickTemplate to the output buffer
1726 * @param QuickTemplate $template
1728 public function addTemplate( &$template ) {
1729 $this->addHTML( $template->getHTML() );
1733 * Parse wikitext and return the HTML.
1735 * @param string $text
1736 * @param bool $linestart Is this the start of a line?
1737 * @param bool $interface Use interface language ($wgLang instead of
1738 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1739 * This also disables LanguageConverter.
1740 * @param Language $language Target language object, will override $interface
1741 * @throws MWException
1742 * @return string HTML
1744 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1747 if ( is_null( $this->getTitle() ) ) {
1748 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1751 $popts = $this->parserOptions();
1753 $popts->setInterfaceMessage( true );
1755 if ( $language !== null ) {
1756 $oldLang = $popts->setTargetLanguage( $language );
1759 $parserOutput = $wgParser->getFreshParser()->parse(
1760 $text, $this->getTitle(), $popts,
1761 $linestart, true, $this->mRevisionId
1765 $popts->setInterfaceMessage( false );
1767 if ( $language !== null ) {
1768 $popts->setTargetLanguage( $oldLang );
1771 return $parserOutput->getText();
1775 * Parse wikitext, strip paragraphs, and return the HTML.
1777 * @param string $text
1778 * @param bool $linestart Is this the start of a line?
1779 * @param bool $interface Use interface language ($wgLang instead of
1780 * $wgContLang) while parsing language sensitive magic
1781 * words like GRAMMAR and PLURAL
1782 * @return string HTML
1784 public function parseInline( $text, $linestart = true, $interface = false ) {
1785 $parsed = $this->parse( $text, $linestart, $interface );
1786 return Parser
::stripOuterParagraph( $parsed );
1790 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1792 * @param int $maxage Maximum cache time on the Squid, in seconds.
1794 public function setSquidMaxage( $maxage ) {
1795 $this->mSquidMaxage
= $maxage;
1799 * Use enableClientCache(false) to force it to send nocache headers
1801 * @param bool $state
1805 public function enableClientCache( $state ) {
1806 return wfSetVar( $this->mEnableClientCache
, $state );
1810 * Get the list of cookies that will influence on the cache
1814 function getCacheVaryCookies() {
1815 global $wgCookiePrefix, $wgCacheVaryCookies;
1817 if ( $cookies === null ) {
1818 $cookies = array_merge(
1820 "{$wgCookiePrefix}Token",
1821 "{$wgCookiePrefix}LoggedOut",
1827 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1833 * Check if the request has a cache-varying cookie header
1834 * If it does, it's very important that we don't allow public caching
1838 function haveCacheVaryCookies() {
1839 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1840 if ( $cookieHeader === false ) {
1843 $cvCookies = $this->getCacheVaryCookies();
1844 foreach ( $cvCookies as $cookieName ) {
1845 # Check for a simple string match, like the way squid does it
1846 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1847 wfDebug( __METHOD__
. ": found $cookieName\n" );
1851 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1856 * Add an HTTP header that will influence on the cache
1858 * @param string $header Header name
1859 * @param array|null $option
1860 * @todo FIXME: Document the $option parameter; it appears to be for
1861 * X-Vary-Options but what format is acceptable?
1863 public function addVaryHeader( $header, $option = null ) {
1864 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1865 $this->mVaryHeader
[$header] = (array)$option;
1866 } elseif ( is_array( $option ) ) {
1867 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1868 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1870 $this->mVaryHeader
[$header] = $option;
1873 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1877 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1878 * such as Accept-Encoding or Cookie
1882 public function getVaryHeader() {
1883 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1887 * Get a complete X-Vary-Options header
1891 public function getXVO() {
1892 $cvCookies = $this->getCacheVaryCookies();
1894 $cookiesOption = array();
1895 foreach ( $cvCookies as $cookieName ) {
1896 $cookiesOption[] = 'string-contains=' . $cookieName;
1898 $this->addVaryHeader( 'Cookie', $cookiesOption );
1901 foreach ( $this->mVaryHeader
as $header => $option ) {
1902 $newheader = $header;
1903 if ( is_array( $option ) && count( $option ) > 0 ) {
1904 $newheader .= ';' . implode( ';', $option );
1906 $headers[] = $newheader;
1908 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1914 * bug 21672: Add Accept-Language to Vary and XVO headers
1915 * if there's no 'variant' parameter existed in GET.
1918 * /w/index.php?title=Main_page should always be served; but
1919 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1921 function addAcceptLanguage() {
1922 $title = $this->getTitle();
1923 if ( !$title instanceof Title
) {
1927 $lang = $title->getPageLanguage();
1928 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1929 $variants = $lang->getVariants();
1930 $aloption = array();
1931 foreach ( $variants as $variant ) {
1932 if ( $variant === $lang->getCode() ) {
1935 $aloption[] = 'string-contains=' . $variant;
1937 // IE and some other browsers use BCP 47 standards in
1938 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1939 // We should handle these too.
1940 $variantBCP47 = wfBCP47( $variant );
1941 if ( $variantBCP47 !== $variant ) {
1942 $aloption[] = 'string-contains=' . $variantBCP47;
1946 $this->addVaryHeader( 'Accept-Language', $aloption );
1951 * Set a flag which will cause an X-Frame-Options header appropriate for
1952 * edit pages to be sent. The header value is controlled by
1953 * $wgEditPageFrameOptions.
1955 * This is the default for special pages. If you display a CSRF-protected
1956 * form on an ordinary view page, then you need to call this function.
1958 * @param bool $enable
1960 public function preventClickjacking( $enable = true ) {
1961 $this->mPreventClickjacking
= $enable;
1965 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1966 * This can be called from pages which do not contain any CSRF-protected
1969 public function allowClickjacking() {
1970 $this->mPreventClickjacking
= false;
1974 * Get the X-Frame-Options header value (without the name part), or false
1975 * if there isn't one. This is used by Skin to determine whether to enable
1976 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1980 public function getFrameOptions() {
1981 global $wgBreakFrames, $wgEditPageFrameOptions;
1982 if ( $wgBreakFrames ) {
1984 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1985 return $wgEditPageFrameOptions;
1991 * Send cache control HTTP headers
1993 public function sendCacheControl() {
1994 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1996 $response = $this->getRequest()->response();
1997 if ( $wgUseETag && $this->mETag
) {
1998 $response->header( "ETag: $this->mETag" );
2001 $this->addVaryHeader( 'Cookie' );
2002 $this->addAcceptLanguage();
2004 # don't serve compressed data to clients who can't handle it
2005 # maintain different caches for logged-in users and non-logged in ones
2006 $response->header( $this->getVaryHeader() );
2009 # Add an X-Vary-Options header for Squid with Wikimedia patches
2010 $response->header( $this->getXVO() );
2013 if ( $this->mEnableClientCache
) {
2015 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
2016 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2019 # We'll purge the proxy cache explicitly, but require end user agents
2020 # to revalidate against the proxy on each visit.
2021 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2022 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2023 # start with a shorter timeout for initial testing
2024 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2025 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
2026 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2027 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2029 # We'll purge the proxy cache for anons explicitly, but require end user agents
2030 # to revalidate against the proxy on each visit.
2031 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2032 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2033 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2034 # start with a shorter timeout for initial testing
2035 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2036 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2037 . ', must-revalidate, max-age=0' );
2040 # We do want clients to cache if they can, but they *must* check for updates
2041 # on revisiting the page.
2042 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2043 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2044 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2046 if ( $this->mLastModified
) {
2047 $response->header( "Last-Modified: {$this->mLastModified}" );
2050 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2052 # In general, the absence of a last modified header should be enough to prevent
2053 # the client from using its cache. We send a few other things just to make sure.
2054 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2055 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2056 $response->header( 'Pragma: no-cache' );
2061 * Finally, all the text has been munged and accumulated into
2062 * the object, let's actually output it:
2064 public function output() {
2065 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
2066 $wgResponsiveImages;
2068 if ( $this->mDoNothing
) {
2072 wfProfileIn( __METHOD__
);
2074 $response = $this->getRequest()->response();
2076 if ( $this->mRedirect
!= '' ) {
2077 # Standards require redirect URLs to be absolute
2078 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2080 $redirect = $this->mRedirect
;
2081 $code = $this->mRedirectCode
;
2083 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2084 if ( $code == '301' ||
$code == '303' ) {
2085 if ( !$wgDebugRedirects ) {
2086 $message = HttpStatus
::getMessage( $code );
2087 $response->header( "HTTP/1.1 $code $message" );
2089 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2091 if ( $wgVaryOnXFP ) {
2092 $this->addVaryHeader( 'X-Forwarded-Proto' );
2094 $this->sendCacheControl();
2096 $response->header( "Content-Type: text/html; charset=utf-8" );
2097 if ( $wgDebugRedirects ) {
2098 $url = htmlspecialchars( $redirect );
2099 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2100 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2101 print "</body>\n</html>\n";
2103 $response->header( 'Location: ' . $redirect );
2107 wfProfileOut( __METHOD__
);
2109 } elseif ( $this->mStatusCode
) {
2110 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2112 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2116 # Buffer output; final headers may depend on later processing
2119 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2120 $response->header( 'Content-language: ' . $wgLanguageCode );
2122 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2123 // jQuery etc. can work correctly.
2124 $response->header( 'X-UA-Compatible: IE=Edge' );
2126 // Prevent framing, if requested
2127 $frameOptions = $this->getFrameOptions();
2128 if ( $frameOptions ) {
2129 $response->header( "X-Frame-Options: $frameOptions" );
2132 if ( $this->mArticleBodyOnly
) {
2133 echo $this->mBodytext
;
2136 $sk = $this->getSkin();
2137 // add skin specific modules
2138 $modules = $sk->getDefaultModules();
2140 // enforce various default modules for all skins
2141 $coreModules = array(
2142 // keep this list as small as possible
2143 'mediawiki.page.startup',
2147 // Support for high-density display images if enabled
2148 if ( $wgResponsiveImages ) {
2149 $coreModules[] = 'mediawiki.hidpi';
2152 $this->addModules( $coreModules );
2153 foreach ( $modules as $group ) {
2154 $this->addModules( $group );
2156 MWDebug
::addModules( $this );
2158 // Hook that allows last minute changes to the output page, e.g.
2159 // adding of CSS or Javascript by extensions.
2160 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2162 wfProfileIn( 'Output-skin' );
2164 wfProfileOut( 'Output-skin' );
2167 // This hook allows last minute changes to final overall output by modifying output buffer
2168 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2170 $this->sendCacheControl();
2174 wfProfileOut( __METHOD__
);
2178 * Actually output something with print.
2180 * @param string $ins The string to output
2181 * @deprecated since 1.22 Use echo yourself.
2183 public function out( $ins ) {
2184 wfDeprecated( __METHOD__
, '1.22' );
2189 * Produce a "user is blocked" page.
2190 * @deprecated since 1.18
2192 function blockedPage() {
2193 throw new UserBlockedError( $this->getUser()->mBlock
);
2197 * Prepare this object to display an error page; disable caching and
2198 * indexing, clear the current text and redirect, set the page's title
2199 * and optionally an custom HTML title (content of the "<title>" tag).
2201 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2202 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2203 * optional, if not passed the "<title>" attribute will be
2204 * based on $pageTitle
2206 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2207 $this->setPageTitle( $pageTitle );
2208 if ( $htmlTitle !== false ) {
2209 $this->setHTMLTitle( $htmlTitle );
2211 $this->setRobotPolicy( 'noindex,nofollow' );
2212 $this->setArticleRelated( false );
2213 $this->enableClientCache( false );
2214 $this->mRedirect
= '';
2215 $this->clearSubtitle();
2220 * Output a standard error page
2222 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2223 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2224 * showErrorPage( 'titlemsg', $messageObject );
2225 * showErrorPage( $titleMessageObject, $messageObject );
2227 * @param string|Message $title Message key (string) for page title, or a Message object
2228 * @param string|Message $msg Message key (string) for page text, or a Message object
2229 * @param array $params Message parameters; ignored if $msg is a Message object
2231 public function showErrorPage( $title, $msg, $params = array() ) {
2232 if ( !$title instanceof Message
) {
2233 $title = $this->msg( $title );
2236 $this->prepareErrorPage( $title );
2238 if ( $msg instanceof Message
) {
2239 if ( $params !== array() ) {
2240 trigger_error( 'Argument ignored: $params. The message parameters argument '
2241 . 'is discarded when the $msg argument is a Message object instead of '
2242 . 'a string.', E_USER_NOTICE
);
2244 $this->addHTML( $msg->parseAsBlock() );
2246 $this->addWikiMsgArray( $msg, $params );
2249 $this->returnToMain();
2253 * Output a standard permission error page
2255 * @param array $errors Error message keys
2256 * @param string $action Action that was denied or null if unknown
2258 public function showPermissionsErrorPage( $errors, $action = null ) {
2259 // For some action (read, edit, create and upload), display a "login to do this action"
2260 // error if all of the following conditions are met:
2261 // 1. the user is not logged in
2262 // 2. the only error is insufficient permissions (i.e. no block or something else)
2263 // 3. the error can be avoided simply by logging in
2264 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2265 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2266 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2267 && ( User
::groupHasPermission( 'user', $action )
2268 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2270 $displayReturnto = null;
2272 # Due to bug 32276, if a user does not have read permissions,
2273 # $this->getTitle() will just give Special:Badtitle, which is
2274 # not especially useful as a returnto parameter. Use the title
2275 # from the request instead, if there was one.
2276 $request = $this->getRequest();
2277 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2278 if ( $action == 'edit' ) {
2279 $msg = 'whitelistedittext';
2280 $displayReturnto = $returnto;
2281 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2282 $msg = 'nocreatetext';
2283 } elseif ( $action == 'upload' ) {
2284 $msg = 'uploadnologintext';
2286 $msg = 'loginreqpagetext';
2287 $displayReturnto = Title
::newMainPage();
2293 $query['returnto'] = $returnto->getPrefixedText();
2295 if ( !$request->wasPosted() ) {
2296 $returntoquery = $request->getValues();
2297 unset( $returntoquery['title'] );
2298 unset( $returntoquery['returnto'] );
2299 unset( $returntoquery['returntoquery'] );
2300 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2303 $loginLink = Linker
::linkKnown(
2304 SpecialPage
::getTitleFor( 'Userlogin' ),
2305 $this->msg( 'loginreqlink' )->escaped(),
2310 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2311 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2313 # Don't return to a page the user can't read otherwise
2314 # we'll end up in a pointless loop
2315 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2316 $this->returnToMain( null, $displayReturnto );
2319 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2320 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2325 * Display an error page indicating that a given version of MediaWiki is
2326 * required to use it
2328 * @param mixed $version The version of MediaWiki needed to use the page
2330 public function versionRequired( $version ) {
2331 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2333 $this->addWikiMsg( 'versionrequiredtext', $version );
2334 $this->returnToMain();
2338 * Display an error page noting that a given permission bit is required.
2339 * @deprecated since 1.18, just throw the exception directly
2340 * @param string $permission Key required
2341 * @throws PermissionsError
2343 public function permissionRequired( $permission ) {
2344 throw new PermissionsError( $permission );
2348 * Produce the stock "please login to use the wiki" page
2350 * @deprecated since 1.19; throw the exception directly
2352 public function loginToUse() {
2353 throw new PermissionsError( 'read' );
2357 * Format a list of error messages
2359 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2360 * @param string $action Action that was denied or null if unknown
2361 * @return string The wikitext error-messages, formatted into a list.
2363 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2364 if ( $action == null ) {
2365 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2367 $action_desc = $this->msg( "action-$action" )->plain();
2369 'permissionserrorstext-withaction',
2372 )->plain() . "\n\n";
2375 if ( count( $errors ) > 1 ) {
2376 $text .= '<ul class="permissions-errors">' . "\n";
2378 foreach ( $errors as $error ) {
2380 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2385 $text .= "<div class=\"permissions-errors\">\n" .
2386 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2394 * Display a page stating that the Wiki is in read-only mode,
2395 * and optionally show the source of the page that the user
2396 * was trying to edit. Should only be called (for this
2397 * purpose) after wfReadOnly() has returned true.
2399 * For historical reasons, this function is _also_ used to
2400 * show the error message when a user tries to edit a page
2401 * they are not allowed to edit. (Unless it's because they're
2402 * blocked, then we show blockedPage() instead.) In this
2403 * case, the second parameter should be set to true and a list
2404 * of reasons supplied as the third parameter.
2406 * @todo Needs to be split into multiple functions.
2408 * @param string $source Source code to show (or null).
2409 * @param bool $protected Is this a permissions error?
2410 * @param array $reasons List of reasons for this error, as returned by
2411 * Title::getUserPermissionsErrors().
2412 * @param string $action Action that was denied or null if unknown
2413 * @throws ReadOnlyError
2415 public function readOnlyPage( $source = null, $protected = false,
2416 $reasons = array(), $action = null
2418 $this->setRobotPolicy( 'noindex,nofollow' );
2419 $this->setArticleRelated( false );
2421 // If no reason is given, just supply a default "I can't let you do
2422 // that, Dave" message. Should only occur if called by legacy code.
2423 if ( $protected && empty( $reasons ) ) {
2424 $reasons[] = array( 'badaccess-group0' );
2427 if ( !empty( $reasons ) ) {
2428 // Permissions error
2430 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2431 $this->addBacklinkSubtitle( $this->getTitle() );
2433 $this->setPageTitle( $this->msg( 'badaccess' ) );
2435 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2437 // Wiki is read only
2438 throw new ReadOnlyError
;
2441 // Show source, if supplied
2442 if ( is_string( $source ) ) {
2443 $this->addWikiMsg( 'viewsourcetext' );
2445 $pageLang = $this->getTitle()->getPageLanguage();
2447 'id' => 'wpTextbox1',
2448 'name' => 'wpTextbox1',
2449 'cols' => $this->getUser()->getOption( 'cols' ),
2450 'rows' => $this->getUser()->getOption( 'rows' ),
2451 'readonly' => 'readonly',
2452 'lang' => $pageLang->getHtmlCode(),
2453 'dir' => $pageLang->getDir(),
2455 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2457 // Show templates used by this article
2458 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2459 $this->addHTML( "<div class='templatesUsed'>
2465 # If the title doesn't exist, it's fairly pointless to print a return
2466 # link to it. After all, you just tried editing it and couldn't, so
2467 # what's there to do there?
2468 if ( $this->getTitle()->exists() ) {
2469 $this->returnToMain( null, $this->getTitle() );
2474 * Turn off regular page output and return an error response
2475 * for when rate limiting has triggered.
2477 public function rateLimited() {
2478 throw new ThrottledError
;
2482 * Show a warning about slave lag
2484 * If the lag is higher than $wgSlaveLagCritical seconds,
2485 * then the warning is a bit more obvious. If the lag is
2486 * lower than $wgSlaveLagWarning, then no warning is shown.
2488 * @param int $lag Slave lag
2490 public function showLagWarning( $lag ) {
2491 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2492 if ( $lag >= $wgSlaveLagWarning ) {
2493 $message = $lag < $wgSlaveLagCritical
2496 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2497 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2501 public function showFatalError( $message ) {
2502 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2504 $this->addHTML( $message );
2507 public function showUnexpectedValueError( $name, $val ) {
2508 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2511 public function showFileCopyError( $old, $new ) {
2512 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2515 public function showFileRenameError( $old, $new ) {
2516 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2519 public function showFileDeleteError( $name ) {
2520 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2523 public function showFileNotFoundError( $name ) {
2524 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2528 * Add a "return to" link pointing to a specified title
2530 * @param Title $title Title to link
2531 * @param array $query Query string parameters
2532 * @param string $text Text of the link (input is not escaped)
2533 * @param array $options Options array to pass to Linker
2535 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2536 $link = $this->msg( 'returnto' )->rawParams(
2537 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2538 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2542 * Add a "return to" link pointing to a specified title,
2543 * or the title indicated in the request, or else the main page
2545 * @param mixed $unused
2546 * @param Title|string $returnto Title or String to return to
2547 * @param string $returntoquery Query string for the return to link
2549 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2550 if ( $returnto == null ) {
2551 $returnto = $this->getRequest()->getText( 'returnto' );
2554 if ( $returntoquery == null ) {
2555 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2558 if ( $returnto === '' ) {
2559 $returnto = Title
::newMainPage();
2562 if ( is_object( $returnto ) ) {
2563 $titleObj = $returnto;
2565 $titleObj = Title
::newFromText( $returnto );
2567 if ( !is_object( $titleObj ) ) {
2568 $titleObj = Title
::newMainPage();
2571 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2575 * @param Skin $sk The given Skin
2576 * @param bool $includeStyle Unused
2577 * @return string The doctype, opening "<html>", and head element.
2579 public function headElement( Skin
$sk, $includeStyle = true ) {
2580 global $wgContLang, $wgMimeType;
2582 $userdir = $this->getLanguage()->getDir();
2583 $sitedir = $wgContLang->getDir();
2585 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2587 if ( $this->getHTMLTitle() == '' ) {
2588 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2591 $openHead = Html
::openElement( 'head' );
2593 # Don't bother with the newline if $head == ''
2594 $ret .= "$openHead\n";
2597 if ( !Html
::isXmlMimeType( $wgMimeType ) ) {
2598 // Add <meta charset="UTF-8">
2599 // This should be before <title> since it defines the charset used by
2600 // text including the text inside <title>.
2601 // The spec recommends defining XHTML5's charset using the XML declaration
2603 // Our XML declaration is output by Html::htmlHeader.
2604 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2605 // http://www.whatwg.org/html/semantics.html#charset
2606 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2609 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2611 foreach ( $this->getHeadLinksArray() as $item ) {
2612 $ret .= $item . "\n";
2615 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2616 $ret .= $this->buildCssLinks();
2618 $ret .= $this->getHeadScripts() . "\n";
2620 foreach ( $this->mHeadItems
as $item ) {
2621 $ret .= $item . "\n";
2624 $closeHead = Html
::closeElement( 'head' );
2626 $ret .= "$closeHead\n";
2629 $bodyClasses = array();
2630 $bodyClasses[] = 'mediawiki';
2632 # Classes for LTR/RTL directionality support
2633 $bodyClasses[] = $userdir;
2634 $bodyClasses[] = "sitedir-$sitedir";
2636 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2637 # A <body> class is probably not the best way to do this . . .
2638 $bodyClasses[] = 'capitalize-all-nouns';
2641 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2642 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2644 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2646 $bodyAttrs = array();
2647 // While the implode() is not strictly needed, it's used for backwards compatibility
2648 // (this used to be built as a string and hooks likely still expect that).
2649 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2651 // Allow skins and extensions to add body attributes they need
2652 $sk->addToBodyAttributes( $this, $bodyAttrs );
2653 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2655 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2661 * Get a ResourceLoader object associated with this OutputPage
2663 * @return ResourceLoader
2665 public function getResourceLoader() {
2666 if ( is_null( $this->mResourceLoader
) ) {
2667 $this->mResourceLoader
= new ResourceLoader();
2669 return $this->mResourceLoader
;
2674 * @param array|string $modules One or more module names
2675 * @param string $only ResourceLoaderModule TYPE_ class constant
2676 * @param bool $useESI
2677 * @param array $extraQuery Array with extra query parameters to add to each
2678 * request. array( param => value ).
2679 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2680 * call rather than a "<script src='...'>" tag.
2681 * @return string The html "<script>", "<link>" and "<style>" tags
2683 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2684 array $extraQuery = array(), $loadCall = false
2686 global $wgResourceLoaderUseESI;
2688 $modules = (array)$modules;
2692 'states' => array(),
2695 if ( !count( $modules ) ) {
2699 if ( count( $modules ) > 1 ) {
2700 // Remove duplicate module requests
2701 $modules = array_unique( $modules );
2702 // Sort module names so requests are more uniform
2705 if ( ResourceLoader
::inDebugMode() ) {
2706 // Recursively call us for every item
2707 foreach ( $modules as $name ) {
2708 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2709 $links['html'] .= $link['html'];
2710 $links['states'] +
= $link['states'];
2716 if ( !is_null( $this->mTarget
) ) {
2717 $extraQuery['target'] = $this->mTarget
;
2720 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2721 $sortedModules = array();
2722 $resourceLoader = $this->getResourceLoader();
2723 foreach ( $modules as $name ) {
2724 $module = $resourceLoader->getModule( $name );
2725 # Check that we're allowed to include this module on this page
2727 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2728 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2729 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2730 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2731 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2736 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2739 foreach ( $sortedModules as $source => $groups ) {
2740 foreach ( $groups as $group => $grpModules ) {
2741 // Special handling for user-specific groups
2743 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2744 $user = $this->getUser()->getName();
2747 // Create a fake request based on the one we are about to make so modules return
2748 // correct timestamp and emptiness data
2749 $query = ResourceLoader
::makeLoaderQuery(
2750 array(), // modules; not determined yet
2751 $this->getLanguage()->getCode(),
2752 $this->getSkin()->getSkinName(),
2754 null, // version; not determined yet
2755 ResourceLoader
::inDebugMode(),
2756 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2757 $this->isPrintable(),
2758 $this->getRequest()->getBool( 'handheld' ),
2761 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2763 // Extract modules that know they're empty
2764 foreach ( $grpModules as $key => $module ) {
2765 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2766 // If we're only getting the styles, we don't need to do anything for empty modules.
2767 if ( $module->isKnownEmpty( $context ) ) {
2768 unset( $grpModules[$key] );
2769 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2770 $links['states'][$key] = 'ready';
2775 // If there are no non-empty modules, skip this group
2776 if ( count( $grpModules ) === 0 ) {
2780 // Inline private modules. These can't be loaded through load.php for security
2781 // reasons, see bug 34907. Note that these modules should be loaded from
2782 // getHeadScripts() before the first loader call. Otherwise other modules can't
2783 // properly use them as dependencies (bug 30914)
2784 if ( $group === 'private' ) {
2785 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2786 $links['html'] .= Html
::inlineStyle(
2787 $resourceLoader->makeModuleResponse( $context, $grpModules )
2790 $links['html'] .= Html
::inlineScript(
2791 ResourceLoader
::makeLoaderConditionalScript(
2792 $resourceLoader->makeModuleResponse( $context, $grpModules )
2796 $links['html'] .= "\n";
2800 // Special handling for the user group; because users might change their stuff
2801 // on-wiki like user pages, or user preferences; we need to find the highest
2802 // timestamp of these user-changeable modules so we can ensure cache misses on change
2803 // This should NOT be done for the site group (bug 27564) because anons get that too
2804 // and we shouldn't be putting timestamps in Squid-cached HTML
2806 if ( $group === 'user' ) {
2807 // Get the maximum timestamp
2809 foreach ( $grpModules as $module ) {
2810 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2812 // Add a version parameter so cache will break when things change
2813 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2816 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2817 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2818 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2820 if ( $useESI && $wgResourceLoaderUseESI ) {
2821 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2822 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2823 $link = Html
::inlineStyle( $esi );
2825 $link = Html
::inlineScript( $esi );
2828 // Automatically select style/script elements
2829 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2830 $link = Html
::linkedStyle( $url );
2831 } elseif ( $loadCall ) {
2832 $link = Html
::inlineScript(
2833 ResourceLoader
::makeLoaderConditionalScript(
2834 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2838 $link = Html
::linkedScript( $url );
2840 // For modules requested directly in the html via <link> or <script>,
2841 // tell mw.loader they are being loading to prevent duplicate requests.
2842 foreach ( $grpModules as $key => $module ) {
2843 // Don't output state=loading for the startup module..
2844 if ( $key !== 'startup' ) {
2845 $links['states'][$key] = 'loading';
2851 if ( $group == 'noscript' ) {
2852 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2854 $links['html'] .= $link . "\n";
2863 * Build html output from an array of links from makeResourceLoaderLink.
2864 * @param array $links
2865 * @return string HTML
2867 protected static function getHtmlFromLoaderLinks( Array $links ) {
2870 foreach ( $links as $link ) {
2871 if ( !is_array( $link ) ) {
2874 $html .= $link['html'];
2875 $states +
= $link['states'];
2879 if ( count( $states ) ) {
2880 $html = Html
::inlineScript(
2881 ResourceLoader
::makeLoaderConditionalScript(
2882 ResourceLoader
::makeLoaderStateScript( $states )
2891 * JS stuff to put in the "<head>". This is the startup module, config
2892 * vars and modules marked with position 'top'
2894 * @return string HTML fragment
2896 function getHeadScripts() {
2897 global $wgResourceLoaderExperimentalAsyncLoading;
2899 // Startup - this will immediately load jquery and mediawiki modules
2901 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ true );
2903 // Load config before anything else
2904 $links[] = Html
::inlineScript(
2905 ResourceLoader
::makeLoaderConditionalScript(
2906 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2910 // Load embeddable private modules before any loader links
2911 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2912 // in mw.loader.implement() calls and deferred until mw.user is available
2913 $embedScripts = array( 'user.options', 'user.tokens' );
2914 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2916 // Scripts and messages "only" requests marked for top inclusion
2917 // Messages should go first
2918 $links[] = $this->makeResourceLoaderLink(
2919 $this->getModuleMessages( true, 'top' ),
2920 ResourceLoaderModule
::TYPE_MESSAGES
2922 $links[] = $this->makeResourceLoaderLink(
2923 $this->getModuleScripts( true, 'top' ),
2924 ResourceLoaderModule
::TYPE_SCRIPTS
2927 // Modules requests - let the client calculate dependencies and batch requests as it likes
2928 // Only load modules that have marked themselves for loading at the top
2929 $modules = $this->getModules( true, 'top' );
2931 $links[] = Html
::inlineScript(
2932 ResourceLoader
::makeLoaderConditionalScript(
2933 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2938 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2939 $links[] = $this->getScriptsForBottomQueue( true );
2942 return self
::getHtmlFromLoaderLinks( $links );
2946 * JS stuff to put at the 'bottom', which can either be the bottom of the
2947 * "<body>" or the bottom of the "<head>" depending on
2948 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2949 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2952 * @param bool $inHead If true, this HTML goes into the "<head>",
2953 * if false it goes into the "<body>".
2956 function getScriptsForBottomQueue( $inHead ) {
2957 global $wgAllowUserJs;
2959 // Scripts and messages "only" requests marked for bottom inclusion
2960 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2961 // Messages should go first
2963 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2964 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2965 /* $loadCall = */ $inHead
2967 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2968 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2969 /* $loadCall = */ $inHead
2972 // Modules requests - let the client calculate dependencies and batch requests as it likes
2973 // Only load modules that have marked themselves for loading at the bottom
2974 $modules = $this->getModules( true, 'bottom' );
2976 $links[] = Html
::inlineScript(
2977 ResourceLoader
::makeLoaderConditionalScript(
2978 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2984 $links[] = "\n" . $this->mScripts
;
2986 // Add site JS if enabled
2987 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2988 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2991 // Add user JS if enabled
2993 && $this->getUser()->isLoggedIn()
2994 && $this->getTitle()
2995 && $this->getTitle()->isJsSubpage()
2996 && $this->userCanPreview()
2998 # XXX: additional security check/prompt?
2999 // We're on a preview of a JS subpage
3000 // Exclude this page from the user module in case it's in there (bug 26283)
3001 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3002 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3004 // Load the previewed JS
3005 $links[] = Html
::inlineScript( "\n"
3006 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3008 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3009 // asynchronously and may arrive *after* the inline script here. So the previewed code
3010 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3012 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3013 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3014 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3018 // Group JS is only enabled if site JS is enabled.
3019 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3020 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3024 wfRunHooks( 'OutputPageScriptsForBottomQueue', array( $this, &$modules ) );
3026 $links[] = $this->makeResourceLoaderLink( $modules, ResourceLoaderModule
::TYPE_COMBINED
,
3027 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3031 return self
::getHtmlFromLoaderLinks( $links );
3035 * JS stuff to put at the bottom of the "<body>"
3038 function getBottomScripts() {
3039 global $wgResourceLoaderExperimentalAsyncLoading;
3041 // Optimise jQuery ready event cross-browser.
3042 // This also enforces $.isReady to be true at </body> which fixes the
3043 // mw.loader bug in Firefox with using document.write between </body>
3044 // and the DOMContentReady event (bug 47457).
3045 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3047 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
3048 $html .= $this->getScriptsForBottomQueue( false );
3055 * Get the javascript config vars to include on this page
3057 * @return array Array of javascript config vars
3060 public function getJsConfigVars() {
3061 return $this->mJsConfigVars
;
3065 * Add one or more variables to be set in mw.config in JavaScript
3067 * @param string|array $keys Key or array of key/value pairs
3068 * @param mixed $value [optional] Value of the configuration variable
3070 public function addJsConfigVars( $keys, $value = null ) {
3071 if ( is_array( $keys ) ) {
3072 foreach ( $keys as $key => $value ) {
3073 $this->mJsConfigVars
[$key] = $value;
3078 $this->mJsConfigVars
[$keys] = $value;
3082 * Get an array containing the variables to be set in mw.config in JavaScript.
3084 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3085 * - in other words, page-independent/site-wide variables (without state).
3086 * You will only be adding bloat to the html page and causing page caches to
3087 * have to be purged on configuration changes.
3090 private function getJSVars() {
3095 $canonicalSpecialPageName = false; # bug 21115
3097 $title = $this->getTitle();
3098 $ns = $title->getNamespace();
3099 $canonicalNamespace = MWNamespace
::exists( $ns )
3100 ? MWNamespace
::getCanonicalName( $ns )
3101 : $title->getNsText();
3103 $sk = $this->getSkin();
3104 // Get the relevant title so that AJAX features can use the correct page name
3105 // when making API requests from certain special pages (bug 34972).
3106 $relevantTitle = $sk->getRelevantTitle();
3107 $relevantUser = $sk->getRelevantUser();
3109 if ( $ns == NS_SPECIAL
) {
3110 list( $canonicalSpecialPageName, /*...*/ ) =
3111 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3112 } elseif ( $this->canUseWikiPage() ) {
3113 $wikiPage = $this->getWikiPage();
3114 $curRevisionId = $wikiPage->getLatest();
3115 $articleId = $wikiPage->getId();
3118 $lang = $title->getPageLanguage();
3120 // Pre-process information
3121 $separatorTransTable = $lang->separatorTransformTable();
3122 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3123 $compactSeparatorTransTable = array(
3124 implode( "\t", array_keys( $separatorTransTable ) ),
3125 implode( "\t", $separatorTransTable ),
3127 $digitTransTable = $lang->digitTransformTable();
3128 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3129 $compactDigitTransTable = array(
3130 implode( "\t", array_keys( $digitTransTable ) ),
3131 implode( "\t", $digitTransTable ),
3134 $user = $this->getUser();
3137 'wgCanonicalNamespace' => $canonicalNamespace,
3138 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3139 'wgNamespaceNumber' => $title->getNamespace(),
3140 'wgPageName' => $title->getPrefixedDBkey(),
3141 'wgTitle' => $title->getText(),
3142 'wgCurRevisionId' => $curRevisionId,
3143 'wgRevisionId' => (int)$this->getRevisionId(),
3144 'wgArticleId' => $articleId,
3145 'wgIsArticle' => $this->isArticle(),
3146 'wgIsRedirect' => $title->isRedirect(),
3147 'wgAction' => Action
::getActionName( $this->getContext() ),
3148 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3149 'wgUserGroups' => $user->getEffectiveGroups(),
3150 'wgCategories' => $this->getCategories(),
3151 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3152 'wgPageContentLanguage' => $lang->getCode(),
3153 'wgPageContentModel' => $title->getContentModel(),
3154 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3155 'wgDigitTransformTable' => $compactDigitTransTable,
3156 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3157 'wgMonthNames' => $lang->getMonthNamesArray(),
3158 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3159 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3162 if ( $user->isLoggedIn() ) {
3163 $vars['wgUserId'] = $user->getId();
3164 $vars['wgUserEditCount'] = $user->getEditCount();
3165 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3166 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3167 // Get the revision ID of the oldest new message on the user's talk
3168 // page. This can be used for constructing new message alerts on
3170 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3173 if ( $wgContLang->hasVariants() ) {
3174 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3176 // Same test as SkinTemplate
3177 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3178 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3180 foreach ( $title->getRestrictionTypes() as $type ) {
3181 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3184 if ( $title->isMainPage() ) {
3185 $vars['wgIsMainPage'] = true;
3188 if ( $this->mRedirectedFrom
) {
3189 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3192 if ( $relevantUser ) {
3193 $vars['wgRelevantUserName'] = $relevantUser->getName();
3196 // Allow extensions to add their custom variables to the mw.config map.
3197 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3198 // page-dependant but site-wide (without state).
3199 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3200 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3202 // Merge in variables from addJsConfigVars last
3203 return array_merge( $vars, $this->getJsConfigVars() );
3207 * To make it harder for someone to slip a user a fake
3208 * user-JavaScript or user-CSS preview, a random token
3209 * is associated with the login session. If it's not
3210 * passed back with the preview request, we won't render
3215 public function userCanPreview() {
3216 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3217 ||
!$this->getRequest()->wasPosted()
3218 ||
!$this->getUser()->matchEditToken(
3219 $this->getRequest()->getVal( 'wpEditToken' ) )
3223 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3227 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3231 * @return array Array in format "link name or number => 'link html'".
3233 public function getHeadLinksArray() {
3234 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3235 $wgSitename, $wgVersion,
3236 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3237 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3238 $wgRightsPage, $wgRightsUrl;
3242 $canonicalUrl = $this->mCanonicalUrl
;
3244 $tags['meta-generator'] = Html
::element( 'meta', array(
3245 'name' => 'generator',
3246 'content' => "MediaWiki $wgVersion",
3249 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3250 if ( $p !== 'index,follow' ) {
3251 // http://www.robotstxt.org/wc/meta-user.html
3252 // Only show if it's different from the default robots policy
3253 $tags['meta-robots'] = Html
::element( 'meta', array(
3259 foreach ( $this->mMetatags
as $tag ) {
3260 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3262 $tag[0] = substr( $tag[0], 5 );
3266 $tagName = "meta-{$tag[0]}";
3267 if ( isset( $tags[$tagName] ) ) {
3268 $tagName .= $tag[1];
3270 $tags[$tagName] = Html
::element( 'meta',
3273 'content' => $tag[1]
3278 foreach ( $this->mLinktags
as $tag ) {
3279 $tags[] = Html
::element( 'link', $tag );
3282 # Universal edit button
3283 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3284 $user = $this->getUser();
3285 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3286 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3287 // Original UniversalEditButton
3288 $msg = $this->msg( 'edit' )->text();
3289 $tags['universal-edit-button'] = Html
::element( 'link', array(
3290 'rel' => 'alternate',
3291 'type' => 'application/x-wiki',
3293 'href' => $this->getTitle()->getEditURL(),
3295 // Alternate edit link
3296 $tags['alternative-edit'] = Html
::element( 'link', array(
3299 'href' => $this->getTitle()->getEditURL(),
3304 # Generally the order of the favicon and apple-touch-icon links
3305 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3306 # uses whichever one appears later in the HTML source. Make sure
3307 # apple-touch-icon is specified first to avoid this.
3308 if ( $wgAppleTouchIcon !== false ) {
3309 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3310 'rel' => 'apple-touch-icon',
3311 'href' => $wgAppleTouchIcon
3315 if ( $wgFavicon !== false ) {
3316 $tags['favicon'] = Html
::element( 'link', array(
3317 'rel' => 'shortcut icon',
3318 'href' => $wgFavicon
3322 # OpenSearch description link
3323 $tags['opensearch'] = Html
::element( 'link', array(
3325 'type' => 'application/opensearchdescription+xml',
3326 'href' => wfScript( 'opensearch_desc' ),
3327 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3330 if ( $wgEnableAPI ) {
3331 # Real Simple Discovery link, provides auto-discovery information
3332 # for the MediaWiki API (and potentially additional custom API
3333 # support such as WordPress or Twitter-compatible APIs for a
3334 # blogging extension, etc)
3335 $tags['rsd'] = Html
::element( 'link', array(
3337 'type' => 'application/rsd+xml',
3338 // Output a protocol-relative URL here if $wgServer is protocol-relative
3339 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3340 'href' => wfExpandUrl( wfAppendQuery(
3342 array( 'action' => 'rsd' ) ),
3349 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3350 $lang = $this->getTitle()->getPageLanguage();
3351 if ( $lang->hasVariants() ) {
3353 $urlvar = $lang->getURLVariant();
3356 $variants = $lang->getVariants();
3357 foreach ( $variants as $_v ) {
3358 $tags["variant-$_v"] = Html
::element( 'link', array(
3359 'rel' => 'alternate',
3360 'hreflang' => wfBCP47( $_v ),
3361 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3365 $canonicalUrl = $this->getTitle()->getLocalURL();
3372 if ( $wgRightsPage ) {
3373 $copy = Title
::newFromText( $wgRightsPage );
3376 $copyright = $copy->getLocalURL();
3380 if ( !$copyright && $wgRightsUrl ) {
3381 $copyright = $wgRightsUrl;
3385 $tags['copyright'] = Html
::element( 'link', array(
3386 'rel' => 'copyright',
3387 'href' => $copyright )
3393 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3394 # Use the page name for the title. In principle, this could
3395 # lead to issues with having the same name for different feeds
3396 # corresponding to the same page, but we can't avoid that at
3399 $tags[] = $this->feedLink(
3402 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3403 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3407 # Recent changes feed should appear on every page (except recentchanges,
3408 # that would be redundant). Put it after the per-page feed to avoid
3409 # changing existing behavior. It's still available, probably via a
3410 # menu in your browser. Some sites might have a different feed they'd
3411 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3412 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3413 # If so, use it instead.
3414 if ( $wgOverrideSiteFeed ) {
3415 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3416 // Note, this->feedLink escapes the url.
3417 $tags[] = $this->feedLink(
3420 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3423 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3424 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3425 foreach ( $wgAdvertisedFeedTypes as $format ) {
3426 $tags[] = $this->feedLink(
3428 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3429 # For grep: 'site-rss-feed', 'site-atom-feed'
3430 $this->msg( "site-{$format}-feed", $wgSitename )->text()
3437 global $wgEnableCanonicalServerLink;
3438 if ( $wgEnableCanonicalServerLink ) {
3439 if ( $canonicalUrl !== false ) {
3440 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3442 $reqUrl = $this->getRequest()->getRequestURL();
3443 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3446 if ( $canonicalUrl !== false ) {
3447 $tags[] = Html
::element( 'link', array(
3448 'rel' => 'canonical',
3449 'href' => $canonicalUrl
3457 * @return string HTML tag links to be put in the header.
3458 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3459 * OutputPage::getHeadLinksArray directly.
3461 public function getHeadLinks() {
3462 wfDeprecated( __METHOD__
, '1.24' );
3463 return implode( "\n", $this->getHeadLinksArray() );
3467 * Generate a "<link rel/>" for a feed.
3469 * @param string $type Feed type
3470 * @param string $url URL to the feed
3471 * @param string $text Value of the "title" attribute
3472 * @return string HTML fragment
3474 private function feedLink( $type, $url, $text ) {
3475 return Html
::element( 'link', array(
3476 'rel' => 'alternate',
3477 'type' => "application/$type+xml",
3484 * Add a local or specified stylesheet, with the given media options.
3485 * Meant primarily for internal use...
3487 * @param string $style URL to the file
3488 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3489 * @param string $condition For IE conditional comments, specifying an IE version
3490 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3492 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3494 // Even though we expect the media type to be lowercase, but here we
3495 // force it to lowercase to be safe.
3497 $options['media'] = $media;
3500 $options['condition'] = $condition;
3503 $options['dir'] = $dir;
3505 $this->styles
[$style] = $options;
3509 * Adds inline CSS styles
3510 * @param mixed $style_css Inline CSS
3511 * @param string $flip Set to 'flip' to flip the CSS if needed
3513 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3514 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3515 # If wanted, and the interface is right-to-left, flip the CSS
3516 $style_css = CSSJanus
::transform( $style_css, true, false );
3518 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3522 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3523 * These will be applied to various media & IE conditionals.
3527 public function buildCssLinks() {
3528 global $wgAllowUserCss, $wgContLang;
3530 $this->getSkin()->setupSkinUserCss( $this );
3532 // Add ResourceLoader styles
3533 // Split the styles into these groups
3538 'private' => array(),
3539 'noscript' => array()
3542 $otherTags = ''; // Tags to append after the normal <link> tags
3543 $resourceLoader = $this->getResourceLoader();
3545 $moduleStyles = $this->getModuleStyles();
3547 // Per-site custom styles
3548 $moduleStyles[] = 'site';
3549 $moduleStyles[] = 'noscript';
3550 $moduleStyles[] = 'user.groups';
3552 // Per-user custom styles
3553 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3554 // We're on a preview of a CSS subpage
3555 // Exclude this page from the user module in case it's in there (bug 26283)
3556 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3557 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3559 $otherTags .= $link['html'];
3561 // Load the previewed CSS
3562 // If needed, Janus it first. This is user-supplied CSS, so it's
3563 // assumed to be right for the content language directionality.
3564 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3565 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3566 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3568 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3570 // Load the user styles normally
3571 $moduleStyles[] = 'user';
3574 // Per-user preference styles
3575 $moduleStyles[] = 'user.cssprefs';
3577 foreach ( $moduleStyles as $name ) {
3578 $module = $resourceLoader->getModule( $name );
3582 $group = $module->getGroup();
3583 // Modules in groups different than the ones listed on top (see $styles assignment)
3584 // will be placed in the "other" group
3585 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3588 // We want site, private and user styles to override dynamically added
3589 // styles from modules, but we want dynamically added styles to override
3590 // statically added styles from other modules. So the order has to be
3591 // other, dynamic, site, private, user. Add statically added styles for
3593 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3594 // Add normal styles added through addStyle()/addInlineStyle() here
3595 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3596 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3597 // We use a <meta> tag with a made-up name for this because that's valid HTML
3598 $links[] = Html
::element(
3600 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3603 // Add site, private and user styles
3604 // 'private' at present only contains user.options, so put that before 'user'
3605 // Any future private modules will likely have a similar user-specific character
3606 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3607 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3608 ResourceLoaderModule
::TYPE_STYLES
3612 // Add stuff in $otherTags (previewed user CSS if applicable)
3613 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3619 public function buildCssLinksArray() {
3622 // Add any extension CSS
3623 foreach ( $this->mExtStyles
as $url ) {
3624 $this->addStyle( $url );
3626 $this->mExtStyles
= array();
3628 foreach ( $this->styles
as $file => $options ) {
3629 $link = $this->styleLink( $file, $options );
3631 $links[$file] = $link;
3638 * Generate \<link\> tags for stylesheets
3640 * @param string $style URL to the file
3641 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3642 * @return string HTML fragment
3644 protected function styleLink( $style, $options ) {
3645 if ( isset( $options['dir'] ) ) {
3646 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3651 if ( isset( $options['media'] ) ) {
3652 $media = self
::transformCssMedia( $options['media'] );
3653 if ( is_null( $media ) ) {
3660 if ( substr( $style, 0, 1 ) == '/' ||
3661 substr( $style, 0, 5 ) == 'http:' ||
3662 substr( $style, 0, 6 ) == 'https:' ) {
3665 global $wgStylePath, $wgStyleVersion;
3666 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3669 $link = Html
::linkedStyle( $url, $media );
3671 if ( isset( $options['condition'] ) ) {
3672 $condition = htmlspecialchars( $options['condition'] );
3673 $link = "<!--[if $condition]>$link<![endif]-->";
3679 * Transform "media" attribute based on request parameters
3681 * @param string $media Current value of the "media" attribute
3682 * @return string Modified value of the "media" attribute, or null to skip
3685 public static function transformCssMedia( $media ) {
3688 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3689 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3691 // Switch in on-screen display for media testing
3693 'printable' => 'print',
3694 'handheld' => 'handheld',
3696 foreach ( $switches as $switch => $targetMedia ) {
3697 if ( $wgRequest->getBool( $switch ) ) {
3698 if ( $media == $targetMedia ) {
3700 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3701 // This regex will not attempt to understand a comma-separated media_query_list
3703 // Example supported values for $media:
3704 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3705 // Example NOT supported value for $media:
3706 // '3d-glasses, screen, print and resolution > 90dpi'
3708 // If it's a print request, we never want any kind of screen stylesheets
3709 // If it's a handheld request (currently the only other choice with a switch),
3710 // we don't want simple 'screen' but we might want screen queries that
3711 // have a max-width or something, so we'll pass all others on and let the
3712 // client do the query.
3713 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3724 * Add a wikitext-formatted message to the output.
3725 * This is equivalent to:
3727 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3729 public function addWikiMsg( /*...*/ ) {
3730 $args = func_get_args();
3731 $name = array_shift( $args );
3732 $this->addWikiMsgArray( $name, $args );
3736 * Add a wikitext-formatted message to the output.
3737 * Like addWikiMsg() except the parameters are taken as an array
3738 * instead of a variable argument list.
3740 * @param string $name
3741 * @param array $args
3743 public function addWikiMsgArray( $name, $args ) {
3744 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3748 * This function takes a number of message/argument specifications, wraps them in
3749 * some overall structure, and then parses the result and adds it to the output.
3751 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3752 * on. The subsequent arguments may either be strings, in which case they are the
3753 * message names, or arrays, in which case the first element is the message name,
3754 * and subsequent elements are the parameters to that message.
3756 * Don't use this for messages that are not in users interface language.
3760 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3764 * $wgOut->addWikiText( "<div class='error'>\n"
3765 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3767 * The newline after opening div is needed in some wikitext. See bug 19226.
3769 * @param string $wrap
3771 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3772 $msgSpecs = func_get_args();
3773 array_shift( $msgSpecs );
3774 $msgSpecs = array_values( $msgSpecs );
3776 foreach ( $msgSpecs as $n => $spec ) {
3777 if ( is_array( $spec ) ) {
3779 $name = array_shift( $args );
3780 if ( isset( $args['options'] ) ) {
3781 unset( $args['options'] );
3783 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3791 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3793 $this->addWikiText( $s );
3797 * Include jQuery core. Use this to avoid loading it multiple times
3798 * before we get a usable script loader.
3800 * @param array $modules List of jQuery modules which should be loaded
3801 * @return array The list of modules which were not loaded.
3803 * @deprecated since 1.17
3805 public function includeJQuery( $modules = array() ) {
3810 * Enables/disables TOC, doesn't override __NOTOC__
3814 public function enableTOC( $flag = true ) {
3815 $this->mEnableTOC
= $flag;
3822 public function isTOCEnabled() {
3823 return $this->mEnableTOC
;
3827 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3831 public function enableSectionEditLinks( $flag = true ) {
3832 $this->mEnableSectionEditLinks
= $flag;
3839 public function sectionEditLinksEnabled() {
3840 return $this->mEnableSectionEditLinks
;