3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @var string Variable mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
126 protected $mIndicators = array();
128 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
129 private $mLanguageLinks = array();
132 * Used for JavaScript (pre resource loader)
133 * @todo We should split JS / CSS.
134 * mScripts content is inserted as is in "<head>" by Skin. This might
135 * contain either a link to a stylesheet or inline CSS.
137 private $mScripts = '';
139 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
140 protected $mInlineStyles = '';
143 private $mLinkColours;
146 * @var string Used by skin template.
147 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
149 public $mPageLinkTitle = '';
151 /** @var array Array of elements in "<head>". Parser might add its own headers! */
152 protected $mHeadItems = array();
154 // @todo FIXME: Next 5 variables probably come from the resource loader
157 protected $mModules = array();
160 protected $mModuleScripts = array();
163 protected $mModuleStyles = array();
166 protected $mModuleMessages = array();
168 /** @var ResourceLoader */
169 protected $mResourceLoader;
172 protected $mJsConfigVars = array();
175 protected $mTemplateIds = array();
178 protected $mImageTimeKeys = array();
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
186 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
187 * @see ResourceLoaderModule::$origin
188 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
190 protected $mAllowedModules = array(
191 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
194 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
195 protected $mDoNothing = false;
200 protected $mContainsNewMagic = 0;
203 * lazy initialised, use parserOptions()
206 protected $mParserOptions = null;
209 * Handles the Atom / RSS links.
210 * We probably only support Atom in 2011.
211 * @see $wgAdvertisedFeedTypes
213 private $mFeedLinks = array();
215 // Gwicke work on squid caching? Roughly from 2003.
216 protected $mEnableClientCache = true;
218 /** @var bool Flag if output should only contain the body of the article. */
219 private $mArticleBodyOnly = false;
222 protected $mNewSectionLink = false;
225 protected $mHideNewSectionLink = false;
228 * @var bool Comes from the parser. This was probably made to load CSS/JS
229 * only if we had "<gallery>". Used directly in CategoryPage.php.
230 * Looks like resource loader can replace this.
232 public $mNoGallery = false;
235 private $mPageTitleActionText = '';
238 private $mParseWarnings = array();
240 /** @var int Cache stuff. Looks like mEnableClientCache */
241 protected $mSquidMaxage = 0;
244 * @var bool Controls if anti-clickjacking / frame-breaking headers will
245 * be sent. This should be done for pages where edit actions are possible.
246 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
248 protected $mPreventClickjacking = true;
250 /** @var int To include the variable {{REVISIONID}} */
251 private $mRevisionId = null;
254 private $mRevisionTimestamp = null;
257 protected $mFileVersion = null;
260 * @var array An array of stylesheet filenames (relative from skins path),
261 * with options for CSS media, IE conditions, and RTL/LTR direction.
262 * For internal use; add settings in the skin via $this->addStyle()
264 * Style again! This seems like a code duplication since we already have
265 * mStyles. This is what makes Open Source amazing.
267 protected $styles = array();
270 * Whether jQuery is already handled.
272 protected $mJQueryDone = false;
274 private $mIndexPolicy = 'index';
275 private $mFollowPolicy = 'follow';
276 private $mVaryHeader = array(
277 'Accept-Encoding' => array( 'list-contains=gzip' ),
281 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
286 private $mRedirectedFrom = null;
289 * Additional key => value data
291 private $mProperties = array();
294 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
296 private $mTarget = null;
299 * @var bool Whether parser output should contain table of contents
301 private $mEnableTOC = true;
304 * @var bool Whether parser output should contain section edit links
306 private $mEnableSectionEditLinks = true;
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource|null $context
314 function __construct( IContextSource
$context = null ) {
315 if ( $context === null ) {
316 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
317 wfDeprecated( __METHOD__
, '1.18' );
319 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect
= str_replace( "\n", '', $url );
332 $this->mRedirectCode
= $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
340 public function getRedirect() {
341 return $this->mRedirect
;
345 * Set the HTTP status code to send with the output.
347 * @param int $statusCode
349 public function setStatusCode( $statusCode ) {
350 $this->mStatusCode
= $statusCode;
354 * Add a new "<meta>" tag
355 * To add an http-equiv meta tag, precede the name with "http:"
357 * @param string $name Tag name
358 * @param string $val Tag value
360 function addMeta( $name, $val ) {
361 array_push( $this->mMetatags
, array( $name, $val ) );
365 * Returns the current <meta> tags
370 public function getMetaTags() {
371 return $this->mMetatags
;
375 * Add a new \<link\> tag to the page header.
377 * Note: use setCanonicalUrl() for rel=canonical.
379 * @param array $linkarr Associative array of attributes.
381 function addLink( array $linkarr ) {
382 array_push( $this->mLinktags
, $linkarr );
386 * Returns the current <link> tags
391 public function getLinkTags() {
392 return $this->mLinktags
;
396 * Add a new \<link\> with "rel" attribute set to "meta"
398 * @param array $linkarr Associative array mapping attribute names to their
399 * values, both keys and values will be escaped, and the
400 * "rel" attribute will be automatically added
402 function addMetadataLink( array $linkarr ) {
403 $linkarr['rel'] = $this->getMetadataAttribute();
404 $this->addLink( $linkarr );
408 * Set the URL to be used for the <link rel=canonical>. This should be used
409 * in preference to addLink(), to avoid duplicate link tags.
412 function setCanonicalUrl( $url ) {
413 $this->mCanonicalUrl
= $url;
417 * Returns the URL to be used for the <link rel=canonical> if
421 * @return bool|string
423 public function getCanonicalUrl() {
424 return $this->mCanonicalUrl
;
428 * Get the value of the "rel" attribute for metadata links
432 public function getMetadataAttribute() {
433 # note: buggy CC software only reads first "meta" link
434 static $haveMeta = false;
436 return 'alternate meta';
444 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
446 * @param string $script Raw HTML
448 function addScript( $script ) {
449 $this->mScripts
.= $script . "\n";
453 * Register and add a stylesheet from an extension directory.
455 * @param string $url Path to sheet. Provide either a full url (beginning
456 * with 'http', etc) or a relative path from the document root
457 * (beginning with '/'). Otherwise it behaves identically to
458 * addStyle() and draws from the /skins folder.
460 public function addExtensionStyle( $url ) {
461 array_push( $this->mExtStyles
, $url );
465 * Get all styles added by extensions
469 function getExtStyle() {
470 return $this->mExtStyles
;
474 * Add a JavaScript file out of skins/common, or a given relative path.
476 * @param string $file Filename in skins/common or complete on-server path
478 * @param string $version Style version of the file. Defaults to $wgStyleVersion
480 public function addScriptFile( $file, $version = null ) {
481 // See if $file parameter is an absolute URL or begins with a slash
482 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
485 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
487 if ( is_null( $version ) ) {
488 $version = $this->getConfig()->get( 'StyleVersion' );
490 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
494 * Add a self-contained script tag with the given contents
496 * @param string $script JavaScript text, no "<script>" tags
498 public function addInlineScript( $script ) {
499 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
503 * Get all registered JS and CSS tags for the header.
506 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
508 function getScript() {
509 wfDeprecated( __METHOD__
, '1.24' );
510 return $this->mScripts
. $this->getHeadItems();
514 * Filter an array of modules to remove insufficiently trustworthy members, and modules
515 * which are no longer registered (eg a page is cached before an extension is disabled)
516 * @param array $modules
517 * @param string|null $position If not null, only return modules with this position
518 * @param string $type
521 protected function filterModules( array $modules, $position = null,
522 $type = ResourceLoaderModule
::TYPE_COMBINED
524 $resourceLoader = $this->getResourceLoader();
525 $filteredModules = array();
526 foreach ( $modules as $val ) {
527 $module = $resourceLoader->getModule( $val );
528 if ( $module instanceof ResourceLoaderModule
529 && $module->getOrigin() <= $this->getAllowedModules( $type )
530 && ( is_null( $position ) ||
$module->getPosition() == $position )
531 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
533 $filteredModules[] = $val;
536 return $filteredModules;
540 * Get the list of modules to include on this page
542 * @param bool $filter Whether to filter out insufficiently trustworthy modules
543 * @param string|null $position If not null, only return modules with this position
544 * @param string $param
545 * @return array Array of module names
547 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
548 $modules = array_values( array_unique( $this->$param ) );
550 ?
$this->filterModules( $modules, $position )
555 * Add one or more modules recognized by the resource loader. Modules added
556 * through this function will be loaded by the resource loader when the
559 * @param string|array $modules Module name (string) or array of module names
561 public function addModules( $modules ) {
562 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
566 * Get the list of module JS to include on this page
568 * @param bool $filter
569 * @param string|null $position
571 * @return array Array of module names
573 public function getModuleScripts( $filter = false, $position = null ) {
574 return $this->getModules( $filter, $position, 'mModuleScripts' );
578 * Add only JS of one or more modules recognized by the resource loader. Module
579 * scripts added through this function will be loaded by the resource loader when
582 * @param string|array $modules Module name (string) or array of module names
584 public function addModuleScripts( $modules ) {
585 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
589 * Get the list of module CSS to include on this page
591 * @param bool $filter
592 * @param string|null $position
594 * @return array Array of module names
596 public function getModuleStyles( $filter = false, $position = null ) {
597 return $this->getModules( $filter, $position, 'mModuleStyles' );
601 * Add only CSS of one or more modules recognized by the resource loader.
603 * Module styles added through this function will be added using standard link CSS
604 * tags, rather than as a combined Javascript and CSS package. Thus, they will
605 * load when JavaScript is disabled (unless CSS also happens to be disabled).
607 * @param string|array $modules Module name (string) or array of module names
609 public function addModuleStyles( $modules ) {
610 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
614 * Get the list of module messages to include on this page
616 * @param bool $filter
617 * @param string|null $position
619 * @return array Array of module names
621 public function getModuleMessages( $filter = false, $position = null ) {
622 return $this->getModules( $filter, $position, 'mModuleMessages' );
626 * Add only messages of one or more modules recognized by the resource loader.
627 * Module messages added through this function will be loaded by the resource
628 * loader when the page loads.
630 * @param string|array $modules Module name (string) or array of module names
632 public function addModuleMessages( $modules ) {
633 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
637 * @return null|string ResourceLoader target
639 public function getTarget() {
640 return $this->mTarget
;
644 * Sets ResourceLoader target for load.php links. If null, will be omitted
646 * @param string|null $target
648 public function setTarget( $target ) {
649 $this->mTarget
= $target;
653 * Get an array of head items
657 function getHeadItemsArray() {
658 return $this->mHeadItems
;
662 * Get all header items in a string
665 * @deprecated since 1.24 Use OutputPage::headElement or
666 * if absolutely necessary use OutputPage::getHeadItemsArray
668 function getHeadItems() {
669 wfDeprecated( __METHOD__
, '1.24' );
671 foreach ( $this->mHeadItems
as $item ) {
678 * Add or replace an header item to the output
680 * @param string $name Item name
681 * @param string $value Raw HTML
683 public function addHeadItem( $name, $value ) {
684 $this->mHeadItems
[$name] = $value;
688 * Check if the header item $name is already set
690 * @param string $name Item name
693 public function hasHeadItem( $name ) {
694 return isset( $this->mHeadItems
[$name] );
698 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
700 * @param string $tag Value of "ETag" header
702 function setETag( $tag ) {
707 * Set whether the output should only contain the body of the article,
708 * without any skin, sidebar, etc.
709 * Used e.g. when calling with "action=render".
711 * @param bool $only Whether to output only the body of the article
713 public function setArticleBodyOnly( $only ) {
714 $this->mArticleBodyOnly
= $only;
718 * Return whether the output will contain only the body of the article
722 public function getArticleBodyOnly() {
723 return $this->mArticleBodyOnly
;
727 * Set an additional output property
730 * @param string $name
731 * @param mixed $value
733 public function setProperty( $name, $value ) {
734 $this->mProperties
[$name] = $value;
738 * Get an additional output property
741 * @param string $name
742 * @return mixed Property value or null if not found
744 public function getProperty( $name ) {
745 if ( isset( $this->mProperties
[$name] ) ) {
746 return $this->mProperties
[$name];
753 * checkLastModified tells the client to use the client-cached page if
754 * possible. If successful, the OutputPage is disabled so that
755 * any future call to OutputPage->output() have no effect.
757 * Side effect: sets mLastModified for Last-Modified header
759 * @param string $timestamp
761 * @return bool True if cache-ok headers was sent.
763 public function checkLastModified( $timestamp ) {
764 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
765 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
768 $config = $this->getConfig();
769 if ( !$config->get( 'CachePages' ) ) {
770 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
774 $timestamp = wfTimestamp( TS_MW
, $timestamp );
775 $modifiedTimes = array(
776 'page' => $timestamp,
777 'user' => $this->getUser()->getTouched(),
778 'epoch' => $config->get( 'CacheEpoch' )
780 if ( $config->get( 'UseSquid' ) ) {
781 // bug 44570: the core page itself may not change, but resources might
782 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
784 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
786 $maxModified = max( $modifiedTimes );
787 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
789 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
790 if ( $clientHeader === false ) {
791 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
795 # IE sends sizes after the date like this:
796 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
797 # this breaks strtotime().
798 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
800 wfSuppressWarnings(); // E_STRICT system time bitching
801 $clientHeaderTime = strtotime( $clientHeader );
803 if ( !$clientHeaderTime ) {
805 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
808 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
812 foreach ( $modifiedTimes as $name => $value ) {
813 if ( $info !== '' ) {
816 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
819 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
820 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
821 wfDebug( __METHOD__
. ": effective Last-Modified: " .
822 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
823 if ( $clientHeaderTime < $maxModified ) {
824 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
829 # Give a 304 response code and disable body output
830 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
831 ini_set( 'zlib.output_compression', 0 );
832 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
833 $this->sendCacheControl();
836 // Don't output a compressed blob when using ob_gzhandler;
837 // it's technically against HTTP spec and seems to confuse
838 // Firefox when the response gets split over two packets.
839 wfClearOutputBuffers();
845 * Override the last modified timestamp
847 * @param string $timestamp New timestamp, in a format readable by
850 public function setLastModified( $timestamp ) {
851 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
855 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
857 * @param string $policy The literal string to output as the contents of
858 * the meta tag. Will be parsed according to the spec and output in
862 public function setRobotPolicy( $policy ) {
863 $policy = Article
::formatRobotPolicy( $policy );
865 if ( isset( $policy['index'] ) ) {
866 $this->setIndexPolicy( $policy['index'] );
868 if ( isset( $policy['follow'] ) ) {
869 $this->setFollowPolicy( $policy['follow'] );
874 * Set the index policy for the page, but leave the follow policy un-
877 * @param string $policy Either 'index' or 'noindex'.
880 public function setIndexPolicy( $policy ) {
881 $policy = trim( $policy );
882 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
883 $this->mIndexPolicy
= $policy;
888 * Set the follow policy for the page, but leave the index policy un-
891 * @param string $policy Either 'follow' or 'nofollow'.
894 public function setFollowPolicy( $policy ) {
895 $policy = trim( $policy );
896 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
897 $this->mFollowPolicy
= $policy;
902 * Set the new value of the "action text", this will be added to the
903 * "HTML title", separated from it with " - ".
905 * @param string $text New value of the "action text"
907 public function setPageTitleActionText( $text ) {
908 $this->mPageTitleActionText
= $text;
912 * Get the value of the "action text"
916 public function getPageTitleActionText() {
917 return $this->mPageTitleActionText
;
921 * "HTML title" means the contents of "<title>".
922 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
924 * @param string|Message $name
926 public function setHTMLTitle( $name ) {
927 if ( $name instanceof Message
) {
928 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
930 $this->mHTMLtitle
= $name;
935 * Return the "HTML title", i.e. the content of the "<title>" tag.
939 public function getHTMLTitle() {
940 return $this->mHTMLtitle
;
944 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
948 public function setRedirectedFrom( $t ) {
949 $this->mRedirectedFrom
= $t;
953 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
954 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
955 * but not bad tags like \<script\>. This function automatically sets
956 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
957 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
958 * good tags like \<i\> will be dropped entirely.
960 * @param string|Message $name
962 public function setPageTitle( $name ) {
963 if ( $name instanceof Message
) {
964 $name = $name->setContext( $this->getContext() )->text();
967 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
968 # but leave "<i>foobar</i>" alone
969 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
970 $this->mPagetitle
= $nameWithTags;
972 # change "<i>foo&bar</i>" to "foo&bar"
974 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
975 ->inContentLanguage()
980 * Return the "page title", i.e. the content of the \<h1\> tag.
984 public function getPageTitle() {
985 return $this->mPagetitle
;
989 * Set the Title object to use
993 public function setTitle( Title
$t ) {
994 $this->getContext()->setTitle( $t );
998 * Replace the subtitle with $str
1000 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1002 public function setSubtitle( $str ) {
1003 $this->clearSubtitle();
1004 $this->addSubtitle( $str );
1008 * Add $str to the subtitle
1010 * @deprecated since 1.19; use addSubtitle() instead
1011 * @param string|Message $str String or Message to add to the subtitle
1013 public function appendSubtitle( $str ) {
1014 $this->addSubtitle( $str );
1018 * Add $str to the subtitle
1020 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1022 public function addSubtitle( $str ) {
1023 if ( $str instanceof Message
) {
1024 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1026 $this->mSubtitle
[] = $str;
1031 * Build message object for a subtitle containing a backlink to a page
1033 * @param Title $title Title to link to
1034 * @param array $query Array of additional parameters to include in the link
1038 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1039 if ( $title->isRedirect() ) {
1040 $query['redirect'] = 'no';
1042 return wfMessage( 'backlinksubtitle' )
1043 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1047 * Add a subtitle containing a backlink to a page
1049 * @param Title $title Title to link to
1050 * @param array $query Array of additional parameters to include in the link
1052 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1053 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1057 * Clear the subtitles
1059 public function clearSubtitle() {
1060 $this->mSubtitle
= array();
1068 public function getSubtitle() {
1069 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1073 * Set the page as printable, i.e. it'll be displayed with all
1074 * print styles included
1076 public function setPrintable() {
1077 $this->mPrintable
= true;
1081 * Return whether the page is "printable"
1085 public function isPrintable() {
1086 return $this->mPrintable
;
1090 * Disable output completely, i.e. calling output() will have no effect
1092 public function disable() {
1093 $this->mDoNothing
= true;
1097 * Return whether the output will be completely disabled
1101 public function isDisabled() {
1102 return $this->mDoNothing
;
1106 * Show an "add new section" link?
1110 public function showNewSectionLink() {
1111 return $this->mNewSectionLink
;
1115 * Forcibly hide the new section link?
1119 public function forceHideNewSectionLink() {
1120 return $this->mHideNewSectionLink
;
1124 * Add or remove feed links in the page header
1125 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1126 * for the new version
1127 * @see addFeedLink()
1129 * @param bool $show True: add default feeds, false: remove all feeds
1131 public function setSyndicated( $show = true ) {
1133 $this->setFeedAppendQuery( false );
1135 $this->mFeedLinks
= array();
1140 * Add default feeds to the page header
1141 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1142 * for the new version
1143 * @see addFeedLink()
1145 * @param string $val Query to append to feed links or false to output
1148 public function setFeedAppendQuery( $val ) {
1149 $this->mFeedLinks
= array();
1151 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1152 $query = "feed=$type";
1153 if ( is_string( $val ) ) {
1154 $query .= '&' . $val;
1156 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1161 * Add a feed link to the page header
1163 * @param string $format Feed type, should be a key of $wgFeedClasses
1164 * @param string $href URL
1166 public function addFeedLink( $format, $href ) {
1167 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1168 $this->mFeedLinks
[$format] = $href;
1173 * Should we output feed links for this page?
1176 public function isSyndicated() {
1177 return count( $this->mFeedLinks
) > 0;
1181 * Return URLs for each supported syndication format for this page.
1182 * @return array Associating format keys with URLs
1184 public function getSyndicationLinks() {
1185 return $this->mFeedLinks
;
1189 * Will currently always return null
1193 public function getFeedAppendQuery() {
1194 return $this->mFeedLinksAppendQuery
;
1198 * Set whether the displayed content is related to the source of the
1199 * corresponding article on the wiki
1200 * Setting true will cause the change "article related" toggle to true
1204 public function setArticleFlag( $v ) {
1205 $this->mIsarticle
= $v;
1207 $this->mIsArticleRelated
= $v;
1212 * Return whether the content displayed page is related to the source of
1213 * the corresponding article on the wiki
1217 public function isArticle() {
1218 return $this->mIsarticle
;
1222 * Set whether this page is related an article on the wiki
1223 * Setting false will cause the change of "article flag" toggle to false
1227 public function setArticleRelated( $v ) {
1228 $this->mIsArticleRelated
= $v;
1230 $this->mIsarticle
= false;
1235 * Return whether this page is related an article on the wiki
1239 public function isArticleRelated() {
1240 return $this->mIsArticleRelated
;
1244 * Add new language links
1246 * @param array $newLinkArray Associative array mapping language code to the page
1249 public function addLanguageLinks( array $newLinkArray ) {
1250 $this->mLanguageLinks +
= $newLinkArray;
1254 * Reset the language links and add new language links
1256 * @param array $newLinkArray Associative array mapping language code to the page
1259 public function setLanguageLinks( array $newLinkArray ) {
1260 $this->mLanguageLinks
= $newLinkArray;
1264 * Get the list of language links
1266 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1268 public function getLanguageLinks() {
1269 return $this->mLanguageLinks
;
1273 * Add an array of categories, with names in the keys
1275 * @param array $categories Mapping category name => sort key
1277 public function addCategoryLinks( array $categories ) {
1280 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1284 # Add the links to a LinkBatch
1285 $arr = array( NS_CATEGORY
=> $categories );
1286 $lb = new LinkBatch
;
1287 $lb->setArray( $arr );
1289 # Fetch existence plus the hiddencat property
1290 $dbr = wfGetDB( DB_SLAVE
);
1291 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1292 'page_is_redirect', 'page_latest', 'pp_value' );
1294 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1295 $fields[] = 'page_content_model';
1298 $res = $dbr->select( array( 'page', 'page_props' ),
1300 $lb->constructSet( 'page', $dbr ),
1303 array( 'page_props' => array( 'LEFT JOIN', array(
1304 'pp_propname' => 'hiddencat',
1309 # Add the results to the link cache
1310 $lb->addResultToCache( LinkCache
::singleton(), $res );
1312 # Set all the values to 'normal'.
1313 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1315 # Mark hidden categories
1316 foreach ( $res as $row ) {
1317 if ( isset( $row->pp_value
) ) {
1318 $categories[$row->page_title
] = 'hidden';
1322 # Add the remaining categories to the skin
1324 'OutputPageMakeCategoryLinks',
1325 array( &$this, $categories, &$this->mCategoryLinks
) )
1327 foreach ( $categories as $category => $type ) {
1328 $origcategory = $category;
1329 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1333 $wgContLang->findVariantLink( $category, $title, true );
1334 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1337 $text = $wgContLang->convertHtml( $title->getText() );
1338 $this->mCategories
[] = $title->getText();
1339 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1345 * Reset the category links (but not the category list) and add $categories
1347 * @param array $categories Mapping category name => sort key
1349 public function setCategoryLinks( array $categories ) {
1350 $this->mCategoryLinks
= array();
1351 $this->addCategoryLinks( $categories );
1355 * Get the list of category links, in a 2-D array with the following format:
1356 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1357 * hidden categories) and $link a HTML fragment with a link to the category
1362 public function getCategoryLinks() {
1363 return $this->mCategoryLinks
;
1367 * Get the list of category names this page belongs to
1369 * @return array Array of strings
1371 public function getCategories() {
1372 return $this->mCategories
;
1376 * Add an array of indicators, with their identifiers as array
1377 * keys and HTML contents as values.
1379 * In case of duplicate keys, existing values are overwritten.
1381 * @param array $indicators
1384 public function setIndicators( array $indicators ) {
1385 $this->mIndicators
= $indicators +
$this->mIndicators
;
1386 // Keep ordered by key
1387 ksort( $this->mIndicators
);
1391 * Get the indicators associated with this page.
1393 * The array will be internally ordered by item keys.
1395 * @return array Keys: identifiers, values: HTML contents
1398 public function getIndicators() {
1399 return $this->mIndicators
;
1403 * Adds help link with an icon via page indicators.
1405 * @param bool $overrideBaseUrl
1408 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1409 $this->addModules( 'mediawiki.helplink' );
1410 $text = wfMessage( 'helppage-top-gethelp' )->escaped();
1412 if ( $overrideBaseUrl ) {
1415 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$to";
1417 $link = Html
::rawElement(
1421 'target' => '_blank',
1422 'class' => 'mw-helplink',
1427 $this->setIndicators( array( 'mw-helplink' => $link ) );
1431 * Do not allow scripts which can be modified by wiki users to load on this page;
1432 * only allow scripts bundled with, or generated by, the software.
1433 * Site-wide styles are controlled by a config setting, since they can be
1434 * used to create a custom skin/theme, but not user-specific ones.
1436 * @todo this should be given a more accurate name
1438 public function disallowUserJs() {
1439 $this->reduceAllowedModules(
1440 ResourceLoaderModule
::TYPE_SCRIPTS
,
1441 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1444 // Site-wide styles are controlled by a config setting, see bug 71621
1445 // for background on why. User styles are never allowed.
1446 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1447 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1449 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1451 $this->reduceAllowedModules(
1452 ResourceLoaderModule
::TYPE_STYLES
,
1458 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1459 * @see ResourceLoaderModule::$origin
1460 * @param string $type ResourceLoaderModule TYPE_ constant
1461 * @return int ResourceLoaderModule ORIGIN_ class constant
1463 public function getAllowedModules( $type ) {
1464 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1465 return min( array_values( $this->mAllowedModules
) );
1467 return isset( $this->mAllowedModules
[$type] )
1468 ?
$this->mAllowedModules
[$type]
1469 : ResourceLoaderModule
::ORIGIN_ALL
;
1474 * Set the highest level of CSS/JS untrustworthiness allowed
1476 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1477 * Use reduceAllowedModules() instead
1478 * @param string $type ResourceLoaderModule TYPE_ constant
1479 * @param int $level ResourceLoaderModule class constant
1481 public function setAllowedModules( $type, $level ) {
1482 wfDeprecated( __METHOD__
, '1.24' );
1483 $this->reduceAllowedModules( $type, $level );
1487 * Limit the highest level of CSS/JS untrustworthiness allowed.
1489 * If passed the same or a higher level than the current level of untrustworthiness set, the
1490 * level will remain unchanged.
1492 * @param string $type
1493 * @param int $level ResourceLoaderModule class constant
1495 public function reduceAllowedModules( $type, $level ) {
1496 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1500 * Prepend $text to the body HTML
1502 * @param string $text HTML
1504 public function prependHTML( $text ) {
1505 $this->mBodytext
= $text . $this->mBodytext
;
1509 * Append $text to the body HTML
1511 * @param string $text HTML
1513 public function addHTML( $text ) {
1514 $this->mBodytext
.= $text;
1518 * Shortcut for adding an Html::element via addHTML.
1522 * @param string $element
1523 * @param array $attribs
1524 * @param string $contents
1526 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1527 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1531 * Clear the body HTML
1533 public function clearHTML() {
1534 $this->mBodytext
= '';
1540 * @return string HTML
1542 public function getHTML() {
1543 return $this->mBodytext
;
1547 * Get/set the ParserOptions object to use for wikitext parsing
1549 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1550 * current ParserOption object
1551 * @return ParserOptions
1553 public function parserOptions( $options = null ) {
1554 if ( !$this->mParserOptions
) {
1555 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1556 $this->mParserOptions
->setEditSection( false );
1558 return wfSetVar( $this->mParserOptions
, $options );
1562 * Set the revision ID which will be seen by the wiki text parser
1563 * for things such as embedded {{REVISIONID}} variable use.
1565 * @param int|null $revid An positive integer, or null
1566 * @return mixed Previous value
1568 public function setRevisionId( $revid ) {
1569 $val = is_null( $revid ) ?
null : intval( $revid );
1570 return wfSetVar( $this->mRevisionId
, $val );
1574 * Get the displayed revision ID
1578 public function getRevisionId() {
1579 return $this->mRevisionId
;
1583 * Set the timestamp of the revision which will be displayed. This is used
1584 * to avoid a extra DB call in Skin::lastModified().
1586 * @param string|null $timestamp
1587 * @return mixed Previous value
1589 public function setRevisionTimestamp( $timestamp ) {
1590 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1594 * Get the timestamp of displayed revision.
1595 * This will be null if not filled by setRevisionTimestamp().
1597 * @return string|null
1599 public function getRevisionTimestamp() {
1600 return $this->mRevisionTimestamp
;
1604 * Set the displayed file version
1606 * @param File|bool $file
1607 * @return mixed Previous value
1609 public function setFileVersion( $file ) {
1611 if ( $file instanceof File
&& $file->exists() ) {
1612 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1614 return wfSetVar( $this->mFileVersion
, $val, true );
1618 * Get the displayed file version
1620 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1622 public function getFileVersion() {
1623 return $this->mFileVersion
;
1627 * Get the templates used on this page
1629 * @return array (namespace => dbKey => revId)
1632 public function getTemplateIds() {
1633 return $this->mTemplateIds
;
1637 * Get the files used on this page
1639 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1642 public function getFileSearchOptions() {
1643 return $this->mImageTimeKeys
;
1647 * Convert wikitext to HTML and add it to the buffer
1648 * Default assumes that the current page title will be used.
1650 * @param string $text
1651 * @param bool $linestart Is this the start of a line?
1652 * @param bool $interface Is this text in the user interface language?
1653 * @throws MWException
1655 public function addWikiText( $text, $linestart = true, $interface = true ) {
1656 $title = $this->getTitle(); // Work around E_STRICT
1658 throw new MWException( 'Title is null' );
1660 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1664 * Add wikitext with a custom Title object
1666 * @param string $text Wikitext
1667 * @param Title $title
1668 * @param bool $linestart Is this the start of a line?
1670 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1671 $this->addWikiTextTitle( $text, $title, $linestart );
1675 * Add wikitext with a custom Title object and tidy enabled.
1677 * @param string $text Wikitext
1678 * @param Title $title
1679 * @param bool $linestart Is this the start of a line?
1681 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1682 $this->addWikiTextTitle( $text, $title, $linestart, true );
1686 * Add wikitext with tidy enabled
1688 * @param string $text Wikitext
1689 * @param bool $linestart Is this the start of a line?
1691 public function addWikiTextTidy( $text, $linestart = true ) {
1692 $title = $this->getTitle();
1693 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1697 * Add wikitext with a custom Title object
1699 * @param string $text Wikitext
1700 * @param Title $title
1701 * @param bool $linestart Is this the start of a line?
1702 * @param bool $tidy Whether to use tidy
1703 * @param bool $interface Whether it is an interface message
1704 * (for example disables conversion)
1706 public function addWikiTextTitle( $text, Title
$title, $linestart,
1707 $tidy = false, $interface = false
1711 $popts = $this->parserOptions();
1712 $oldTidy = $popts->setTidy( $tidy );
1713 $popts->setInterfaceMessage( (bool)$interface );
1715 $parserOutput = $wgParser->getFreshParser()->parse(
1716 $text, $title, $popts,
1717 $linestart, true, $this->mRevisionId
1720 $popts->setTidy( $oldTidy );
1722 $this->addParserOutput( $parserOutput );
1727 * Add a ParserOutput object, but without Html.
1729 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1730 * @param ParserOutput $parserOutput
1732 public function addParserOutputNoText( $parserOutput ) {
1733 $this->addParserOutputMetadata( $parserOutput );
1737 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1738 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1742 * @param ParserOutput $parserOutput
1744 public function addParserOutputMetadata( $parserOutput ) {
1745 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1746 $this->addCategoryLinks( $parserOutput->getCategories() );
1747 $this->setIndicators( $parserOutput->getIndicators() );
1748 $this->mNewSectionLink
= $parserOutput->getNewSection();
1749 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1751 $this->mParseWarnings
= $parserOutput->getWarnings();
1752 if ( !$parserOutput->isCacheable() ) {
1753 $this->enableClientCache( false );
1755 $this->mNoGallery
= $parserOutput->getNoGallery();
1756 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1757 $this->addModules( $parserOutput->getModules() );
1758 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1759 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1760 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1761 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1762 $this->mPreventClickjacking
= $this->mPreventClickjacking
1763 ||
$parserOutput->preventClickjacking();
1765 // Template versioning...
1766 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1767 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1768 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1770 $this->mTemplateIds
[$ns] = $dbks;
1773 // File versioning...
1774 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1775 $this->mImageTimeKeys
[$dbk] = $data;
1778 // Hooks registered in the object
1779 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1780 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1781 list( $hookName, $data ) = $hookInfo;
1782 if ( isset( $parserOutputHooks[$hookName] ) ) {
1783 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1787 // Link flags are ignored for now, but may in the future be
1788 // used to mark individual language links.
1789 $linkFlags = array();
1790 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1791 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1795 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1796 * ParserOutput object, without any other metadata.
1799 * @param ParserOutput $parserOutput
1801 public function addParserOutputContent( $parserOutput ) {
1802 $this->addParserOutputText( $parserOutput );
1804 $this->addModules( $parserOutput->getModules() );
1805 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1806 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1807 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1809 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1813 * Add the HTML associated with a ParserOutput object, without any metadata.
1816 * @param ParserOutput $parserOutput
1818 public function addParserOutputText( $parserOutput ) {
1819 $text = $parserOutput->getText();
1820 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1821 $this->addHTML( $text );
1825 * Add everything from a ParserOutput object.
1827 * @param ParserOutput $parserOutput
1829 function addParserOutput( $parserOutput ) {
1830 $this->addParserOutputMetadata( $parserOutput );
1831 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1833 // Touch section edit links only if not previously disabled
1834 if ( $parserOutput->getEditSectionTokens() ) {
1835 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1838 $this->addParserOutputText( $parserOutput );
1842 * Add the output of a QuickTemplate to the output buffer
1844 * @param QuickTemplate $template
1846 public function addTemplate( &$template ) {
1847 $this->addHTML( $template->getHTML() );
1851 * Parse wikitext and return the HTML.
1853 * @param string $text
1854 * @param bool $linestart Is this the start of a line?
1855 * @param bool $interface Use interface language ($wgLang instead of
1856 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1857 * This also disables LanguageConverter.
1858 * @param Language $language Target language object, will override $interface
1859 * @throws MWException
1860 * @return string HTML
1862 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1865 if ( is_null( $this->getTitle() ) ) {
1866 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1869 $popts = $this->parserOptions();
1871 $popts->setInterfaceMessage( true );
1873 if ( $language !== null ) {
1874 $oldLang = $popts->setTargetLanguage( $language );
1877 $parserOutput = $wgParser->getFreshParser()->parse(
1878 $text, $this->getTitle(), $popts,
1879 $linestart, true, $this->mRevisionId
1883 $popts->setInterfaceMessage( false );
1885 if ( $language !== null ) {
1886 $popts->setTargetLanguage( $oldLang );
1889 return $parserOutput->getText();
1893 * Parse wikitext, strip paragraphs, and return the HTML.
1895 * @param string $text
1896 * @param bool $linestart Is this the start of a line?
1897 * @param bool $interface Use interface language ($wgLang instead of
1898 * $wgContLang) while parsing language sensitive magic
1899 * words like GRAMMAR and PLURAL
1900 * @return string HTML
1902 public function parseInline( $text, $linestart = true, $interface = false ) {
1903 $parsed = $this->parse( $text, $linestart, $interface );
1904 return Parser
::stripOuterParagraph( $parsed );
1908 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1910 * @param int $maxage Maximum cache time on the Squid, in seconds.
1912 public function setSquidMaxage( $maxage ) {
1913 $this->mSquidMaxage
= $maxage;
1917 * Use enableClientCache(false) to force it to send nocache headers
1919 * @param bool $state
1923 public function enableClientCache( $state ) {
1924 return wfSetVar( $this->mEnableClientCache
, $state );
1928 * Get the list of cookies that will influence on the cache
1932 function getCacheVaryCookies() {
1934 if ( $cookies === null ) {
1935 $config = $this->getConfig();
1936 $cookies = array_merge(
1938 $config->get( 'CookiePrefix' ) . 'Token',
1939 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1943 $config->get( 'CacheVaryCookies' )
1945 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1951 * Check if the request has a cache-varying cookie header
1952 * If it does, it's very important that we don't allow public caching
1956 function haveCacheVaryCookies() {
1957 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1958 if ( $cookieHeader === false ) {
1961 $cvCookies = $this->getCacheVaryCookies();
1962 foreach ( $cvCookies as $cookieName ) {
1963 # Check for a simple string match, like the way squid does it
1964 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1965 wfDebug( __METHOD__
. ": found $cookieName\n" );
1969 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1974 * Add an HTTP header that will influence on the cache
1976 * @param string $header Header name
1977 * @param array|null $option
1978 * @todo FIXME: Document the $option parameter; it appears to be for
1979 * X-Vary-Options but what format is acceptable?
1981 public function addVaryHeader( $header, $option = null ) {
1982 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1983 $this->mVaryHeader
[$header] = (array)$option;
1984 } elseif ( is_array( $option ) ) {
1985 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1986 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1988 $this->mVaryHeader
[$header] = $option;
1991 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1995 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1996 * such as Accept-Encoding or Cookie
2000 public function getVaryHeader() {
2001 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2005 * Get a complete X-Vary-Options header
2009 public function getXVO() {
2010 $cvCookies = $this->getCacheVaryCookies();
2012 $cookiesOption = array();
2013 foreach ( $cvCookies as $cookieName ) {
2014 $cookiesOption[] = 'string-contains=' . $cookieName;
2016 $this->addVaryHeader( 'Cookie', $cookiesOption );
2019 foreach ( $this->mVaryHeader
as $header => $option ) {
2020 $newheader = $header;
2021 if ( is_array( $option ) && count( $option ) > 0 ) {
2022 $newheader .= ';' . implode( ';', $option );
2024 $headers[] = $newheader;
2026 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2032 * bug 21672: Add Accept-Language to Vary and XVO headers
2033 * if there's no 'variant' parameter existed in GET.
2036 * /w/index.php?title=Main_page should always be served; but
2037 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2039 function addAcceptLanguage() {
2040 $title = $this->getTitle();
2041 if ( !$title instanceof Title
) {
2045 $lang = $title->getPageLanguage();
2046 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2047 $variants = $lang->getVariants();
2048 $aloption = array();
2049 foreach ( $variants as $variant ) {
2050 if ( $variant === $lang->getCode() ) {
2053 $aloption[] = 'string-contains=' . $variant;
2055 // IE and some other browsers use BCP 47 standards in
2056 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2057 // We should handle these too.
2058 $variantBCP47 = wfBCP47( $variant );
2059 if ( $variantBCP47 !== $variant ) {
2060 $aloption[] = 'string-contains=' . $variantBCP47;
2064 $this->addVaryHeader( 'Accept-Language', $aloption );
2069 * Set a flag which will cause an X-Frame-Options header appropriate for
2070 * edit pages to be sent. The header value is controlled by
2071 * $wgEditPageFrameOptions.
2073 * This is the default for special pages. If you display a CSRF-protected
2074 * form on an ordinary view page, then you need to call this function.
2076 * @param bool $enable
2078 public function preventClickjacking( $enable = true ) {
2079 $this->mPreventClickjacking
= $enable;
2083 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2084 * This can be called from pages which do not contain any CSRF-protected
2087 public function allowClickjacking() {
2088 $this->mPreventClickjacking
= false;
2092 * Get the prevent-clickjacking flag
2097 public function getPreventClickjacking() {
2098 return $this->mPreventClickjacking
;
2102 * Get the X-Frame-Options header value (without the name part), or false
2103 * if there isn't one. This is used by Skin to determine whether to enable
2104 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2108 public function getFrameOptions() {
2109 $config = $this->getConfig();
2110 if ( $config->get( 'BreakFrames' ) ) {
2112 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2113 return $config->get( 'EditPageFrameOptions' );
2119 * Send cache control HTTP headers
2121 public function sendCacheControl() {
2122 $response = $this->getRequest()->response();
2123 $config = $this->getConfig();
2124 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2125 $response->header( "ETag: $this->mETag" );
2128 $this->addVaryHeader( 'Cookie' );
2129 $this->addAcceptLanguage();
2131 # don't serve compressed data to clients who can't handle it
2132 # maintain different caches for logged-in users and non-logged in ones
2133 $response->header( $this->getVaryHeader() );
2135 if ( $config->get( 'UseXVO' ) ) {
2136 # Add an X-Vary-Options header for Squid with Wikimedia patches
2137 $response->header( $this->getXVO() );
2140 if ( $this->mEnableClientCache
) {
2142 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2143 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2145 if ( $config->get( 'UseESI' ) ) {
2146 # We'll purge the proxy cache explicitly, but require end user agents
2147 # to revalidate against the proxy on each visit.
2148 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2149 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2150 # start with a shorter timeout for initial testing
2151 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2152 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2153 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2154 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2156 # We'll purge the proxy cache for anons explicitly, but require end user agents
2157 # to revalidate against the proxy on each visit.
2158 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2159 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2160 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2161 # start with a shorter timeout for initial testing
2162 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2163 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2164 . ', must-revalidate, max-age=0' );
2167 # We do want clients to cache if they can, but they *must* check for updates
2168 # on revisiting the page.
2169 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2170 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2171 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2173 if ( $this->mLastModified
) {
2174 $response->header( "Last-Modified: {$this->mLastModified}" );
2177 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2179 # In general, the absence of a last modified header should be enough to prevent
2180 # the client from using its cache. We send a few other things just to make sure.
2181 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2182 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2183 $response->header( 'Pragma: no-cache' );
2188 * Finally, all the text has been munged and accumulated into
2189 * the object, let's actually output it:
2191 public function output() {
2192 if ( $this->mDoNothing
) {
2196 $response = $this->getRequest()->response();
2197 $config = $this->getConfig();
2199 if ( $this->mRedirect
!= '' ) {
2200 # Standards require redirect URLs to be absolute
2201 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2203 $redirect = $this->mRedirect
;
2204 $code = $this->mRedirectCode
;
2206 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2207 if ( $code == '301' ||
$code == '303' ) {
2208 if ( !$config->get( 'DebugRedirects' ) ) {
2209 $message = HttpStatus
::getMessage( $code );
2210 $response->header( "HTTP/1.1 $code $message" );
2212 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2214 if ( $config->get( 'VaryOnXFP' ) ) {
2215 $this->addVaryHeader( 'X-Forwarded-Proto' );
2217 $this->sendCacheControl();
2219 $response->header( "Content-Type: text/html; charset=utf-8" );
2220 if ( $config->get( 'DebugRedirects' ) ) {
2221 $url = htmlspecialchars( $redirect );
2222 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2223 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2224 print "</body>\n</html>\n";
2226 $response->header( 'Location: ' . $redirect );
2231 } elseif ( $this->mStatusCode
) {
2232 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2234 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2238 # Buffer output; final headers may depend on later processing
2241 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2242 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2244 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2245 // jQuery etc. can work correctly.
2246 $response->header( 'X-UA-Compatible: IE=Edge' );
2248 // Prevent framing, if requested
2249 $frameOptions = $this->getFrameOptions();
2250 if ( $frameOptions ) {
2251 $response->header( "X-Frame-Options: $frameOptions" );
2254 if ( $this->mArticleBodyOnly
) {
2255 echo $this->mBodytext
;
2258 $sk = $this->getSkin();
2259 // add skin specific modules
2260 $modules = $sk->getDefaultModules();
2262 // enforce various default modules for all skins
2263 $coreModules = array(
2264 // keep this list as small as possible
2265 'mediawiki.page.startup',
2269 // Support for high-density display images if enabled
2270 if ( $config->get( 'ResponsiveImages' ) ) {
2271 $coreModules[] = 'mediawiki.hidpi';
2274 $this->addModules( $coreModules );
2275 foreach ( $modules as $group ) {
2276 $this->addModules( $group );
2278 MWDebug
::addModules( $this );
2280 // Hook that allows last minute changes to the output page, e.g.
2281 // adding of CSS or Javascript by extensions.
2282 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2287 // This hook allows last minute changes to final overall output by modifying output buffer
2288 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2290 $this->sendCacheControl();
2297 * Actually output something with print.
2299 * @param string $ins The string to output
2300 * @deprecated since 1.22 Use echo yourself.
2302 public function out( $ins ) {
2303 wfDeprecated( __METHOD__
, '1.22' );
2308 * Produce a "user is blocked" page.
2309 * @deprecated since 1.18
2311 function blockedPage() {
2312 throw new UserBlockedError( $this->getUser()->mBlock
);
2316 * Prepare this object to display an error page; disable caching and
2317 * indexing, clear the current text and redirect, set the page's title
2318 * and optionally an custom HTML title (content of the "<title>" tag).
2320 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2321 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2322 * optional, if not passed the "<title>" attribute will be
2323 * based on $pageTitle
2325 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2326 $this->setPageTitle( $pageTitle );
2327 if ( $htmlTitle !== false ) {
2328 $this->setHTMLTitle( $htmlTitle );
2330 $this->setRobotPolicy( 'noindex,nofollow' );
2331 $this->setArticleRelated( false );
2332 $this->enableClientCache( false );
2333 $this->mRedirect
= '';
2334 $this->clearSubtitle();
2339 * Output a standard error page
2341 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2342 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2343 * showErrorPage( 'titlemsg', $messageObject );
2344 * showErrorPage( $titleMessageObject, $messageObject );
2346 * @param string|Message $title Message key (string) for page title, or a Message object
2347 * @param string|Message $msg Message key (string) for page text, or a Message object
2348 * @param array $params Message parameters; ignored if $msg is a Message object
2350 public function showErrorPage( $title, $msg, $params = array() ) {
2351 if ( !$title instanceof Message
) {
2352 $title = $this->msg( $title );
2355 $this->prepareErrorPage( $title );
2357 if ( $msg instanceof Message
) {
2358 if ( $params !== array() ) {
2359 trigger_error( 'Argument ignored: $params. The message parameters argument '
2360 . 'is discarded when the $msg argument is a Message object instead of '
2361 . 'a string.', E_USER_NOTICE
);
2363 $this->addHTML( $msg->parseAsBlock() );
2365 $this->addWikiMsgArray( $msg, $params );
2368 $this->returnToMain();
2372 * Output a standard permission error page
2374 * @param array $errors Error message keys
2375 * @param string $action Action that was denied or null if unknown
2377 public function showPermissionsErrorPage( array $errors, $action = null ) {
2378 // For some action (read, edit, create and upload), display a "login to do this action"
2379 // error if all of the following conditions are met:
2380 // 1. the user is not logged in
2381 // 2. the only error is insufficient permissions (i.e. no block or something else)
2382 // 3. the error can be avoided simply by logging in
2383 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2384 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2385 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2386 && ( User
::groupHasPermission( 'user', $action )
2387 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2389 $displayReturnto = null;
2391 # Due to bug 32276, if a user does not have read permissions,
2392 # $this->getTitle() will just give Special:Badtitle, which is
2393 # not especially useful as a returnto parameter. Use the title
2394 # from the request instead, if there was one.
2395 $request = $this->getRequest();
2396 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2397 if ( $action == 'edit' ) {
2398 $msg = 'whitelistedittext';
2399 $displayReturnto = $returnto;
2400 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2401 $msg = 'nocreatetext';
2402 } elseif ( $action == 'upload' ) {
2403 $msg = 'uploadnologintext';
2405 $msg = 'loginreqpagetext';
2406 $displayReturnto = Title
::newMainPage();
2412 $query['returnto'] = $returnto->getPrefixedText();
2414 if ( !$request->wasPosted() ) {
2415 $returntoquery = $request->getValues();
2416 unset( $returntoquery['title'] );
2417 unset( $returntoquery['returnto'] );
2418 unset( $returntoquery['returntoquery'] );
2419 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2422 $loginLink = Linker
::linkKnown(
2423 SpecialPage
::getTitleFor( 'Userlogin' ),
2424 $this->msg( 'loginreqlink' )->escaped(),
2429 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2430 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2432 # Don't return to a page the user can't read otherwise
2433 # we'll end up in a pointless loop
2434 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2435 $this->returnToMain( null, $displayReturnto );
2438 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2439 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2444 * Display an error page indicating that a given version of MediaWiki is
2445 * required to use it
2447 * @param mixed $version The version of MediaWiki needed to use the page
2449 public function versionRequired( $version ) {
2450 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2452 $this->addWikiMsg( 'versionrequiredtext', $version );
2453 $this->returnToMain();
2457 * Display an error page noting that a given permission bit is required.
2458 * @deprecated since 1.18, just throw the exception directly
2459 * @param string $permission Key required
2460 * @throws PermissionsError
2462 public function permissionRequired( $permission ) {
2463 throw new PermissionsError( $permission );
2467 * Produce the stock "please login to use the wiki" page
2469 * @deprecated since 1.19; throw the exception directly
2471 public function loginToUse() {
2472 throw new PermissionsError( 'read' );
2476 * Format a list of error messages
2478 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2479 * @param string $action Action that was denied or null if unknown
2480 * @return string The wikitext error-messages, formatted into a list.
2482 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2483 if ( $action == null ) {
2484 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2486 $action_desc = $this->msg( "action-$action" )->plain();
2488 'permissionserrorstext-withaction',
2491 )->plain() . "\n\n";
2494 if ( count( $errors ) > 1 ) {
2495 $text .= '<ul class="permissions-errors">' . "\n";
2497 foreach ( $errors as $error ) {
2499 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2504 $text .= "<div class=\"permissions-errors\">\n" .
2505 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2513 * Display a page stating that the Wiki is in read-only mode.
2514 * Should only be called after wfReadOnly() has returned true.
2516 * Historically, this function was used to show the source of the page that the user
2517 * was trying to edit and _also_ permissions error messages. The relevant code was
2518 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2520 * @deprecated since 1.25; throw the exception directly
2521 * @throws ReadOnlyError
2523 public function readOnlyPage() {
2524 if ( func_num_args() > 0 ) {
2525 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2528 throw new ReadOnlyError
;
2532 * Turn off regular page output and return an error response
2533 * for when rate limiting has triggered.
2535 * @deprecated since 1.25; throw the exception directly
2537 public function rateLimited() {
2538 wfDeprecated( __METHOD__
, '1.25' );
2539 throw new ThrottledError
;
2543 * Show a warning about slave lag
2545 * If the lag is higher than $wgSlaveLagCritical seconds,
2546 * then the warning is a bit more obvious. If the lag is
2547 * lower than $wgSlaveLagWarning, then no warning is shown.
2549 * @param int $lag Slave lag
2551 public function showLagWarning( $lag ) {
2552 $config = $this->getConfig();
2553 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2554 $message = $lag < $config->get( 'SlaveLagCritical' )
2557 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2558 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2562 public function showFatalError( $message ) {
2563 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2565 $this->addHTML( $message );
2568 public function showUnexpectedValueError( $name, $val ) {
2569 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2572 public function showFileCopyError( $old, $new ) {
2573 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2576 public function showFileRenameError( $old, $new ) {
2577 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2580 public function showFileDeleteError( $name ) {
2581 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2584 public function showFileNotFoundError( $name ) {
2585 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2589 * Add a "return to" link pointing to a specified title
2591 * @param Title $title Title to link
2592 * @param array $query Query string parameters
2593 * @param string $text Text of the link (input is not escaped)
2594 * @param array $options Options array to pass to Linker
2596 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2597 $link = $this->msg( 'returnto' )->rawParams(
2598 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2599 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2603 * Add a "return to" link pointing to a specified title,
2604 * or the title indicated in the request, or else the main page
2606 * @param mixed $unused
2607 * @param Title|string $returnto Title or String to return to
2608 * @param string $returntoquery Query string for the return to link
2610 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2611 if ( $returnto == null ) {
2612 $returnto = $this->getRequest()->getText( 'returnto' );
2615 if ( $returntoquery == null ) {
2616 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2619 if ( $returnto === '' ) {
2620 $returnto = Title
::newMainPage();
2623 if ( is_object( $returnto ) ) {
2624 $titleObj = $returnto;
2626 $titleObj = Title
::newFromText( $returnto );
2628 if ( !is_object( $titleObj ) ) {
2629 $titleObj = Title
::newMainPage();
2632 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2636 * @param Skin $sk The given Skin
2637 * @param bool $includeStyle Unused
2638 * @return string The doctype, opening "<html>", and head element.
2640 public function headElement( Skin
$sk, $includeStyle = true ) {
2643 $userdir = $this->getLanguage()->getDir();
2644 $sitedir = $wgContLang->getDir();
2646 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2648 if ( $this->getHTMLTitle() == '' ) {
2649 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2652 $openHead = Html
::openElement( 'head' );
2654 # Don't bother with the newline if $head == ''
2655 $ret .= "$openHead\n";
2658 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2659 // Add <meta charset="UTF-8">
2660 // This should be before <title> since it defines the charset used by
2661 // text including the text inside <title>.
2662 // The spec recommends defining XHTML5's charset using the XML declaration
2664 // Our XML declaration is output by Html::htmlHeader.
2665 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2666 // http://www.whatwg.org/html/semantics.html#charset
2667 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2670 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2672 foreach ( $this->getHeadLinksArray() as $item ) {
2673 $ret .= $item . "\n";
2676 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2677 $ret .= $this->buildCssLinks();
2679 $ret .= $this->getHeadScripts() . "\n";
2681 foreach ( $this->mHeadItems
as $item ) {
2682 $ret .= $item . "\n";
2685 $closeHead = Html
::closeElement( 'head' );
2687 $ret .= "$closeHead\n";
2690 $bodyClasses = array();
2691 $bodyClasses[] = 'mediawiki';
2693 # Classes for LTR/RTL directionality support
2694 $bodyClasses[] = $userdir;
2695 $bodyClasses[] = "sitedir-$sitedir";
2697 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2698 # A <body> class is probably not the best way to do this . . .
2699 $bodyClasses[] = 'capitalize-all-nouns';
2702 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2703 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2705 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2707 $bodyAttrs = array();
2708 // While the implode() is not strictly needed, it's used for backwards compatibility
2709 // (this used to be built as a string and hooks likely still expect that).
2710 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2712 // Allow skins and extensions to add body attributes they need
2713 $sk->addToBodyAttributes( $this, $bodyAttrs );
2714 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2716 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2722 * Get a ResourceLoader object associated with this OutputPage
2724 * @return ResourceLoader
2726 public function getResourceLoader() {
2727 if ( is_null( $this->mResourceLoader
) ) {
2728 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2730 return $this->mResourceLoader
;
2735 * @param array|string $modules One or more module names
2736 * @param string $only ResourceLoaderModule TYPE_ class constant
2737 * @param bool $useESI
2738 * @param array $extraQuery Array with extra query parameters to add to each
2739 * request. array( param => value ).
2740 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2741 * call rather than a "<script src='...'>" tag.
2742 * @return string The html "<script>", "<link>" and "<style>" tags
2744 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2745 array $extraQuery = array(), $loadCall = false
2747 $modules = (array)$modules;
2751 'states' => array(),
2754 if ( !count( $modules ) ) {
2758 if ( count( $modules ) > 1 ) {
2759 // Remove duplicate module requests
2760 $modules = array_unique( $modules );
2761 // Sort module names so requests are more uniform
2764 if ( ResourceLoader
::inDebugMode() ) {
2765 // Recursively call us for every item
2766 foreach ( $modules as $name ) {
2767 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2768 $links['html'] .= $link['html'];
2769 $links['states'] +
= $link['states'];
2775 if ( !is_null( $this->mTarget
) ) {
2776 $extraQuery['target'] = $this->mTarget
;
2779 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2780 $sortedModules = array();
2781 $resourceLoader = $this->getResourceLoader();
2782 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2783 foreach ( $modules as $name ) {
2784 $module = $resourceLoader->getModule( $name );
2785 # Check that we're allowed to include this module on this page
2787 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2788 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2789 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2790 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2791 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2792 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2793 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2798 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2801 foreach ( $sortedModules as $source => $groups ) {
2802 foreach ( $groups as $group => $grpModules ) {
2803 // Special handling for user-specific groups
2805 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2806 $user = $this->getUser()->getName();
2809 // Create a fake request based on the one we are about to make so modules return
2810 // correct timestamp and emptiness data
2811 $query = ResourceLoader
::makeLoaderQuery(
2812 array(), // modules; not determined yet
2813 $this->getLanguage()->getCode(),
2814 $this->getSkin()->getSkinName(),
2816 null, // version; not determined yet
2817 ResourceLoader
::inDebugMode(),
2818 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2819 $this->isPrintable(),
2820 $this->getRequest()->getBool( 'handheld' ),
2823 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2825 // Extract modules that know they're empty and see if we have one or more
2828 foreach ( $grpModules as $key => $module ) {
2829 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2830 // If we're only getting the styles, we don't need to do anything for empty modules.
2831 if ( $module->isKnownEmpty( $context ) ) {
2832 unset( $grpModules[$key] );
2833 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2834 $links['states'][$key] = 'ready';
2838 $isRaw |
= $module->isRaw();
2841 // If there are no non-empty modules, skip this group
2842 if ( count( $grpModules ) === 0 ) {
2846 // Inline private modules. These can't be loaded through load.php for security
2847 // reasons, see bug 34907. Note that these modules should be loaded from
2848 // getHeadScripts() before the first loader call. Otherwise other modules can't
2849 // properly use them as dependencies (bug 30914)
2850 if ( $group === 'private' ) {
2851 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2852 $links['html'] .= Html
::inlineStyle(
2853 $resourceLoader->makeModuleResponse( $context, $grpModules )
2856 $links['html'] .= Html
::inlineScript(
2857 ResourceLoader
::makeLoaderConditionalScript(
2858 $resourceLoader->makeModuleResponse( $context, $grpModules )
2862 $links['html'] .= "\n";
2866 // Special handling for the user group; because users might change their stuff
2867 // on-wiki like user pages, or user preferences; we need to find the highest
2868 // timestamp of these user-changeable modules so we can ensure cache misses on change
2869 // This should NOT be done for the site group (bug 27564) because anons get that too
2870 // and we shouldn't be putting timestamps in Squid-cached HTML
2872 if ( $group === 'user' ) {
2873 // Get the maximum timestamp
2875 foreach ( $grpModules as $module ) {
2876 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2878 // Add a version parameter so cache will break when things change
2879 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2882 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2883 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2884 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2886 if ( $useESI && $resourceLoaderUseESI ) {
2887 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2888 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2889 $link = Html
::inlineStyle( $esi );
2891 $link = Html
::inlineScript( $esi );
2894 // Automatically select style/script elements
2895 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2896 $link = Html
::linkedStyle( $url );
2897 } elseif ( $loadCall ) {
2898 $link = Html
::inlineScript(
2899 ResourceLoader
::makeLoaderConditionalScript(
2900 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2904 $link = Html
::linkedScript( $url );
2905 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2906 // Wrap only=script requests in a conditional as browsers not supported
2907 // by the startup module would unconditionally execute this module.
2908 // Otherwise users will get "ReferenceError: mw is undefined" or
2909 // "jQuery is undefined" from e.g. a "site" module.
2910 $link = Html
::inlineScript(
2911 ResourceLoader
::makeLoaderConditionalScript(
2912 Xml
::encodeJsCall( 'document.write', array( $link ) )
2917 // For modules requested directly in the html via <link> or <script>,
2918 // tell mw.loader they are being loading to prevent duplicate requests.
2919 foreach ( $grpModules as $key => $module ) {
2920 // Don't output state=loading for the startup module..
2921 if ( $key !== 'startup' ) {
2922 $links['states'][$key] = 'loading';
2928 if ( $group == 'noscript' ) {
2929 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2931 $links['html'] .= $link . "\n";
2940 * Build html output from an array of links from makeResourceLoaderLink.
2941 * @param array $links
2942 * @return string HTML
2944 protected static function getHtmlFromLoaderLinks( array $links ) {
2947 foreach ( $links as $link ) {
2948 if ( !is_array( $link ) ) {
2951 $html .= $link['html'];
2952 $states +
= $link['states'];
2956 if ( count( $states ) ) {
2957 $html = Html
::inlineScript(
2958 ResourceLoader
::makeLoaderConditionalScript(
2959 ResourceLoader
::makeLoaderStateScript( $states )
2968 * JS stuff to put in the "<head>". This is the startup module, config
2969 * vars and modules marked with position 'top'
2971 * @return string HTML fragment
2973 function getHeadScripts() {
2974 // Startup - this will immediately load jquery and mediawiki modules
2976 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2978 // Load config before anything else
2979 $links[] = Html
::inlineScript(
2980 ResourceLoader
::makeLoaderConditionalScript(
2981 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2985 // Load embeddable private modules before any loader links
2986 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2987 // in mw.loader.implement() calls and deferred until mw.user is available
2988 $embedScripts = array( 'user.options', 'user.tokens' );
2989 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2991 // Scripts and messages "only" requests marked for top inclusion
2992 // Messages should go first
2993 $links[] = $this->makeResourceLoaderLink(
2994 $this->getModuleMessages( true, 'top' ),
2995 ResourceLoaderModule
::TYPE_MESSAGES
2997 $links[] = $this->makeResourceLoaderLink(
2998 $this->getModuleScripts( true, 'top' ),
2999 ResourceLoaderModule
::TYPE_SCRIPTS
3002 // Modules requests - let the client calculate dependencies and batch requests as it likes
3003 // Only load modules that have marked themselves for loading at the top
3004 $modules = $this->getModules( true, 'top' );
3006 $links[] = Html
::inlineScript(
3007 ResourceLoader
::makeLoaderConditionalScript(
3008 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3013 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3014 $links[] = $this->getScriptsForBottomQueue( true );
3017 return self
::getHtmlFromLoaderLinks( $links );
3021 * JS stuff to put at the 'bottom', which can either be the bottom of the
3022 * "<body>" or the bottom of the "<head>" depending on
3023 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3024 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3027 * @param bool $inHead If true, this HTML goes into the "<head>",
3028 * if false it goes into the "<body>".
3031 function getScriptsForBottomQueue( $inHead ) {
3032 // Scripts and messages "only" requests marked for bottom inclusion
3033 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3034 // Messages should go first
3036 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
3037 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
3038 /* $loadCall = */ $inHead
3040 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3041 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
3042 /* $loadCall = */ $inHead
3045 // Modules requests - let the client calculate dependencies and batch requests as it likes
3046 // Only load modules that have marked themselves for loading at the bottom
3047 $modules = $this->getModules( true, 'bottom' );
3049 $links[] = Html
::inlineScript(
3050 ResourceLoader
::makeLoaderConditionalScript(
3051 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3057 $links[] = "\n" . $this->mScripts
;
3059 // Add site JS if enabled
3060 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3061 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3064 // Add user JS if enabled
3065 if ( $this->getConfig()->get( 'AllowUserJs' )
3066 && $this->getUser()->isLoggedIn()
3067 && $this->getTitle()
3068 && $this->getTitle()->isJsSubpage()
3069 && $this->userCanPreview()
3071 # XXX: additional security check/prompt?
3072 // We're on a preview of a JS subpage
3073 // Exclude this page from the user module in case it's in there (bug 26283)
3074 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3075 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3077 // Load the previewed JS
3078 $links[] = Html
::inlineScript( "\n"
3079 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3081 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3082 // asynchronously and may arrive *after* the inline script here. So the previewed code
3083 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3085 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3086 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3087 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3091 // Group JS is only enabled if site JS is enabled.
3092 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3093 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3096 return self
::getHtmlFromLoaderLinks( $links );
3100 * JS stuff to put at the bottom of the "<body>"
3103 function getBottomScripts() {
3104 // Optimise jQuery ready event cross-browser.
3105 // This also enforces $.isReady to be true at </body> which fixes the
3106 // mw.loader bug in Firefox with using document.write between </body>
3107 // and the DOMContentReady event (bug 47457).
3108 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3110 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3111 $html .= $this->getScriptsForBottomQueue( false );
3118 * Get the javascript config vars to include on this page
3120 * @return array Array of javascript config vars
3123 public function getJsConfigVars() {
3124 return $this->mJsConfigVars
;
3128 * Add one or more variables to be set in mw.config in JavaScript
3130 * @param string|array $keys Key or array of key/value pairs
3131 * @param mixed $value [optional] Value of the configuration variable
3133 public function addJsConfigVars( $keys, $value = null ) {
3134 if ( is_array( $keys ) ) {
3135 foreach ( $keys as $key => $value ) {
3136 $this->mJsConfigVars
[$key] = $value;
3141 $this->mJsConfigVars
[$keys] = $value;
3145 * Get an array containing the variables to be set in mw.config in JavaScript.
3147 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3148 * - in other words, page-independent/site-wide variables (without state).
3149 * You will only be adding bloat to the html page and causing page caches to
3150 * have to be purged on configuration changes.
3153 public function getJSVars() {
3158 $canonicalSpecialPageName = false; # bug 21115
3160 $title = $this->getTitle();
3161 $ns = $title->getNamespace();
3162 $canonicalNamespace = MWNamespace
::exists( $ns )
3163 ? MWNamespace
::getCanonicalName( $ns )
3164 : $title->getNsText();
3166 $sk = $this->getSkin();
3167 // Get the relevant title so that AJAX features can use the correct page name
3168 // when making API requests from certain special pages (bug 34972).
3169 $relevantTitle = $sk->getRelevantTitle();
3170 $relevantUser = $sk->getRelevantUser();
3172 if ( $ns == NS_SPECIAL
) {
3173 list( $canonicalSpecialPageName, /*...*/ ) =
3174 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3175 } elseif ( $this->canUseWikiPage() ) {
3176 $wikiPage = $this->getWikiPage();
3177 $curRevisionId = $wikiPage->getLatest();
3178 $articleId = $wikiPage->getId();
3181 $lang = $title->getPageLanguage();
3183 // Pre-process information
3184 $separatorTransTable = $lang->separatorTransformTable();
3185 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3186 $compactSeparatorTransTable = array(
3187 implode( "\t", array_keys( $separatorTransTable ) ),
3188 implode( "\t", $separatorTransTable ),
3190 $digitTransTable = $lang->digitTransformTable();
3191 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3192 $compactDigitTransTable = array(
3193 implode( "\t", array_keys( $digitTransTable ) ),
3194 implode( "\t", $digitTransTable ),
3197 $user = $this->getUser();
3200 'wgCanonicalNamespace' => $canonicalNamespace,
3201 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3202 'wgNamespaceNumber' => $title->getNamespace(),
3203 'wgPageName' => $title->getPrefixedDBkey(),
3204 'wgTitle' => $title->getText(),
3205 'wgCurRevisionId' => $curRevisionId,
3206 'wgRevisionId' => (int)$this->getRevisionId(),
3207 'wgArticleId' => $articleId,
3208 'wgIsArticle' => $this->isArticle(),
3209 'wgIsRedirect' => $title->isRedirect(),
3210 'wgAction' => Action
::getActionName( $this->getContext() ),
3211 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3212 'wgUserGroups' => $user->getEffectiveGroups(),
3213 'wgCategories' => $this->getCategories(),
3214 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3215 'wgPageContentLanguage' => $lang->getCode(),
3216 'wgPageContentModel' => $title->getContentModel(),
3217 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3218 'wgDigitTransformTable' => $compactDigitTransTable,
3219 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3220 'wgMonthNames' => $lang->getMonthNamesArray(),
3221 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3222 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3223 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3226 if ( $user->isLoggedIn() ) {
3227 $vars['wgUserId'] = $user->getId();
3228 $vars['wgUserEditCount'] = $user->getEditCount();
3229 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3230 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3231 // Get the revision ID of the oldest new message on the user's talk
3232 // page. This can be used for constructing new message alerts on
3234 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3237 if ( $wgContLang->hasVariants() ) {
3238 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3240 // Same test as SkinTemplate
3241 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3242 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3244 foreach ( $title->getRestrictionTypes() as $type ) {
3245 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3248 if ( $title->isMainPage() ) {
3249 $vars['wgIsMainPage'] = true;
3252 if ( $this->mRedirectedFrom
) {
3253 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3256 if ( $relevantUser ) {
3257 $vars['wgRelevantUserName'] = $relevantUser->getName();
3260 // Allow extensions to add their custom variables to the mw.config map.
3261 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3262 // page-dependant but site-wide (without state).
3263 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3264 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3266 // Merge in variables from addJsConfigVars last
3267 return array_merge( $vars, $this->getJsConfigVars() );
3271 * To make it harder for someone to slip a user a fake
3272 * user-JavaScript or user-CSS preview, a random token
3273 * is associated with the login session. If it's not
3274 * passed back with the preview request, we won't render
3279 public function userCanPreview() {
3280 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3281 ||
!$this->getRequest()->wasPosted()
3282 ||
!$this->getUser()->matchEditToken(
3283 $this->getRequest()->getVal( 'wpEditToken' ) )
3287 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3291 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3295 * @return array Array in format "link name or number => 'link html'".
3297 public function getHeadLinksArray() {
3301 $config = $this->getConfig();
3303 $canonicalUrl = $this->mCanonicalUrl
;
3305 $tags['meta-generator'] = Html
::element( 'meta', array(
3306 'name' => 'generator',
3307 'content' => "MediaWiki $wgVersion",
3310 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3311 $tags['meta-referrer'] = Html
::element( 'meta', array(
3312 'name' => 'referrer',
3313 'content' => $config->get( 'ReferrerPolicy' )
3317 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3318 if ( $p !== 'index,follow' ) {
3319 // http://www.robotstxt.org/wc/meta-user.html
3320 // Only show if it's different from the default robots policy
3321 $tags['meta-robots'] = Html
::element( 'meta', array(
3327 foreach ( $this->mMetatags
as $tag ) {
3328 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3330 $tag[0] = substr( $tag[0], 5 );
3334 $tagName = "meta-{$tag[0]}";
3335 if ( isset( $tags[$tagName] ) ) {
3336 $tagName .= $tag[1];
3338 $tags[$tagName] = Html
::element( 'meta',
3341 'content' => $tag[1]
3346 foreach ( $this->mLinktags
as $tag ) {
3347 $tags[] = Html
::element( 'link', $tag );
3350 # Universal edit button
3351 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3352 $user = $this->getUser();
3353 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3354 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3355 // Original UniversalEditButton
3356 $msg = $this->msg( 'edit' )->text();
3357 $tags['universal-edit-button'] = Html
::element( 'link', array(
3358 'rel' => 'alternate',
3359 'type' => 'application/x-wiki',
3361 'href' => $this->getTitle()->getEditURL(),
3363 // Alternate edit link
3364 $tags['alternative-edit'] = Html
::element( 'link', array(
3367 'href' => $this->getTitle()->getEditURL(),
3372 # Generally the order of the favicon and apple-touch-icon links
3373 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3374 # uses whichever one appears later in the HTML source. Make sure
3375 # apple-touch-icon is specified first to avoid this.
3376 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3377 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3378 'rel' => 'apple-touch-icon',
3379 'href' => $config->get( 'AppleTouchIcon' )
3383 if ( $config->get( 'Favicon' ) !== false ) {
3384 $tags['favicon'] = Html
::element( 'link', array(
3385 'rel' => 'shortcut icon',
3386 'href' => $config->get( 'Favicon' )
3390 # OpenSearch description link
3391 $tags['opensearch'] = Html
::element( 'link', array(
3393 'type' => 'application/opensearchdescription+xml',
3394 'href' => wfScript( 'opensearch_desc' ),
3395 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3398 if ( $config->get( 'EnableAPI' ) ) {
3399 # Real Simple Discovery link, provides auto-discovery information
3400 # for the MediaWiki API (and potentially additional custom API
3401 # support such as WordPress or Twitter-compatible APIs for a
3402 # blogging extension, etc)
3403 $tags['rsd'] = Html
::element( 'link', array(
3405 'type' => 'application/rsd+xml',
3406 // Output a protocol-relative URL here if $wgServer is protocol-relative
3407 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3408 'href' => wfExpandUrl( wfAppendQuery(
3410 array( 'action' => 'rsd' ) ),
3417 if ( !$config->get( 'DisableLangConversion' ) ) {
3418 $lang = $this->getTitle()->getPageLanguage();
3419 if ( $lang->hasVariants() ) {
3420 $variants = $lang->getVariants();
3421 foreach ( $variants as $_v ) {
3422 $tags["variant-$_v"] = Html
::element( 'link', array(
3423 'rel' => 'alternate',
3424 'hreflang' => wfBCP47( $_v ),
3425 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3429 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3430 $tags["variant-x-default"] = Html
::element( 'link', array(
3431 'rel' => 'alternate',
3432 'hreflang' => 'x-default',
3433 'href' => $this->getTitle()->getLocalURL() ) );
3438 if ( $config->get( 'RightsPage' ) ) {
3439 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3442 $copyright = $copy->getLocalURL();
3446 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3447 $copyright = $config->get( 'RightsUrl' );
3451 $tags['copyright'] = Html
::element( 'link', array(
3452 'rel' => 'copyright',
3453 'href' => $copyright )
3458 if ( $config->get( 'Feed' ) ) {
3459 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3460 # Use the page name for the title. In principle, this could
3461 # lead to issues with having the same name for different feeds
3462 # corresponding to the same page, but we can't avoid that at
3465 $tags[] = $this->feedLink(
3468 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3469 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3473 # Recent changes feed should appear on every page (except recentchanges,
3474 # that would be redundant). Put it after the per-page feed to avoid
3475 # changing existing behavior. It's still available, probably via a
3476 # menu in your browser. Some sites might have a different feed they'd
3477 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3478 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3479 # If so, use it instead.
3480 $sitename = $config->get( 'Sitename' );
3481 if ( $config->get( 'OverrideSiteFeed' ) ) {
3482 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3483 // Note, this->feedLink escapes the url.
3484 $tags[] = $this->feedLink(
3487 $this->msg( "site-{$type}-feed", $sitename )->text()
3490 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3491 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3492 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3493 $tags[] = $this->feedLink(
3495 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3496 # For grep: 'site-rss-feed', 'site-atom-feed'
3497 $this->msg( "site-{$format}-feed", $sitename )->text()
3504 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3505 if ( $canonicalUrl !== false ) {
3506 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3508 $reqUrl = $this->getRequest()->getRequestURL();
3509 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3512 if ( $canonicalUrl !== false ) {
3513 $tags[] = Html
::element( 'link', array(
3514 'rel' => 'canonical',
3515 'href' => $canonicalUrl
3523 * @return string HTML tag links to be put in the header.
3524 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3525 * OutputPage::getHeadLinksArray directly.
3527 public function getHeadLinks() {
3528 wfDeprecated( __METHOD__
, '1.24' );
3529 return implode( "\n", $this->getHeadLinksArray() );
3533 * Generate a "<link rel/>" for a feed.
3535 * @param string $type Feed type
3536 * @param string $url URL to the feed
3537 * @param string $text Value of the "title" attribute
3538 * @return string HTML fragment
3540 private function feedLink( $type, $url, $text ) {
3541 return Html
::element( 'link', array(
3542 'rel' => 'alternate',
3543 'type' => "application/$type+xml",
3550 * Add a local or specified stylesheet, with the given media options.
3551 * Meant primarily for internal use...
3553 * @param string $style URL to the file
3554 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3555 * @param string $condition For IE conditional comments, specifying an IE version
3556 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3558 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3560 // Even though we expect the media type to be lowercase, but here we
3561 // force it to lowercase to be safe.
3563 $options['media'] = $media;
3566 $options['condition'] = $condition;
3569 $options['dir'] = $dir;
3571 $this->styles
[$style] = $options;
3575 * Adds inline CSS styles
3576 * @param mixed $style_css Inline CSS
3577 * @param string $flip Set to 'flip' to flip the CSS if needed
3579 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3580 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3581 # If wanted, and the interface is right-to-left, flip the CSS
3582 $style_css = CSSJanus
::transform( $style_css, true, false );
3584 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3588 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3589 * These will be applied to various media & IE conditionals.
3593 public function buildCssLinks() {
3596 $this->getSkin()->setupSkinUserCss( $this );
3598 // Add ResourceLoader styles
3599 // Split the styles into these groups
3604 'private' => array(),
3605 'noscript' => array()
3608 $otherTags = ''; // Tags to append after the normal <link> tags
3609 $resourceLoader = $this->getResourceLoader();
3611 $moduleStyles = $this->getModuleStyles();
3613 // Per-site custom styles
3614 $moduleStyles[] = 'site';
3615 $moduleStyles[] = 'noscript';
3616 $moduleStyles[] = 'user.groups';
3618 // Per-user custom styles
3619 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3620 && $this->userCanPreview()
3622 // We're on a preview of a CSS subpage
3623 // Exclude this page from the user module in case it's in there (bug 26283)
3624 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3625 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3627 $otherTags .= $link['html'];
3629 // Load the previewed CSS
3630 // If needed, Janus it first. This is user-supplied CSS, so it's
3631 // assumed to be right for the content language directionality.
3632 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3633 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3634 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3636 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3638 // Load the user styles normally
3639 $moduleStyles[] = 'user';
3642 // Per-user preference styles
3643 $moduleStyles[] = 'user.cssprefs';
3645 foreach ( $moduleStyles as $name ) {
3646 $module = $resourceLoader->getModule( $name );
3650 $group = $module->getGroup();
3651 // Modules in groups different than the ones listed on top (see $styles assignment)
3652 // will be placed in the "other" group
3653 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3656 // We want site, private and user styles to override dynamically added
3657 // styles from modules, but we want dynamically added styles to override
3658 // statically added styles from other modules. So the order has to be
3659 // other, dynamic, site, private, user. Add statically added styles for
3661 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3662 // Add normal styles added through addStyle()/addInlineStyle() here
3663 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3664 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3665 // We use a <meta> tag with a made-up name for this because that's valid HTML
3666 $links[] = Html
::element(
3668 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3671 // Add site, private and user styles
3672 // 'private' at present only contains user.options, so put that before 'user'
3673 // Any future private modules will likely have a similar user-specific character
3674 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3675 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3676 ResourceLoaderModule
::TYPE_STYLES
3680 // Add stuff in $otherTags (previewed user CSS if applicable)
3681 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3687 public function buildCssLinksArray() {
3690 // Add any extension CSS
3691 foreach ( $this->mExtStyles
as $url ) {
3692 $this->addStyle( $url );
3694 $this->mExtStyles
= array();
3696 foreach ( $this->styles
as $file => $options ) {
3697 $link = $this->styleLink( $file, $options );
3699 $links[$file] = $link;
3706 * Generate \<link\> tags for stylesheets
3708 * @param string $style URL to the file
3709 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3710 * @return string HTML fragment
3712 protected function styleLink( $style, array $options ) {
3713 if ( isset( $options['dir'] ) ) {
3714 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3719 if ( isset( $options['media'] ) ) {
3720 $media = self
::transformCssMedia( $options['media'] );
3721 if ( is_null( $media ) ) {
3728 if ( substr( $style, 0, 1 ) == '/' ||
3729 substr( $style, 0, 5 ) == 'http:' ||
3730 substr( $style, 0, 6 ) == 'https:' ) {
3733 $config = $this->getConfig();
3734 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3737 $link = Html
::linkedStyle( $url, $media );
3739 if ( isset( $options['condition'] ) ) {
3740 $condition = htmlspecialchars( $options['condition'] );
3741 $link = "<!--[if $condition]>$link<![endif]-->";
3747 * Transform "media" attribute based on request parameters
3749 * @param string $media Current value of the "media" attribute
3750 * @return string Modified value of the "media" attribute, or null to skip
3753 public static function transformCssMedia( $media ) {
3756 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3757 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3759 // Switch in on-screen display for media testing
3761 'printable' => 'print',
3762 'handheld' => 'handheld',
3764 foreach ( $switches as $switch => $targetMedia ) {
3765 if ( $wgRequest->getBool( $switch ) ) {
3766 if ( $media == $targetMedia ) {
3768 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3769 // This regex will not attempt to understand a comma-separated media_query_list
3771 // Example supported values for $media:
3772 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3773 // Example NOT supported value for $media:
3774 // '3d-glasses, screen, print and resolution > 90dpi'
3776 // If it's a print request, we never want any kind of screen stylesheets
3777 // If it's a handheld request (currently the only other choice with a switch),
3778 // we don't want simple 'screen' but we might want screen queries that
3779 // have a max-width or something, so we'll pass all others on and let the
3780 // client do the query.
3781 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3792 * Add a wikitext-formatted message to the output.
3793 * This is equivalent to:
3795 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3797 public function addWikiMsg( /*...*/ ) {
3798 $args = func_get_args();
3799 $name = array_shift( $args );
3800 $this->addWikiMsgArray( $name, $args );
3804 * Add a wikitext-formatted message to the output.
3805 * Like addWikiMsg() except the parameters are taken as an array
3806 * instead of a variable argument list.
3808 * @param string $name
3809 * @param array $args
3811 public function addWikiMsgArray( $name, $args ) {
3812 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3816 * This function takes a number of message/argument specifications, wraps them in
3817 * some overall structure, and then parses the result and adds it to the output.
3819 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3820 * and so on. The subsequent arguments may be either
3821 * 1) strings, in which case they are message names, or
3822 * 2) arrays, in which case, within each array, the first element is the message
3823 * name, and subsequent elements are the parameters to that message.
3825 * Don't use this for messages that are not in the user's interface language.
3829 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3833 * $wgOut->addWikiText( "<div class='error'>\n"
3834 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3836 * The newline after the opening div is needed in some wikitext. See bug 19226.
3838 * @param string $wrap
3840 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3841 $msgSpecs = func_get_args();
3842 array_shift( $msgSpecs );
3843 $msgSpecs = array_values( $msgSpecs );
3845 foreach ( $msgSpecs as $n => $spec ) {
3846 if ( is_array( $spec ) ) {
3848 $name = array_shift( $args );
3849 if ( isset( $args['options'] ) ) {
3850 unset( $args['options'] );
3852 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3860 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3862 $this->addWikiText( $s );
3866 * Include jQuery core. Use this to avoid loading it multiple times
3867 * before we get a usable script loader.
3869 * @param array $modules List of jQuery modules which should be loaded
3870 * @return array The list of modules which were not loaded.
3872 * @deprecated since 1.17
3874 public function includeJQuery( array $modules = array() ) {
3879 * Enables/disables TOC, doesn't override __NOTOC__
3883 public function enableTOC( $flag = true ) {
3884 $this->mEnableTOC
= $flag;
3891 public function isTOCEnabled() {
3892 return $this->mEnableTOC
;
3896 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3900 public function enableSectionEditLinks( $flag = true ) {
3901 $this->mEnableSectionEditLinks
= $flag;
3908 public function sectionEditLinksEnabled() {
3909 return $this->mEnableSectionEditLinks
;
3913 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3914 * MediaWiki and this OutputPage instance.
3918 public function enableOOUI() {
3919 OOUI\Theme
::setSingleton( new OOUI\
MediaWikiTheme() );
3920 OOUI\Element
::setDefaultDir( $this->getLanguage()->getDir() );
3921 $this->addModuleStyles( 'oojs-ui.styles' );