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
23 use MediaWiki\Logger\LoggerFactory
;
24 use WrappedString\WrappedString
;
27 * This class should be covered by a general architecture document which does
28 * not exist as of January 2011. This is one of the Core classes and should
29 * be read at least once by any new developers.
31 * This class is used to prepare the final rendering. A skin is then
32 * applied to the output parameters (links, javascript, html, categories ...).
34 * @todo FIXME: Another class handles sending the whole page to the client.
36 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
41 class OutputPage
extends ContextSource
{
42 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
43 protected $mMetatags = array();
46 protected $mLinktags = array();
49 protected $mCanonicalUrl = false;
52 * @var array Additional stylesheets. Looks like this is for extensions.
53 * Might be replaced by resource loader.
55 protected $mExtStyles = array();
58 * @var string Should be private - has getter and setter. Contains
60 public $mPagetitle = '';
63 * @var string Contains all of the "<body>" content. Should be private we
64 * got set/get accessors and the append() method.
66 public $mBodytext = '';
69 * Holds the debug lines that will be output as comments in page source if
70 * $wgDebugComments is enabled. See also $wgShowDebug.
71 * @deprecated since 1.20; use MWDebug class instead.
73 public $mDebugtext = '';
75 /** @var string Stores contents of "<title>" tag */
76 private $mHTMLtitle = '';
79 * @var bool Is the displayed content related to the source of the
80 * corresponding wiki article.
82 private $mIsarticle = false;
84 /** @var bool Stores "article flag" toggle. */
85 private $mIsArticleRelated = true;
88 * @var bool We have to set isPrintable(). Some pages should
89 * never be printed (ex: redirections).
91 private $mPrintable = false;
94 * @var array Contains the page subtitle. Special pages usually have some
95 * links here. Don't confuse with site subtitle added by skins.
97 private $mSubtitle = array();
100 public $mRedirect = '';
103 protected $mStatusCode;
106 * @var string Variable mLastModified and mEtag are used for sending cache control.
107 * The whole caching system should probably be moved into its own class.
109 protected $mLastModified = '';
112 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
113 * as a unique identifier for the content. It is later used by the client
114 * to compare its cached version with the server version. Client sends
115 * headers If-Match and If-None-Match containing its locally cached ETAG value.
117 * To get more information, you will have to look at HTTP/1.1 protocol which
118 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
120 private $mETag = false;
123 protected $mCategoryLinks = array();
126 protected $mCategories = array();
129 protected $mIndicators = array();
131 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
132 private $mLanguageLinks = array();
135 * Used for JavaScript (pre resource loader)
136 * @todo We should split JS / CSS.
137 * mScripts content is inserted as is in "<head>" by Skin. This might
138 * contain either a link to a stylesheet or inline CSS.
140 private $mScripts = '';
142 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
143 protected $mInlineStyles = '';
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();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
197 protected $mContainsNewMagic = 0;
200 * lazy initialised, use parserOptions()
203 protected $mParserOptions = null;
206 * Handles the Atom / RSS links.
207 * We probably only support Atom in 2011.
208 * @see $wgAdvertisedFeedTypes
210 private $mFeedLinks = array();
212 // Gwicke work on squid caching? Roughly from 2003.
213 protected $mEnableClientCache = true;
215 /** @var bool Flag if output should only contain the body of the article. */
216 private $mArticleBodyOnly = false;
219 protected $mNewSectionLink = false;
222 protected $mHideNewSectionLink = false;
225 * @var bool Comes from the parser. This was probably made to load CSS/JS
226 * only if we had "<gallery>". Used directly in CategoryPage.php.
227 * Looks like resource loader can replace this.
229 public $mNoGallery = false;
232 private $mPageTitleActionText = '';
235 private $mParseWarnings = array();
237 /** @var int Cache stuff. Looks like mEnableClientCache */
238 protected $mSquidMaxage = 0;
241 * @var bool Controls if anti-clickjacking / frame-breaking headers will
242 * be sent. This should be done for pages where edit actions are possible.
243 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
245 protected $mPreventClickjacking = true;
247 /** @var int To include the variable {{REVISIONID}} */
248 private $mRevisionId = null;
251 private $mRevisionTimestamp = null;
254 protected $mFileVersion = null;
257 * @var array An array of stylesheet filenames (relative from skins path),
258 * with options for CSS media, IE conditions, and RTL/LTR direction.
259 * For internal use; add settings in the skin via $this->addStyle()
261 * Style again! This seems like a code duplication since we already have
262 * mStyles. This is what makes Open Source amazing.
264 protected $styles = array();
267 * Whether jQuery is already handled.
269 protected $mJQueryDone = false;
271 private $mIndexPolicy = 'index';
272 private $mFollowPolicy = 'follow';
273 private $mVaryHeader = array(
274 'Accept-Encoding' => array( 'list-contains=gzip' ),
278 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
283 private $mRedirectedFrom = null;
286 * Additional key => value data
288 private $mProperties = array();
291 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
293 private $mTarget = null;
296 * @var bool Whether parser output should contain table of contents
298 private $mEnableTOC = true;
301 * @var bool Whether parser output should contain section edit links
303 private $mEnableSectionEditLinks = true;
306 * @var string|null The URL to send in a <link> element with rel=copyright
308 private $copyrightUrl;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
314 * @param IContextSource|null $context
316 function __construct( IContextSource
$context = null ) {
317 if ( $context === null ) {
318 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
319 wfDeprecated( __METHOD__
, '1.18' );
321 $this->setContext( $context );
326 * Redirect to $url rather than displaying the normal page
328 * @param string $url URL
329 * @param string $responsecode HTTP status code
331 public function redirect( $url, $responsecode = '302' ) {
332 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
333 $this->mRedirect
= str_replace( "\n", '', $url );
334 $this->mRedirectCode
= $responsecode;
338 * Get the URL to redirect to, or an empty string if not redirect URL set
342 public function getRedirect() {
343 return $this->mRedirect
;
347 * Set the copyright URL to send with the output.
348 * Empty string to omit, null to reset.
352 * @param string|null $url
354 public function setCopyrightUrl( $url ) {
355 $this->copyrightUrl
= $url;
359 * Set the HTTP status code to send with the output.
361 * @param int $statusCode
363 public function setStatusCode( $statusCode ) {
364 $this->mStatusCode
= $statusCode;
368 * Add a new "<meta>" tag
369 * To add an http-equiv meta tag, precede the name with "http:"
371 * @param string $name Tag name
372 * @param string $val Tag value
374 function addMeta( $name, $val ) {
375 array_push( $this->mMetatags
, array( $name, $val ) );
379 * Returns the current <meta> tags
384 public function getMetaTags() {
385 return $this->mMetatags
;
389 * Add a new \<link\> tag to the page header.
391 * Note: use setCanonicalUrl() for rel=canonical.
393 * @param array $linkarr Associative array of attributes.
395 function addLink( array $linkarr ) {
396 array_push( $this->mLinktags
, $linkarr );
400 * Returns the current <link> tags
405 public function getLinkTags() {
406 return $this->mLinktags
;
410 * Add a new \<link\> with "rel" attribute set to "meta"
412 * @param array $linkarr Associative array mapping attribute names to their
413 * values, both keys and values will be escaped, and the
414 * "rel" attribute will be automatically added
416 function addMetadataLink( array $linkarr ) {
417 $linkarr['rel'] = $this->getMetadataAttribute();
418 $this->addLink( $linkarr );
422 * Set the URL to be used for the <link rel=canonical>. This should be used
423 * in preference to addLink(), to avoid duplicate link tags.
426 function setCanonicalUrl( $url ) {
427 $this->mCanonicalUrl
= $url;
431 * Returns the URL to be used for the <link rel=canonical> if
435 * @return bool|string
437 public function getCanonicalUrl() {
438 return $this->mCanonicalUrl
;
442 * Get the value of the "rel" attribute for metadata links
446 public function getMetadataAttribute() {
447 # note: buggy CC software only reads first "meta" link
448 static $haveMeta = false;
450 return 'alternate meta';
458 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts
.= $script . "\n";
467 * Register and add a stylesheet from an extension directory.
469 * @param string $url Path to sheet. Provide either a full url (beginning
470 * with 'http', etc) or a relative path from the document root
471 * (beginning with '/'). Otherwise it behaves identically to
472 * addStyle() and draws from the /skins folder.
474 public function addExtensionStyle( $url ) {
475 array_push( $this->mExtStyles
, $url );
479 * Get all styles added by extensions
483 function getExtStyle() {
484 return $this->mExtStyles
;
488 * Add a JavaScript file out of skins/common, or a given relative path.
490 * @param string $file Filename in skins/common or complete on-server path
492 * @param string $version Style version of the file. Defaults to $wgStyleVersion
494 public function addScriptFile( $file, $version = null ) {
495 // See if $file parameter is an absolute URL or begins with a slash
496 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
499 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
501 if ( is_null( $version ) ) {
502 $version = $this->getConfig()->get( 'StyleVersion' );
504 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
508 * Add a self-contained script tag with the given contents
510 * @param string $script JavaScript text, no "<script>" tags
512 public function addInlineScript( $script ) {
513 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
517 * Get all registered JS and CSS tags for the header.
520 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
522 function getScript() {
523 wfDeprecated( __METHOD__
, '1.24' );
524 return $this->mScripts
. $this->getHeadItems();
528 * Filter an array of modules to remove insufficiently trustworthy members, and modules
529 * which are no longer registered (eg a page is cached before an extension is disabled)
530 * @param array $modules
531 * @param string|null $position If not null, only return modules with this position
532 * @param string $type
535 protected function filterModules( array $modules, $position = null,
536 $type = ResourceLoaderModule
::TYPE_COMBINED
538 $resourceLoader = $this->getResourceLoader();
539 $filteredModules = array();
540 foreach ( $modules as $val ) {
541 $module = $resourceLoader->getModule( $val );
542 if ( $module instanceof ResourceLoaderModule
543 && $module->getOrigin() <= $this->getAllowedModules( $type )
544 && ( is_null( $position ) ||
$module->getPosition() == $position )
545 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
547 $filteredModules[] = $val;
550 return $filteredModules;
554 * Get the list of modules to include on this page
556 * @param bool $filter Whether to filter out insufficiently trustworthy modules
557 * @param string|null $position If not null, only return modules with this position
558 * @param string $param
559 * @return array Array of module names
561 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
562 $modules = array_values( array_unique( $this->$param ) );
564 ?
$this->filterModules( $modules, $position )
569 * Add one or more modules recognized by the resource loader. Modules added
570 * through this function will be loaded by the resource loader when the
573 * @param string|array $modules Module name (string) or array of module names
575 public function addModules( $modules ) {
576 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
580 * Get the list of module JS to include on this page
582 * @param bool $filter
583 * @param string|null $position
585 * @return array Array of module names
587 public function getModuleScripts( $filter = false, $position = null ) {
588 return $this->getModules( $filter, $position, 'mModuleScripts' );
592 * Add only JS of one or more modules recognized by the resource loader. Module
593 * scripts added through this function will be loaded by the resource loader when
596 * @param string|array $modules Module name (string) or array of module names
598 public function addModuleScripts( $modules ) {
599 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
603 * Get the list of module CSS to include on this page
605 * @param bool $filter
606 * @param string|null $position
608 * @return array Array of module names
610 public function getModuleStyles( $filter = false, $position = null ) {
612 $resourceLoader = $this->getResourceLoader();
614 foreach ( $this->mModuleStyles
as $val ) {
615 $module = $resourceLoader->getModule( $val );
617 if ( $module instanceof ResourceLoaderModule
&& $module->isPositionDefault() ) {
618 $warning = __METHOD__
. ': style module should define its position explicitly: ' .
619 $val . ' ' . get_class( $module );
620 wfDebugLog( 'resourceloader', $warning );
621 wfLogWarning( $warning );
625 return $this->getModules( $filter, $position, 'mModuleStyles' );
629 * Add only CSS of one or more modules recognized by the resource loader.
631 * Module styles added through this function will be added using standard link CSS
632 * tags, rather than as a combined Javascript and CSS package. Thus, they will
633 * load when JavaScript is disabled (unless CSS also happens to be disabled).
635 * @param string|array $modules Module name (string) or array of module names
637 public function addModuleStyles( $modules ) {
638 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
642 * Get the list of module messages to include on this page
644 * @deprecated since 1.26 Obsolete
645 * @param bool $filter
646 * @param string|null $position
647 * @return array Array of module names
649 public function getModuleMessages( $filter = false, $position = null ) {
650 wfDeprecated( __METHOD__
, '1.26' );
655 * Load messages of one or more ResourceLoader modules.
657 * @deprecated since 1.26 Use addModules() instead
658 * @param string|array $modules Module name (string) or array of module names
660 public function addModuleMessages( $modules ) {
661 wfDeprecated( __METHOD__
, '1.26' );
665 * @return null|string ResourceLoader target
667 public function getTarget() {
668 return $this->mTarget
;
672 * Sets ResourceLoader target for load.php links. If null, will be omitted
674 * @param string|null $target
676 public function setTarget( $target ) {
677 $this->mTarget
= $target;
681 * Get an array of head items
685 function getHeadItemsArray() {
686 return $this->mHeadItems
;
690 * Get all header items in a string
693 * @deprecated since 1.24 Use OutputPage::headElement or
694 * if absolutely necessary use OutputPage::getHeadItemsArray
696 function getHeadItems() {
697 wfDeprecated( __METHOD__
, '1.24' );
699 foreach ( $this->mHeadItems
as $item ) {
706 * Add or replace an header item to the output
708 * @param string $name Item name
709 * @param string $value Raw HTML
711 public function addHeadItem( $name, $value ) {
712 $this->mHeadItems
[$name] = $value;
716 * Check if the header item $name is already set
718 * @param string $name Item name
721 public function hasHeadItem( $name ) {
722 return isset( $this->mHeadItems
[$name] );
726 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
728 * @param string $tag Value of "ETag" header
730 function setETag( $tag ) {
735 * Set whether the output should only contain the body of the article,
736 * without any skin, sidebar, etc.
737 * Used e.g. when calling with "action=render".
739 * @param bool $only Whether to output only the body of the article
741 public function setArticleBodyOnly( $only ) {
742 $this->mArticleBodyOnly
= $only;
746 * Return whether the output will contain only the body of the article
750 public function getArticleBodyOnly() {
751 return $this->mArticleBodyOnly
;
755 * Set an additional output property
758 * @param string $name
759 * @param mixed $value
761 public function setProperty( $name, $value ) {
762 $this->mProperties
[$name] = $value;
766 * Get an additional output property
769 * @param string $name
770 * @return mixed Property value or null if not found
772 public function getProperty( $name ) {
773 if ( isset( $this->mProperties
[$name] ) ) {
774 return $this->mProperties
[$name];
781 * checkLastModified tells the client to use the client-cached page if
782 * possible. If successful, the OutputPage is disabled so that
783 * any future call to OutputPage->output() have no effect.
785 * Side effect: sets mLastModified for Last-Modified header
787 * @param string $timestamp
789 * @return bool True if cache-ok headers was sent.
791 public function checkLastModified( $timestamp ) {
792 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
793 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
796 $config = $this->getConfig();
797 if ( !$config->get( 'CachePages' ) ) {
798 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
802 $timestamp = wfTimestamp( TS_MW
, $timestamp );
803 $modifiedTimes = array(
804 'page' => $timestamp,
805 'user' => $this->getUser()->getTouched(),
806 'epoch' => $config->get( 'CacheEpoch' )
808 if ( $config->get( 'UseSquid' ) ) {
809 // bug 44570: the core page itself may not change, but resources might
810 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
812 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
814 $maxModified = max( $modifiedTimes );
815 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
817 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
818 if ( $clientHeader === false ) {
819 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
823 # IE sends sizes after the date like this:
824 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
825 # this breaks strtotime().
826 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
828 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
829 $clientHeaderTime = strtotime( $clientHeader );
830 MediaWiki\restoreWarnings
();
831 if ( !$clientHeaderTime ) {
833 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
836 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
840 foreach ( $modifiedTimes as $name => $value ) {
841 if ( $info !== '' ) {
844 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
847 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
848 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
849 wfDebug( __METHOD__
. ": effective Last-Modified: " .
850 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
851 if ( $clientHeaderTime < $maxModified ) {
852 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
857 # Give a 304 Not Modified response code and disable body output
858 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
859 ini_set( 'zlib.output_compression', 0 );
860 $this->getRequest()->response()->statusHeader( 304 );
861 $this->sendCacheControl();
864 // Don't output a compressed blob when using ob_gzhandler;
865 // it's technically against HTTP spec and seems to confuse
866 // Firefox when the response gets split over two packets.
867 wfClearOutputBuffers();
873 * Override the last modified timestamp
875 * @param string $timestamp New timestamp, in a format readable by
878 public function setLastModified( $timestamp ) {
879 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
883 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
885 * @param string $policy The literal string to output as the contents of
886 * the meta tag. Will be parsed according to the spec and output in
890 public function setRobotPolicy( $policy ) {
891 $policy = Article
::formatRobotPolicy( $policy );
893 if ( isset( $policy['index'] ) ) {
894 $this->setIndexPolicy( $policy['index'] );
896 if ( isset( $policy['follow'] ) ) {
897 $this->setFollowPolicy( $policy['follow'] );
902 * Set the index policy for the page, but leave the follow policy un-
905 * @param string $policy Either 'index' or 'noindex'.
908 public function setIndexPolicy( $policy ) {
909 $policy = trim( $policy );
910 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
911 $this->mIndexPolicy
= $policy;
916 * Set the follow policy for the page, but leave the index policy un-
919 * @param string $policy Either 'follow' or 'nofollow'.
922 public function setFollowPolicy( $policy ) {
923 $policy = trim( $policy );
924 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
925 $this->mFollowPolicy
= $policy;
930 * Set the new value of the "action text", this will be added to the
931 * "HTML title", separated from it with " - ".
933 * @param string $text New value of the "action text"
935 public function setPageTitleActionText( $text ) {
936 $this->mPageTitleActionText
= $text;
940 * Get the value of the "action text"
944 public function getPageTitleActionText() {
945 return $this->mPageTitleActionText
;
949 * "HTML title" means the contents of "<title>".
950 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
952 * @param string|Message $name
954 public function setHTMLTitle( $name ) {
955 if ( $name instanceof Message
) {
956 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
958 $this->mHTMLtitle
= $name;
963 * Return the "HTML title", i.e. the content of the "<title>" tag.
967 public function getHTMLTitle() {
968 return $this->mHTMLtitle
;
972 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
976 public function setRedirectedFrom( $t ) {
977 $this->mRedirectedFrom
= $t;
981 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
982 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
983 * but not bad tags like \<script\>. This function automatically sets
984 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
985 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
986 * good tags like \<i\> will be dropped entirely.
988 * @param string|Message $name
990 public function setPageTitle( $name ) {
991 if ( $name instanceof Message
) {
992 $name = $name->setContext( $this->getContext() )->text();
995 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
996 # but leave "<i>foobar</i>" alone
997 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
998 $this->mPagetitle
= $nameWithTags;
1000 # change "<i>foo&bar</i>" to "foo&bar"
1001 $this->setHTMLTitle(
1002 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
1003 ->inContentLanguage()
1008 * Return the "page title", i.e. the content of the \<h1\> tag.
1012 public function getPageTitle() {
1013 return $this->mPagetitle
;
1017 * Set the Title object to use
1021 public function setTitle( Title
$t ) {
1022 $this->getContext()->setTitle( $t );
1026 * Replace the subtitle with $str
1028 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1030 public function setSubtitle( $str ) {
1031 $this->clearSubtitle();
1032 $this->addSubtitle( $str );
1036 * Add $str to the subtitle
1038 * @deprecated since 1.19; use addSubtitle() instead
1039 * @param string|Message $str String or Message to add to the subtitle
1041 public function appendSubtitle( $str ) {
1042 $this->addSubtitle( $str );
1046 * Add $str to the subtitle
1048 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1050 public function addSubtitle( $str ) {
1051 if ( $str instanceof Message
) {
1052 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1054 $this->mSubtitle
[] = $str;
1059 * Build message object for a subtitle containing a backlink to a page
1061 * @param Title $title Title to link to
1062 * @param array $query Array of additional parameters to include in the link
1066 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1067 if ( $title->isRedirect() ) {
1068 $query['redirect'] = 'no';
1070 return wfMessage( 'backlinksubtitle' )
1071 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1075 * Add a subtitle containing a backlink to a page
1077 * @param Title $title Title to link to
1078 * @param array $query Array of additional parameters to include in the link
1080 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1081 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1085 * Clear the subtitles
1087 public function clearSubtitle() {
1088 $this->mSubtitle
= array();
1096 public function getSubtitle() {
1097 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1101 * Set the page as printable, i.e. it'll be displayed with all
1102 * print styles included
1104 public function setPrintable() {
1105 $this->mPrintable
= true;
1109 * Return whether the page is "printable"
1113 public function isPrintable() {
1114 return $this->mPrintable
;
1118 * Disable output completely, i.e. calling output() will have no effect
1120 public function disable() {
1121 $this->mDoNothing
= true;
1125 * Return whether the output will be completely disabled
1129 public function isDisabled() {
1130 return $this->mDoNothing
;
1134 * Show an "add new section" link?
1138 public function showNewSectionLink() {
1139 return $this->mNewSectionLink
;
1143 * Forcibly hide the new section link?
1147 public function forceHideNewSectionLink() {
1148 return $this->mHideNewSectionLink
;
1152 * Add or remove feed links in the page header
1153 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1154 * for the new version
1155 * @see addFeedLink()
1157 * @param bool $show True: add default feeds, false: remove all feeds
1159 public function setSyndicated( $show = true ) {
1161 $this->setFeedAppendQuery( false );
1163 $this->mFeedLinks
= array();
1168 * Add default feeds to the page header
1169 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1170 * for the new version
1171 * @see addFeedLink()
1173 * @param string $val Query to append to feed links or false to output
1176 public function setFeedAppendQuery( $val ) {
1177 $this->mFeedLinks
= array();
1179 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1180 $query = "feed=$type";
1181 if ( is_string( $val ) ) {
1182 $query .= '&' . $val;
1184 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1189 * Add a feed link to the page header
1191 * @param string $format Feed type, should be a key of $wgFeedClasses
1192 * @param string $href URL
1194 public function addFeedLink( $format, $href ) {
1195 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1196 $this->mFeedLinks
[$format] = $href;
1201 * Should we output feed links for this page?
1204 public function isSyndicated() {
1205 return count( $this->mFeedLinks
) > 0;
1209 * Return URLs for each supported syndication format for this page.
1210 * @return array Associating format keys with URLs
1212 public function getSyndicationLinks() {
1213 return $this->mFeedLinks
;
1217 * Will currently always return null
1221 public function getFeedAppendQuery() {
1222 return $this->mFeedLinksAppendQuery
;
1226 * Set whether the displayed content is related to the source of the
1227 * corresponding article on the wiki
1228 * Setting true will cause the change "article related" toggle to true
1232 public function setArticleFlag( $v ) {
1233 $this->mIsarticle
= $v;
1235 $this->mIsArticleRelated
= $v;
1240 * Return whether the content displayed page is related to the source of
1241 * the corresponding article on the wiki
1245 public function isArticle() {
1246 return $this->mIsarticle
;
1250 * Set whether this page is related an article on the wiki
1251 * Setting false will cause the change of "article flag" toggle to false
1255 public function setArticleRelated( $v ) {
1256 $this->mIsArticleRelated
= $v;
1258 $this->mIsarticle
= false;
1263 * Return whether this page is related an article on the wiki
1267 public function isArticleRelated() {
1268 return $this->mIsArticleRelated
;
1272 * Add new language links
1274 * @param array $newLinkArray Associative array mapping language code to the page
1277 public function addLanguageLinks( array $newLinkArray ) {
1278 $this->mLanguageLinks +
= $newLinkArray;
1282 * Reset the language links and add new language links
1284 * @param array $newLinkArray Associative array mapping language code to the page
1287 public function setLanguageLinks( array $newLinkArray ) {
1288 $this->mLanguageLinks
= $newLinkArray;
1292 * Get the list of language links
1294 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1296 public function getLanguageLinks() {
1297 return $this->mLanguageLinks
;
1301 * Add an array of categories, with names in the keys
1303 * @param array $categories Mapping category name => sort key
1305 public function addCategoryLinks( array $categories ) {
1308 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1312 # Add the links to a LinkBatch
1313 $arr = array( NS_CATEGORY
=> $categories );
1314 $lb = new LinkBatch
;
1315 $lb->setArray( $arr );
1317 # Fetch existence plus the hiddencat property
1318 $dbr = wfGetDB( DB_SLAVE
);
1319 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1320 'page_is_redirect', 'page_latest', 'pp_value' );
1322 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1323 $fields[] = 'page_content_model';
1326 $res = $dbr->select( array( 'page', 'page_props' ),
1328 $lb->constructSet( 'page', $dbr ),
1331 array( 'page_props' => array( 'LEFT JOIN', array(
1332 'pp_propname' => 'hiddencat',
1337 # Add the results to the link cache
1338 $lb->addResultToCache( LinkCache
::singleton(), $res );
1340 # Set all the values to 'normal'.
1341 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1343 # Mark hidden categories
1344 foreach ( $res as $row ) {
1345 if ( isset( $row->pp_value
) ) {
1346 $categories[$row->page_title
] = 'hidden';
1350 # Add the remaining categories to the skin
1352 'OutputPageMakeCategoryLinks',
1353 array( &$this, $categories, &$this->mCategoryLinks
) )
1355 foreach ( $categories as $category => $type ) {
1356 $origcategory = $category;
1357 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1361 $wgContLang->findVariantLink( $category, $title, true );
1362 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1365 $text = $wgContLang->convertHtml( $title->getText() );
1366 $this->mCategories
[] = $title->getText();
1367 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1373 * Reset the category links (but not the category list) and add $categories
1375 * @param array $categories Mapping category name => sort key
1377 public function setCategoryLinks( array $categories ) {
1378 $this->mCategoryLinks
= array();
1379 $this->addCategoryLinks( $categories );
1383 * Get the list of category links, in a 2-D array with the following format:
1384 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1385 * hidden categories) and $link a HTML fragment with a link to the category
1390 public function getCategoryLinks() {
1391 return $this->mCategoryLinks
;
1395 * Get the list of category names this page belongs to
1397 * @return array Array of strings
1399 public function getCategories() {
1400 return $this->mCategories
;
1404 * Add an array of indicators, with their identifiers as array
1405 * keys and HTML contents as values.
1407 * In case of duplicate keys, existing values are overwritten.
1409 * @param array $indicators
1412 public function setIndicators( array $indicators ) {
1413 $this->mIndicators
= $indicators +
$this->mIndicators
;
1414 // Keep ordered by key
1415 ksort( $this->mIndicators
);
1419 * Get the indicators associated with this page.
1421 * The array will be internally ordered by item keys.
1423 * @return array Keys: identifiers, values: HTML contents
1426 public function getIndicators() {
1427 return $this->mIndicators
;
1431 * Adds help link with an icon via page indicators.
1432 * Link target can be overridden by a local message containing a wikilink:
1433 * the message key is: lowercase action or special page name + '-helppage'.
1434 * @param string $to Target MediaWiki.org page title or encoded URL.
1435 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1438 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1439 $this->addModuleStyles( 'mediawiki.helplink' );
1440 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1442 if ( $overrideBaseUrl ) {
1445 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1446 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1449 $link = Html
::rawElement(
1453 'target' => '_blank',
1454 'class' => 'mw-helplink',
1459 $this->setIndicators( array( 'mw-helplink' => $link ) );
1463 * Do not allow scripts which can be modified by wiki users to load on this page;
1464 * only allow scripts bundled with, or generated by, the software.
1465 * Site-wide styles are controlled by a config setting, since they can be
1466 * used to create a custom skin/theme, but not user-specific ones.
1468 * @todo this should be given a more accurate name
1470 public function disallowUserJs() {
1471 $this->reduceAllowedModules(
1472 ResourceLoaderModule
::TYPE_SCRIPTS
,
1473 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1476 // Site-wide styles are controlled by a config setting, see bug 71621
1477 // for background on why. User styles are never allowed.
1478 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1479 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1481 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1483 $this->reduceAllowedModules(
1484 ResourceLoaderModule
::TYPE_STYLES
,
1490 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1491 * @see ResourceLoaderModule::$origin
1492 * @param string $type ResourceLoaderModule TYPE_ constant
1493 * @return int ResourceLoaderModule ORIGIN_ class constant
1495 public function getAllowedModules( $type ) {
1496 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1497 return min( array_values( $this->mAllowedModules
) );
1499 return isset( $this->mAllowedModules
[$type] )
1500 ?
$this->mAllowedModules
[$type]
1501 : ResourceLoaderModule
::ORIGIN_ALL
;
1506 * Set the highest level of CSS/JS untrustworthiness allowed
1508 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1509 * Use reduceAllowedModules() instead
1510 * @param string $type ResourceLoaderModule TYPE_ constant
1511 * @param int $level ResourceLoaderModule class constant
1513 public function setAllowedModules( $type, $level ) {
1514 wfDeprecated( __METHOD__
, '1.24' );
1515 $this->reduceAllowedModules( $type, $level );
1519 * Limit the highest level of CSS/JS untrustworthiness allowed.
1521 * If passed the same or a higher level than the current level of untrustworthiness set, the
1522 * level will remain unchanged.
1524 * @param string $type
1525 * @param int $level ResourceLoaderModule class constant
1527 public function reduceAllowedModules( $type, $level ) {
1528 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1532 * Prepend $text to the body HTML
1534 * @param string $text HTML
1536 public function prependHTML( $text ) {
1537 $this->mBodytext
= $text . $this->mBodytext
;
1541 * Append $text to the body HTML
1543 * @param string $text HTML
1545 public function addHTML( $text ) {
1546 $this->mBodytext
.= $text;
1550 * Shortcut for adding an Html::element via addHTML.
1554 * @param string $element
1555 * @param array $attribs
1556 * @param string $contents
1558 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1559 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1563 * Clear the body HTML
1565 public function clearHTML() {
1566 $this->mBodytext
= '';
1572 * @return string HTML
1574 public function getHTML() {
1575 return $this->mBodytext
;
1579 * Get/set the ParserOptions object to use for wikitext parsing
1581 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1582 * current ParserOption object
1583 * @return ParserOptions
1585 public function parserOptions( $options = null ) {
1586 if ( !$this->mParserOptions
) {
1587 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1588 $this->mParserOptions
->setEditSection( false );
1590 return wfSetVar( $this->mParserOptions
, $options );
1594 * Set the revision ID which will be seen by the wiki text parser
1595 * for things such as embedded {{REVISIONID}} variable use.
1597 * @param int|null $revid An positive integer, or null
1598 * @return mixed Previous value
1600 public function setRevisionId( $revid ) {
1601 $val = is_null( $revid ) ?
null : intval( $revid );
1602 return wfSetVar( $this->mRevisionId
, $val );
1606 * Get the displayed revision ID
1610 public function getRevisionId() {
1611 return $this->mRevisionId
;
1615 * Set the timestamp of the revision which will be displayed. This is used
1616 * to avoid a extra DB call in Skin::lastModified().
1618 * @param string|null $timestamp
1619 * @return mixed Previous value
1621 public function setRevisionTimestamp( $timestamp ) {
1622 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1626 * Get the timestamp of displayed revision.
1627 * This will be null if not filled by setRevisionTimestamp().
1629 * @return string|null
1631 public function getRevisionTimestamp() {
1632 return $this->mRevisionTimestamp
;
1636 * Set the displayed file version
1638 * @param File|bool $file
1639 * @return mixed Previous value
1641 public function setFileVersion( $file ) {
1643 if ( $file instanceof File
&& $file->exists() ) {
1644 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1646 return wfSetVar( $this->mFileVersion
, $val, true );
1650 * Get the displayed file version
1652 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1654 public function getFileVersion() {
1655 return $this->mFileVersion
;
1659 * Get the templates used on this page
1661 * @return array (namespace => dbKey => revId)
1664 public function getTemplateIds() {
1665 return $this->mTemplateIds
;
1669 * Get the files used on this page
1671 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1674 public function getFileSearchOptions() {
1675 return $this->mImageTimeKeys
;
1679 * Convert wikitext to HTML and add it to the buffer
1680 * Default assumes that the current page title will be used.
1682 * @param string $text
1683 * @param bool $linestart Is this the start of a line?
1684 * @param bool $interface Is this text in the user interface language?
1685 * @throws MWException
1687 public function addWikiText( $text, $linestart = true, $interface = true ) {
1688 $title = $this->getTitle(); // Work around E_STRICT
1690 throw new MWException( 'Title is null' );
1692 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1696 * Add wikitext with a custom Title object
1698 * @param string $text Wikitext
1699 * @param Title $title
1700 * @param bool $linestart Is this the start of a line?
1702 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1703 $this->addWikiTextTitle( $text, $title, $linestart );
1707 * Add wikitext with a custom Title object and tidy enabled.
1709 * @param string $text Wikitext
1710 * @param Title $title
1711 * @param bool $linestart Is this the start of a line?
1713 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1714 $this->addWikiTextTitle( $text, $title, $linestart, true );
1718 * Add wikitext with tidy enabled
1720 * @param string $text Wikitext
1721 * @param bool $linestart Is this the start of a line?
1723 public function addWikiTextTidy( $text, $linestart = true ) {
1724 $title = $this->getTitle();
1725 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1729 * Add wikitext with a custom Title object
1731 * @param string $text Wikitext
1732 * @param Title $title
1733 * @param bool $linestart Is this the start of a line?
1734 * @param bool $tidy Whether to use tidy
1735 * @param bool $interface Whether it is an interface message
1736 * (for example disables conversion)
1738 public function addWikiTextTitle( $text, Title
$title, $linestart,
1739 $tidy = false, $interface = false
1743 $popts = $this->parserOptions();
1744 $oldTidy = $popts->setTidy( $tidy );
1745 $popts->setInterfaceMessage( (bool)$interface );
1747 $parserOutput = $wgParser->getFreshParser()->parse(
1748 $text, $title, $popts,
1749 $linestart, true, $this->mRevisionId
1752 $popts->setTidy( $oldTidy );
1754 $this->addParserOutput( $parserOutput );
1759 * Add a ParserOutput object, but without Html.
1761 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1762 * @param ParserOutput $parserOutput
1764 public function addParserOutputNoText( $parserOutput ) {
1765 $this->addParserOutputMetadata( $parserOutput );
1769 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1770 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1774 * @param ParserOutput $parserOutput
1776 public function addParserOutputMetadata( $parserOutput ) {
1777 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1778 $this->addCategoryLinks( $parserOutput->getCategories() );
1779 $this->setIndicators( $parserOutput->getIndicators() );
1780 $this->mNewSectionLink
= $parserOutput->getNewSection();
1781 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1783 $this->mParseWarnings
= $parserOutput->getWarnings();
1784 if ( !$parserOutput->isCacheable() ) {
1785 $this->enableClientCache( false );
1787 $this->mNoGallery
= $parserOutput->getNoGallery();
1788 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1789 $this->addModules( $parserOutput->getModules() );
1790 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1791 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1792 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1793 $this->mPreventClickjacking
= $this->mPreventClickjacking
1794 ||
$parserOutput->preventClickjacking();
1796 // Template versioning...
1797 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1798 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1799 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1801 $this->mTemplateIds
[$ns] = $dbks;
1804 // File versioning...
1805 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1806 $this->mImageTimeKeys
[$dbk] = $data;
1809 // Hooks registered in the object
1810 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1811 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1812 list( $hookName, $data ) = $hookInfo;
1813 if ( isset( $parserOutputHooks[$hookName] ) ) {
1814 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1818 // enable OOUI if requested via ParserOutput
1819 if ( $parserOutput->getEnableOOUI() ) {
1820 $this->enableOOUI();
1823 // Link flags are ignored for now, but may in the future be
1824 // used to mark individual language links.
1825 $linkFlags = array();
1826 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1827 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1831 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1832 * ParserOutput object, without any other metadata.
1835 * @param ParserOutput $parserOutput
1837 public function addParserOutputContent( $parserOutput ) {
1838 $this->addParserOutputText( $parserOutput );
1840 $this->addModules( $parserOutput->getModules() );
1841 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1842 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1844 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1848 * Add the HTML associated with a ParserOutput object, without any metadata.
1851 * @param ParserOutput $parserOutput
1853 public function addParserOutputText( $parserOutput ) {
1854 $text = $parserOutput->getText();
1855 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1856 $this->addHTML( $text );
1860 * Add everything from a ParserOutput object.
1862 * @param ParserOutput $parserOutput
1864 function addParserOutput( $parserOutput ) {
1865 $this->addParserOutputMetadata( $parserOutput );
1866 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1868 // Touch section edit links only if not previously disabled
1869 if ( $parserOutput->getEditSectionTokens() ) {
1870 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1873 $this->addParserOutputText( $parserOutput );
1877 * Add the output of a QuickTemplate to the output buffer
1879 * @param QuickTemplate $template
1881 public function addTemplate( &$template ) {
1882 $this->addHTML( $template->getHTML() );
1886 * Parse wikitext and return the HTML.
1888 * @param string $text
1889 * @param bool $linestart Is this the start of a line?
1890 * @param bool $interface Use interface language ($wgLang instead of
1891 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1892 * This also disables LanguageConverter.
1893 * @param Language $language Target language object, will override $interface
1894 * @throws MWException
1895 * @return string HTML
1897 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1900 if ( is_null( $this->getTitle() ) ) {
1901 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1904 $popts = $this->parserOptions();
1906 $popts->setInterfaceMessage( true );
1908 if ( $language !== null ) {
1909 $oldLang = $popts->setTargetLanguage( $language );
1912 $parserOutput = $wgParser->getFreshParser()->parse(
1913 $text, $this->getTitle(), $popts,
1914 $linestart, true, $this->mRevisionId
1918 $popts->setInterfaceMessage( false );
1920 if ( $language !== null ) {
1921 $popts->setTargetLanguage( $oldLang );
1924 return $parserOutput->getText();
1928 * Parse wikitext, strip paragraphs, and return the HTML.
1930 * @param string $text
1931 * @param bool $linestart Is this the start of a line?
1932 * @param bool $interface Use interface language ($wgLang instead of
1933 * $wgContLang) while parsing language sensitive magic
1934 * words like GRAMMAR and PLURAL
1935 * @return string HTML
1937 public function parseInline( $text, $linestart = true, $interface = false ) {
1938 $parsed = $this->parse( $text, $linestart, $interface );
1939 return Parser
::stripOuterParagraph( $parsed );
1943 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1945 * @param int $maxage Maximum cache time on the Squid, in seconds.
1947 public function setSquidMaxage( $maxage ) {
1948 $this->mSquidMaxage
= $maxage;
1952 * Use enableClientCache(false) to force it to send nocache headers
1954 * @param bool $state
1958 public function enableClientCache( $state ) {
1959 return wfSetVar( $this->mEnableClientCache
, $state );
1963 * Get the list of cookies that will influence on the cache
1967 function getCacheVaryCookies() {
1969 if ( $cookies === null ) {
1970 $config = $this->getConfig();
1971 $cookies = array_merge(
1973 $config->get( 'CookiePrefix' ) . 'Token',
1974 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1978 $config->get( 'CacheVaryCookies' )
1980 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1986 * Check if the request has a cache-varying cookie header
1987 * If it does, it's very important that we don't allow public caching
1991 function haveCacheVaryCookies() {
1992 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1993 if ( $cookieHeader === false ) {
1996 $cvCookies = $this->getCacheVaryCookies();
1997 foreach ( $cvCookies as $cookieName ) {
1998 # Check for a simple string match, like the way squid does it
1999 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
2000 wfDebug( __METHOD__
. ": found $cookieName\n" );
2004 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2009 * Add an HTTP header that will influence on the cache
2011 * @param string $header Header name
2012 * @param string[]|null $option Options for X-Vary-Options. Possible options are:
2013 * - "string-contains=$XXX" varies on whether the header value as a string
2014 * contains $XXX as a substring.
2015 * - "list-contains=$XXX" varies on whether the header value as a
2016 * comma-separated list contains $XXX as one of the list items.
2018 public function addVaryHeader( $header, $option = null ) {
2019 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2020 $this->mVaryHeader
[$header] = (array)$option;
2021 } elseif ( is_array( $option ) ) {
2022 if ( is_array( $this->mVaryHeader
[$header] ) ) {
2023 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
2025 $this->mVaryHeader
[$header] = $option;
2028 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
2032 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2033 * such as Accept-Encoding or Cookie
2037 public function getVaryHeader() {
2038 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2042 * Get a complete X-Vary-Options header
2046 public function getXVO() {
2047 $cvCookies = $this->getCacheVaryCookies();
2049 $cookiesOption = array();
2050 foreach ( $cvCookies as $cookieName ) {
2051 $cookiesOption[] = 'string-contains=' . $cookieName;
2053 $this->addVaryHeader( 'Cookie', $cookiesOption );
2056 foreach ( $this->mVaryHeader
as $header => $option ) {
2057 $newheader = $header;
2058 if ( is_array( $option ) && count( $option ) > 0 ) {
2059 $newheader .= ';' . implode( ';', $option );
2061 $headers[] = $newheader;
2063 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2069 * bug 21672: Add Accept-Language to Vary and XVO headers
2070 * if there's no 'variant' parameter existed in GET.
2073 * /w/index.php?title=Main_page should always be served; but
2074 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2076 function addAcceptLanguage() {
2077 $title = $this->getTitle();
2078 if ( !$title instanceof Title
) {
2082 $lang = $title->getPageLanguage();
2083 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2084 $variants = $lang->getVariants();
2085 $aloption = array();
2086 foreach ( $variants as $variant ) {
2087 if ( $variant === $lang->getCode() ) {
2090 $aloption[] = 'string-contains=' . $variant;
2092 // IE and some other browsers use BCP 47 standards in
2093 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2094 // We should handle these too.
2095 $variantBCP47 = wfBCP47( $variant );
2096 if ( $variantBCP47 !== $variant ) {
2097 $aloption[] = 'string-contains=' . $variantBCP47;
2101 $this->addVaryHeader( 'Accept-Language', $aloption );
2106 * Set a flag which will cause an X-Frame-Options header appropriate for
2107 * edit pages to be sent. The header value is controlled by
2108 * $wgEditPageFrameOptions.
2110 * This is the default for special pages. If you display a CSRF-protected
2111 * form on an ordinary view page, then you need to call this function.
2113 * @param bool $enable
2115 public function preventClickjacking( $enable = true ) {
2116 $this->mPreventClickjacking
= $enable;
2120 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2121 * This can be called from pages which do not contain any CSRF-protected
2124 public function allowClickjacking() {
2125 $this->mPreventClickjacking
= false;
2129 * Get the prevent-clickjacking flag
2134 public function getPreventClickjacking() {
2135 return $this->mPreventClickjacking
;
2139 * Get the X-Frame-Options header value (without the name part), or false
2140 * if there isn't one. This is used by Skin to determine whether to enable
2141 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2145 public function getFrameOptions() {
2146 $config = $this->getConfig();
2147 if ( $config->get( 'BreakFrames' ) ) {
2149 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2150 return $config->get( 'EditPageFrameOptions' );
2156 * Send cache control HTTP headers
2158 public function sendCacheControl() {
2159 $response = $this->getRequest()->response();
2160 $config = $this->getConfig();
2161 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2162 $response->header( "ETag: $this->mETag" );
2165 $this->addVaryHeader( 'Cookie' );
2166 $this->addAcceptLanguage();
2168 # don't serve compressed data to clients who can't handle it
2169 # maintain different caches for logged-in users and non-logged in ones
2170 $response->header( $this->getVaryHeader() );
2172 if ( $config->get( 'UseXVO' ) ) {
2173 # Add an X-Vary-Options header for Squid with Wikimedia patches
2174 $response->header( $this->getXVO() );
2177 if ( $this->mEnableClientCache
) {
2179 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2180 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2182 if ( $config->get( 'UseESI' ) ) {
2183 # We'll purge the proxy cache explicitly, but require end user agents
2184 # to revalidate against the proxy on each visit.
2185 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2186 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2187 # start with a shorter timeout for initial testing
2188 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2189 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2190 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2191 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2193 # We'll purge the proxy cache for anons explicitly, but require end user agents
2194 # to revalidate against the proxy on each visit.
2195 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2196 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2197 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2198 # start with a shorter timeout for initial testing
2199 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2200 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2201 . ', must-revalidate, max-age=0' );
2204 # We do want clients to cache if they can, but they *must* check for updates
2205 # on revisiting the page.
2206 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2207 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2208 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2210 if ( $this->mLastModified
) {
2211 $response->header( "Last-Modified: {$this->mLastModified}" );
2214 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2216 # In general, the absence of a last modified header should be enough to prevent
2217 # the client from using its cache. We send a few other things just to make sure.
2218 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2219 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2220 $response->header( 'Pragma: no-cache' );
2225 * Finally, all the text has been munged and accumulated into
2226 * the object, let's actually output it:
2228 public function output() {
2229 if ( $this->mDoNothing
) {
2233 $response = $this->getRequest()->response();
2234 $config = $this->getConfig();
2236 if ( $this->mRedirect
!= '' ) {
2237 # Standards require redirect URLs to be absolute
2238 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2240 $redirect = $this->mRedirect
;
2241 $code = $this->mRedirectCode
;
2243 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2244 if ( $code == '301' ||
$code == '303' ) {
2245 if ( !$config->get( 'DebugRedirects' ) ) {
2246 $response->statusHeader( $code );
2248 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2250 if ( $config->get( 'VaryOnXFP' ) ) {
2251 $this->addVaryHeader( 'X-Forwarded-Proto' );
2253 $this->sendCacheControl();
2255 $response->header( "Content-Type: text/html; charset=utf-8" );
2256 if ( $config->get( 'DebugRedirects' ) ) {
2257 $url = htmlspecialchars( $redirect );
2258 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2259 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2260 print "</body>\n</html>\n";
2262 $response->header( 'Location: ' . $redirect );
2267 } elseif ( $this->mStatusCode
) {
2268 $response->statusHeader( $this->mStatusCode
);
2271 # Buffer output; final headers may depend on later processing
2274 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2275 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2277 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2278 // jQuery etc. can work correctly.
2279 $response->header( 'X-UA-Compatible: IE=Edge' );
2281 // Prevent framing, if requested
2282 $frameOptions = $this->getFrameOptions();
2283 if ( $frameOptions ) {
2284 $response->header( "X-Frame-Options: $frameOptions" );
2287 if ( $this->mArticleBodyOnly
) {
2288 echo $this->mBodytext
;
2290 $sk = $this->getSkin();
2291 // add skin specific modules
2292 $modules = $sk->getDefaultModules();
2294 // Enforce various default modules for all skins
2295 $coreModules = array(
2296 // Keep this list as small as possible
2298 'mediawiki.page.startup',
2302 // Support for high-density display images if enabled
2303 if ( $config->get( 'ResponsiveImages' ) ) {
2304 $coreModules[] = 'mediawiki.hidpi';
2307 $this->addModules( $coreModules );
2308 foreach ( $modules as $group ) {
2309 $this->addModules( $group );
2311 MWDebug
::addModules( $this );
2313 // Hook that allows last minute changes to the output page, e.g.
2314 // adding of CSS or Javascript by extensions.
2315 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2320 // This hook allows last minute changes to final overall output by modifying output buffer
2321 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2323 $this->sendCacheControl();
2330 * Actually output something with print.
2332 * @param string $ins The string to output
2333 * @deprecated since 1.22 Use echo yourself.
2335 public function out( $ins ) {
2336 wfDeprecated( __METHOD__
, '1.22' );
2341 * Produce a "user is blocked" page.
2342 * @deprecated since 1.18
2344 function blockedPage() {
2345 throw new UserBlockedError( $this->getUser()->mBlock
);
2349 * Prepare this object to display an error page; disable caching and
2350 * indexing, clear the current text and redirect, set the page's title
2351 * and optionally an custom HTML title (content of the "<title>" tag).
2353 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2354 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2355 * optional, if not passed the "<title>" attribute will be
2356 * based on $pageTitle
2358 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2359 $this->setPageTitle( $pageTitle );
2360 if ( $htmlTitle !== false ) {
2361 $this->setHTMLTitle( $htmlTitle );
2363 $this->setRobotPolicy( 'noindex,nofollow' );
2364 $this->setArticleRelated( false );
2365 $this->enableClientCache( false );
2366 $this->mRedirect
= '';
2367 $this->clearSubtitle();
2372 * Output a standard error page
2374 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2375 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2376 * showErrorPage( 'titlemsg', $messageObject );
2377 * showErrorPage( $titleMessageObject, $messageObject );
2379 * @param string|Message $title Message key (string) for page title, or a Message object
2380 * @param string|Message $msg Message key (string) for page text, or a Message object
2381 * @param array $params Message parameters; ignored if $msg is a Message object
2383 public function showErrorPage( $title, $msg, $params = array() ) {
2384 if ( !$title instanceof Message
) {
2385 $title = $this->msg( $title );
2388 $this->prepareErrorPage( $title );
2390 if ( $msg instanceof Message
) {
2391 if ( $params !== array() ) {
2392 trigger_error( 'Argument ignored: $params. The message parameters argument '
2393 . 'is discarded when the $msg argument is a Message object instead of '
2394 . 'a string.', E_USER_NOTICE
);
2396 $this->addHTML( $msg->parseAsBlock() );
2398 $this->addWikiMsgArray( $msg, $params );
2401 $this->returnToMain();
2405 * Output a standard permission error page
2407 * @param array $errors Error message keys
2408 * @param string $action Action that was denied or null if unknown
2410 public function showPermissionsErrorPage( array $errors, $action = null ) {
2411 // For some action (read, edit, create and upload), display a "login to do this action"
2412 // error if all of the following conditions are met:
2413 // 1. the user is not logged in
2414 // 2. the only error is insufficient permissions (i.e. no block or something else)
2415 // 3. the error can be avoided simply by logging in
2416 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2417 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2418 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2419 && ( User
::groupHasPermission( 'user', $action )
2420 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2422 $displayReturnto = null;
2424 # Due to bug 32276, if a user does not have read permissions,
2425 # $this->getTitle() will just give Special:Badtitle, which is
2426 # not especially useful as a returnto parameter. Use the title
2427 # from the request instead, if there was one.
2428 $request = $this->getRequest();
2429 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2430 if ( $action == 'edit' ) {
2431 $msg = 'whitelistedittext';
2432 $displayReturnto = $returnto;
2433 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2434 $msg = 'nocreatetext';
2435 } elseif ( $action == 'upload' ) {
2436 $msg = 'uploadnologintext';
2438 $msg = 'loginreqpagetext';
2439 $displayReturnto = Title
::newMainPage();
2445 $query['returnto'] = $returnto->getPrefixedText();
2447 if ( !$request->wasPosted() ) {
2448 $returntoquery = $request->getValues();
2449 unset( $returntoquery['title'] );
2450 unset( $returntoquery['returnto'] );
2451 unset( $returntoquery['returntoquery'] );
2452 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2455 $loginLink = Linker
::linkKnown(
2456 SpecialPage
::getTitleFor( 'Userlogin' ),
2457 $this->msg( 'loginreqlink' )->escaped(),
2462 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2463 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2465 # Don't return to a page the user can't read otherwise
2466 # we'll end up in a pointless loop
2467 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2468 $this->returnToMain( null, $displayReturnto );
2471 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2472 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2477 * Display an error page indicating that a given version of MediaWiki is
2478 * required to use it
2480 * @param mixed $version The version of MediaWiki needed to use the page
2482 public function versionRequired( $version ) {
2483 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2485 $this->addWikiMsg( 'versionrequiredtext', $version );
2486 $this->returnToMain();
2490 * Display an error page noting that a given permission bit is required.
2491 * @deprecated since 1.18, just throw the exception directly
2492 * @param string $permission Key required
2493 * @throws PermissionsError
2495 public function permissionRequired( $permission ) {
2496 throw new PermissionsError( $permission );
2500 * Produce the stock "please login to use the wiki" page
2502 * @deprecated since 1.19; throw the exception directly
2504 public function loginToUse() {
2505 throw new PermissionsError( 'read' );
2509 * Format a list of error messages
2511 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2512 * @param string $action Action that was denied or null if unknown
2513 * @return string The wikitext error-messages, formatted into a list.
2515 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2516 if ( $action == null ) {
2517 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2519 $action_desc = $this->msg( "action-$action" )->plain();
2521 'permissionserrorstext-withaction',
2524 )->plain() . "\n\n";
2527 if ( count( $errors ) > 1 ) {
2528 $text .= '<ul class="permissions-errors">' . "\n";
2530 foreach ( $errors as $error ) {
2532 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2537 $text .= "<div class=\"permissions-errors\">\n" .
2538 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2546 * Display a page stating that the Wiki is in read-only mode.
2547 * Should only be called after wfReadOnly() has returned true.
2549 * Historically, this function was used to show the source of the page that the user
2550 * was trying to edit and _also_ permissions error messages. The relevant code was
2551 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2553 * @deprecated since 1.25; throw the exception directly
2554 * @throws ReadOnlyError
2556 public function readOnlyPage() {
2557 if ( func_num_args() > 0 ) {
2558 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2561 throw new ReadOnlyError
;
2565 * Turn off regular page output and return an error response
2566 * for when rate limiting has triggered.
2568 * @deprecated since 1.25; throw the exception directly
2570 public function rateLimited() {
2571 wfDeprecated( __METHOD__
, '1.25' );
2572 throw new ThrottledError
;
2576 * Show a warning about slave lag
2578 * If the lag is higher than $wgSlaveLagCritical seconds,
2579 * then the warning is a bit more obvious. If the lag is
2580 * lower than $wgSlaveLagWarning, then no warning is shown.
2582 * @param int $lag Slave lag
2584 public function showLagWarning( $lag ) {
2585 $config = $this->getConfig();
2586 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2587 $message = $lag < $config->get( 'SlaveLagCritical' )
2590 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2591 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2595 public function showFatalError( $message ) {
2596 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2598 $this->addHTML( $message );
2601 public function showUnexpectedValueError( $name, $val ) {
2602 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2605 public function showFileCopyError( $old, $new ) {
2606 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2609 public function showFileRenameError( $old, $new ) {
2610 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2613 public function showFileDeleteError( $name ) {
2614 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2617 public function showFileNotFoundError( $name ) {
2618 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2622 * Add a "return to" link pointing to a specified title
2624 * @param Title $title Title to link
2625 * @param array $query Query string parameters
2626 * @param string $text Text of the link (input is not escaped)
2627 * @param array $options Options array to pass to Linker
2629 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2630 $link = $this->msg( 'returnto' )->rawParams(
2631 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2632 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2636 * Add a "return to" link pointing to a specified title,
2637 * or the title indicated in the request, or else the main page
2639 * @param mixed $unused
2640 * @param Title|string $returnto Title or String to return to
2641 * @param string $returntoquery Query string for the return to link
2643 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2644 if ( $returnto == null ) {
2645 $returnto = $this->getRequest()->getText( 'returnto' );
2648 if ( $returntoquery == null ) {
2649 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2652 if ( $returnto === '' ) {
2653 $returnto = Title
::newMainPage();
2656 if ( is_object( $returnto ) ) {
2657 $titleObj = $returnto;
2659 $titleObj = Title
::newFromText( $returnto );
2661 if ( !is_object( $titleObj ) ) {
2662 $titleObj = Title
::newMainPage();
2665 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2669 * @param Skin $sk The given Skin
2670 * @param bool $includeStyle Unused
2671 * @return string The doctype, opening "<html>", and head element.
2673 public function headElement( Skin
$sk, $includeStyle = true ) {
2676 $userdir = $this->getLanguage()->getDir();
2677 $sitedir = $wgContLang->getDir();
2679 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2681 if ( $this->getHTMLTitle() == '' ) {
2682 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2685 $openHead = Html
::openElement( 'head' );
2687 # Don't bother with the newline if $head == ''
2688 $ret .= "$openHead\n";
2691 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2692 // Add <meta charset="UTF-8">
2693 // This should be before <title> since it defines the charset used by
2694 // text including the text inside <title>.
2695 // The spec recommends defining XHTML5's charset using the XML declaration
2697 // Our XML declaration is output by Html::htmlHeader.
2698 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2699 // http://www.whatwg.org/html/semantics.html#charset
2700 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2703 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2704 $ret .= $this->getInlineHeadScripts() . "\n";
2705 $ret .= $this->buildCssLinks() . "\n";
2706 $ret .= $this->getExternalHeadScripts() . "\n";
2708 foreach ( $this->getHeadLinksArray() as $item ) {
2709 $ret .= $item . "\n";
2712 foreach ( $this->mHeadItems
as $item ) {
2713 $ret .= $item . "\n";
2716 $closeHead = Html
::closeElement( 'head' );
2718 $ret .= "$closeHead\n";
2721 $bodyClasses = array();
2722 $bodyClasses[] = 'mediawiki';
2724 # Classes for LTR/RTL directionality support
2725 $bodyClasses[] = $userdir;
2726 $bodyClasses[] = "sitedir-$sitedir";
2728 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2729 # A <body> class is probably not the best way to do this . . .
2730 $bodyClasses[] = 'capitalize-all-nouns';
2733 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2734 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2736 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2738 $bodyAttrs = array();
2739 // While the implode() is not strictly needed, it's used for backwards compatibility
2740 // (this used to be built as a string and hooks likely still expect that).
2741 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2743 // Allow skins and extensions to add body attributes they need
2744 $sk->addToBodyAttributes( $this, $bodyAttrs );
2745 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2747 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2753 * Get a ResourceLoader object associated with this OutputPage
2755 * @return ResourceLoader
2757 public function getResourceLoader() {
2758 if ( is_null( $this->mResourceLoader
) ) {
2759 $this->mResourceLoader
= new ResourceLoader(
2761 LoggerFactory
::getInstance( 'resourceloader' )
2764 return $this->mResourceLoader
;
2768 * Construct neccecary html and loader preset states to load modules on a page.
2770 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2772 * @param array|string $modules One or more module names
2773 * @param string $only ResourceLoaderModule TYPE_ class constant
2774 * @param array $extraQuery [optional] Array with extra query parameters for the request
2775 * @return array A list of HTML strings and array of client loader preset states
2777 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2778 $modules = (array)$modules;
2781 // List of html strings
2783 // Associative array of module names and their states
2784 'states' => array(),
2787 if ( !count( $modules ) ) {
2791 if ( count( $modules ) > 1 ) {
2792 // Remove duplicate module requests
2793 $modules = array_unique( $modules );
2794 // Sort module names so requests are more uniform
2797 if ( ResourceLoader
::inDebugMode() ) {
2798 // Recursively call us for every item
2799 foreach ( $modules as $name ) {
2800 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2801 $links['html'] = array_merge( $links['html'], $link['html'] );
2802 $links['states'] +
= $link['states'];
2808 if ( !is_null( $this->mTarget
) ) {
2809 $extraQuery['target'] = $this->mTarget
;
2812 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2813 $sortedModules = array();
2814 $resourceLoader = $this->getResourceLoader();
2815 foreach ( $modules as $name ) {
2816 $module = $resourceLoader->getModule( $name );
2817 # Check that we're allowed to include this module on this page
2819 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2820 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2821 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2822 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2823 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2824 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2825 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2830 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2833 foreach ( $sortedModules as $source => $groups ) {
2834 foreach ( $groups as $group => $grpModules ) {
2835 // Special handling for user-specific groups
2837 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2838 $user = $this->getUser()->getName();
2841 // Create a fake request based on the one we are about to make so modules return
2842 // correct timestamp and emptiness data
2843 $query = ResourceLoader
::makeLoaderQuery(
2844 array(), // modules; not determined yet
2845 $this->getLanguage()->getCode(),
2846 $this->getSkin()->getSkinName(),
2848 null, // version; not determined yet
2849 ResourceLoader
::inDebugMode(),
2850 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2851 $this->isPrintable(),
2852 $this->getRequest()->getBool( 'handheld' ),
2855 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2857 // Extract modules that know they're empty and see if we have one or more
2860 foreach ( $grpModules as $key => $module ) {
2861 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2862 // If we're only getting the styles, we don't need to do anything for empty modules.
2863 if ( $module->isKnownEmpty( $context ) ) {
2864 unset( $grpModules[$key] );
2865 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2866 $links['states'][$key] = 'ready';
2870 $isRaw |
= $module->isRaw();
2873 // If there are no non-empty modules, skip this group
2874 if ( count( $grpModules ) === 0 ) {
2878 // Inline private modules. These can't be loaded through load.php for security
2879 // reasons, see bug 34907. Note that these modules should be loaded from
2880 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2881 // properly use them as dependencies (bug 30914)
2882 if ( $group === 'private' ) {
2883 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2884 $links['html'][] = Html
::inlineStyle(
2885 $resourceLoader->makeModuleResponse( $context, $grpModules )
2888 $links['html'][] = ResourceLoader
::makeInlineScript(
2889 $resourceLoader->makeModuleResponse( $context, $grpModules )
2895 // Special handling for the user group; because users might change their stuff
2896 // on-wiki like user pages, or user preferences; we need to find the highest
2897 // timestamp of these user-changeable modules so we can ensure cache misses on change
2898 // This should NOT be done for the site group (bug 27564) because anons get that too
2899 // and we shouldn't be putting timestamps in Squid-cached HTML
2901 if ( $group === 'user' ) {
2902 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2905 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2906 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2907 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2909 // Automatically select style/script elements
2910 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2911 $media = $group === 'print' ?
'print' : 'all';
2912 $link = Html
::linkedStyle( $url, $media );
2914 if ( $context->getRaw() ||
$isRaw ) {
2915 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2916 $link = Html
::element( 'script', array(
2917 // In SpecialJavaScriptTest, QUnit must load synchronous
2918 'async' => !isset( $extraQuery['sync'] ),
2922 $link = ResourceLoader
::makeInlineScript(
2923 Xml
::encodeJsCall( 'mw.loader.load', array( $url ) )
2927 // For modules requested directly in the html via <script> or mw.loader.load
2928 // tell mw.loader they are being loading to prevent duplicate requests.
2929 foreach ( $grpModules as $key => $module ) {
2930 // Don't output state=loading for the startup module.
2931 if ( $key !== 'startup' ) {
2932 $links['states'][$key] = 'loading';
2937 if ( $group == 'noscript' ) {
2938 $links['html'][] = Html
::rawElement( 'noscript', array(), $link );
2940 $links['html'][] = $link;
2949 * Build html output from an array of links from makeResourceLoaderLink.
2950 * @param array $links
2951 * @return string HTML
2953 protected static function getHtmlFromLoaderLinks( array $links ) {
2956 foreach ( $links as $link ) {
2957 if ( !is_array( $link ) ) {
2960 $html = array_merge( $html, $link['html'] );
2961 $states +
= $link['states'];
2964 // Filter out empty values
2965 $html = array_filter( $html, 'strlen' );
2967 if ( count( $states ) ) {
2968 array_unshift( $html, ResourceLoader
::makeInlineScript(
2969 ResourceLoader
::makeLoaderStateScript( $states )
2973 return WrappedString
::join( "\n", $html );
2977 * JS stuff to put in the "<head>". This is the startup module, config
2978 * vars and modules marked with position 'top'
2980 * @return string HTML fragment
2982 function getHeadScripts() {
2983 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2987 * <script src="..."> tags for "<head>". This is the startup module
2988 * and other modules marked with position 'top'.
2990 * @return string HTML fragment
2992 function getExternalHeadScripts() {
2995 // Startup - this provides the client with the module manifest and loads jquery and mediawiki base modules
2996 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
2998 return self
::getHtmlFromLoaderLinks( $links );
3002 * <script>...</script> tags to put in "<head>".
3004 * @return string HTML fragment
3006 function getInlineHeadScripts() {
3009 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
3010 // Must be done synchronously on every page to avoid flashes of wrong content.
3011 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
3012 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
3013 // For the performance benefit of the majority, this is added unconditionally here and is
3014 // then fixed up by the startup module for unsupported browsers.
3015 $links[] = Html
::inlineScript(
3016 'document.documentElement.className = document.documentElement.className'
3017 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3020 // Load config before anything else
3021 $links[] = ResourceLoader
::makeInlineScript(
3022 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
3025 // Load embeddable private modules before any loader links
3026 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3027 // in mw.loader.implement() calls and deferred until mw.user is available
3028 $embedScripts = array( 'user.options' );
3029 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
3030 // Separate user.tokens as otherwise caching will be allowed (T84960)
3031 $links[] = $this->makeResourceLoaderLink( 'user.tokens', ResourceLoaderModule
::TYPE_COMBINED
);
3033 // Modules requests - let the client calculate dependencies and batch requests as it likes
3034 // Only load modules that have marked themselves for loading at the top
3035 $modules = $this->getModules( true, 'top' );
3037 $links[] = ResourceLoader
::makeInlineScript(
3038 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3042 // "Scripts only" modules marked for top inclusion
3043 $links[] = $this->makeResourceLoaderLink(
3044 $this->getModuleScripts( true, 'top' ),
3045 ResourceLoaderModule
::TYPE_SCRIPTS
3048 return self
::getHtmlFromLoaderLinks( $links );
3052 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3053 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3054 * site JS, and user JS.
3056 * @param bool $unused Previously used to let this method change its output based
3057 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3060 function getScriptsForBottomQueue( $unused = null ) {
3061 // Scripts "only" requests marked for bottom inclusion
3062 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3065 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3066 ResourceLoaderModule
::TYPE_SCRIPTS
3069 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3070 ResourceLoaderModule
::TYPE_STYLES
3073 // Modules requests - let the client calculate dependencies and batch requests as it likes
3074 // Only load modules that have marked themselves for loading at the bottom
3075 $modules = $this->getModules( true, 'bottom' );
3077 $links[] = ResourceLoader
::makeInlineScript(
3078 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3083 $links[] = $this->mScripts
;
3085 // Add user JS if enabled
3086 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3087 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3088 if ( $this->getConfig()->get( 'AllowUserJs' )
3089 && $this->getUser()->isLoggedIn()
3090 && $this->getTitle()
3091 && $this->getTitle()->isJsSubpage()
3092 && $this->userCanPreview()
3094 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3095 // and include the draft contents as a raw script instead.
3096 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3097 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3099 // Load the previewed JS
3100 $links[] = ResourceLoader
::makeInlineScript(
3101 Xml
::encodeJsCall( 'mw.loader.using', array(
3102 array( 'user', 'site' ),
3105 . Xml
::encodeJsCall( '$.globalEval', array(
3106 $this->getRequest()->getText( 'wpTextbox1' )
3113 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3114 // asynchronously and may arrive *after* the inline script here. So the previewed code
3115 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3116 // Similarly, when previewing ./common.js and the user module does arrive first, it will
3117 // arrive without common.js and the inline script runs after. Thus running common after
3118 // the excluded subpage.
3120 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3121 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3124 // Group JS is only enabled if site JS is enabled.
3125 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
);
3127 return self
::getHtmlFromLoaderLinks( $links );
3131 * JS stuff to put at the bottom of the "<body>"
3134 function getBottomScripts() {
3135 // In case the skin wants to add bottom CSS
3136 $this->getSkin()->setupSkinUserCss( $this );
3138 return $this->getScriptsForBottomQueue();
3142 * Get the javascript config vars to include on this page
3144 * @return array Array of javascript config vars
3147 public function getJsConfigVars() {
3148 return $this->mJsConfigVars
;
3152 * Add one or more variables to be set in mw.config in JavaScript
3154 * @param string|array $keys Key or array of key/value pairs
3155 * @param mixed $value [optional] Value of the configuration variable
3157 public function addJsConfigVars( $keys, $value = null ) {
3158 if ( is_array( $keys ) ) {
3159 foreach ( $keys as $key => $value ) {
3160 $this->mJsConfigVars
[$key] = $value;
3165 $this->mJsConfigVars
[$keys] = $value;
3169 * Get an array containing the variables to be set in mw.config in JavaScript.
3171 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3172 * - in other words, page-independent/site-wide variables (without state).
3173 * You will only be adding bloat to the html page and causing page caches to
3174 * have to be purged on configuration changes.
3177 public function getJSVars() {
3182 $canonicalSpecialPageName = false; # bug 21115
3184 $title = $this->getTitle();
3185 $ns = $title->getNamespace();
3186 $canonicalNamespace = MWNamespace
::exists( $ns )
3187 ? MWNamespace
::getCanonicalName( $ns )
3188 : $title->getNsText();
3190 $sk = $this->getSkin();
3191 // Get the relevant title so that AJAX features can use the correct page name
3192 // when making API requests from certain special pages (bug 34972).
3193 $relevantTitle = $sk->getRelevantTitle();
3194 $relevantUser = $sk->getRelevantUser();
3196 if ( $ns == NS_SPECIAL
) {
3197 list( $canonicalSpecialPageName, /*...*/ ) =
3198 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3199 } elseif ( $this->canUseWikiPage() ) {
3200 $wikiPage = $this->getWikiPage();
3201 $curRevisionId = $wikiPage->getLatest();
3202 $articleId = $wikiPage->getId();
3205 $lang = $title->getPageLanguage();
3207 // Pre-process information
3208 $separatorTransTable = $lang->separatorTransformTable();
3209 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3210 $compactSeparatorTransTable = array(
3211 implode( "\t", array_keys( $separatorTransTable ) ),
3212 implode( "\t", $separatorTransTable ),
3214 $digitTransTable = $lang->digitTransformTable();
3215 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3216 $compactDigitTransTable = array(
3217 implode( "\t", array_keys( $digitTransTable ) ),
3218 implode( "\t", $digitTransTable ),
3221 $user = $this->getUser();
3224 'wgCanonicalNamespace' => $canonicalNamespace,
3225 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3226 'wgNamespaceNumber' => $title->getNamespace(),
3227 'wgPageName' => $title->getPrefixedDBkey(),
3228 'wgTitle' => $title->getText(),
3229 'wgCurRevisionId' => $curRevisionId,
3230 'wgRevisionId' => (int)$this->getRevisionId(),
3231 'wgArticleId' => $articleId,
3232 'wgIsArticle' => $this->isArticle(),
3233 'wgIsRedirect' => $title->isRedirect(),
3234 'wgAction' => Action
::getActionName( $this->getContext() ),
3235 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3236 'wgUserGroups' => $user->getEffectiveGroups(),
3237 'wgCategories' => $this->getCategories(),
3238 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3239 'wgPageContentLanguage' => $lang->getCode(),
3240 'wgPageContentModel' => $title->getContentModel(),
3241 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3242 'wgDigitTransformTable' => $compactDigitTransTable,
3243 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3244 'wgMonthNames' => $lang->getMonthNamesArray(),
3245 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3246 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3247 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3250 if ( $user->isLoggedIn() ) {
3251 $vars['wgUserId'] = $user->getId();
3252 $vars['wgUserEditCount'] = $user->getEditCount();
3253 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3254 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3255 // Get the revision ID of the oldest new message on the user's talk
3256 // page. This can be used for constructing new message alerts on
3258 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3261 if ( $wgContLang->hasVariants() ) {
3262 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3264 // Same test as SkinTemplate
3265 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3266 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3268 foreach ( $title->getRestrictionTypes() as $type ) {
3269 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3272 if ( $title->isMainPage() ) {
3273 $vars['wgIsMainPage'] = true;
3276 if ( $this->mRedirectedFrom
) {
3277 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3280 if ( $relevantUser ) {
3281 $vars['wgRelevantUserName'] = $relevantUser->getName();
3284 // Allow extensions to add their custom variables to the mw.config map.
3285 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3286 // page-dependant but site-wide (without state).
3287 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3288 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3290 // Merge in variables from addJsConfigVars last
3291 return array_merge( $vars, $this->getJsConfigVars() );
3295 * To make it harder for someone to slip a user a fake
3296 * user-JavaScript or user-CSS preview, a random token
3297 * is associated with the login session. If it's not
3298 * passed back with the preview request, we won't render
3303 public function userCanPreview() {
3304 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3305 ||
!$this->getRequest()->wasPosted()
3306 ||
!$this->getUser()->matchEditToken(
3307 $this->getRequest()->getVal( 'wpEditToken' ) )
3311 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3314 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3315 // Don't execute another user's CSS or JS on preview (T85855)
3319 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3323 * @return array Array in format "link name or number => 'link html'".
3325 public function getHeadLinksArray() {
3329 $config = $this->getConfig();
3331 $canonicalUrl = $this->mCanonicalUrl
;
3333 $tags['meta-generator'] = Html
::element( 'meta', array(
3334 'name' => 'generator',
3335 'content' => "MediaWiki $wgVersion",
3338 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3339 $tags['meta-referrer'] = Html
::element( 'meta', array(
3340 'name' => 'referrer',
3341 'content' => $config->get( 'ReferrerPolicy' )
3345 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3346 if ( $p !== 'index,follow' ) {
3347 // http://www.robotstxt.org/wc/meta-user.html
3348 // Only show if it's different from the default robots policy
3349 $tags['meta-robots'] = Html
::element( 'meta', array(
3355 foreach ( $this->mMetatags
as $tag ) {
3356 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3358 $tag[0] = substr( $tag[0], 5 );
3362 $tagName = "meta-{$tag[0]}";
3363 if ( isset( $tags[$tagName] ) ) {
3364 $tagName .= $tag[1];
3366 $tags[$tagName] = Html
::element( 'meta',
3369 'content' => $tag[1]
3374 foreach ( $this->mLinktags
as $tag ) {
3375 $tags[] = Html
::element( 'link', $tag );
3378 # Universal edit button
3379 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3380 $user = $this->getUser();
3381 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3382 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3383 // Original UniversalEditButton
3384 $msg = $this->msg( 'edit' )->text();
3385 $tags['universal-edit-button'] = Html
::element( 'link', array(
3386 'rel' => 'alternate',
3387 'type' => 'application/x-wiki',
3389 'href' => $this->getTitle()->getEditURL(),
3391 // Alternate edit link
3392 $tags['alternative-edit'] = Html
::element( 'link', array(
3395 'href' => $this->getTitle()->getEditURL(),
3400 # Generally the order of the favicon and apple-touch-icon links
3401 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3402 # uses whichever one appears later in the HTML source. Make sure
3403 # apple-touch-icon is specified first to avoid this.
3404 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3405 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3406 'rel' => 'apple-touch-icon',
3407 'href' => $config->get( 'AppleTouchIcon' )
3411 if ( $config->get( 'Favicon' ) !== false ) {
3412 $tags['favicon'] = Html
::element( 'link', array(
3413 'rel' => 'shortcut icon',
3414 'href' => $config->get( 'Favicon' )
3418 # OpenSearch description link
3419 $tags['opensearch'] = Html
::element( 'link', array(
3421 'type' => 'application/opensearchdescription+xml',
3422 'href' => wfScript( 'opensearch_desc' ),
3423 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3426 if ( $config->get( 'EnableAPI' ) ) {
3427 # Real Simple Discovery link, provides auto-discovery information
3428 # for the MediaWiki API (and potentially additional custom API
3429 # support such as WordPress or Twitter-compatible APIs for a
3430 # blogging extension, etc)
3431 $tags['rsd'] = Html
::element( 'link', array(
3433 'type' => 'application/rsd+xml',
3434 // Output a protocol-relative URL here if $wgServer is protocol-relative
3435 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3436 'href' => wfExpandUrl( wfAppendQuery(
3438 array( 'action' => 'rsd' ) ),
3445 if ( !$config->get( 'DisableLangConversion' ) ) {
3446 $lang = $this->getTitle()->getPageLanguage();
3447 if ( $lang->hasVariants() ) {
3448 $variants = $lang->getVariants();
3449 foreach ( $variants as $variant ) {
3450 $tags["variant-$variant"] = Html
::element( 'link', array(
3451 'rel' => 'alternate',
3452 'hreflang' => wfBCP47( $variant ),
3453 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $variant ) ) )
3456 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3457 $tags["variant-x-default"] = Html
::element( 'link', array(
3458 'rel' => 'alternate',
3459 'hreflang' => 'x-default',
3460 'href' => $this->getTitle()->getLocalURL() ) );
3465 if ( $this->copyrightUrl
!== null ) {
3466 $copyright = $this->copyrightUrl
;
3469 if ( $config->get( 'RightsPage' ) ) {
3470 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3473 $copyright = $copy->getLocalURL();
3477 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3478 $copyright = $config->get( 'RightsUrl' );
3483 $tags['copyright'] = Html
::element( 'link', array(
3484 'rel' => 'copyright',
3485 'href' => $copyright )
3490 if ( $config->get( 'Feed' ) ) {
3491 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3492 # Use the page name for the title. In principle, this could
3493 # lead to issues with having the same name for different feeds
3494 # corresponding to the same page, but we can't avoid that at
3497 $tags[] = $this->feedLink(
3500 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3501 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3505 # Recent changes feed should appear on every page (except recentchanges,
3506 # that would be redundant). Put it after the per-page feed to avoid
3507 # changing existing behavior. It's still available, probably via a
3508 # menu in your browser. Some sites might have a different feed they'd
3509 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3510 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3511 # If so, use it instead.
3512 $sitename = $config->get( 'Sitename' );
3513 if ( $config->get( 'OverrideSiteFeed' ) ) {
3514 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3515 // Note, this->feedLink escapes the url.
3516 $tags[] = $this->feedLink(
3519 $this->msg( "site-{$type}-feed", $sitename )->text()
3522 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3523 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3524 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3525 $tags[] = $this->feedLink(
3527 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3528 # For grep: 'site-rss-feed', 'site-atom-feed'
3529 $this->msg( "site-{$format}-feed", $sitename )->text()
3536 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3537 if ( $canonicalUrl !== false ) {
3538 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3540 if ( $this->isArticleRelated() ) {
3541 // This affects all requests where "setArticleRelated" is true. This is
3542 // typically all requests that show content (query title, curid, oldid, diff),
3543 // and all wikipage actions (edit, delete, purge, info, history etc.).
3544 // It does not apply to File pages and Special pages.
3545 // 'history' and 'info' actions address page metadata rather than the page
3546 // content itself, so they may not be canonicalized to the view page url.
3547 // TODO: this ought to be better encapsulated in the Action class.
3548 $action = Action
::getActionName( $this->getContext() );
3549 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3550 $query = "action={$action}";
3554 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3556 $reqUrl = $this->getRequest()->getRequestURL();
3557 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3561 if ( $canonicalUrl !== false ) {
3562 $tags[] = Html
::element( 'link', array(
3563 'rel' => 'canonical',
3564 'href' => $canonicalUrl
3572 * @return string HTML tag links to be put in the header.
3573 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3574 * OutputPage::getHeadLinksArray directly.
3576 public function getHeadLinks() {
3577 wfDeprecated( __METHOD__
, '1.24' );
3578 return implode( "\n", $this->getHeadLinksArray() );
3582 * Generate a "<link rel/>" for a feed.
3584 * @param string $type Feed type
3585 * @param string $url URL to the feed
3586 * @param string $text Value of the "title" attribute
3587 * @return string HTML fragment
3589 private function feedLink( $type, $url, $text ) {
3590 return Html
::element( 'link', array(
3591 'rel' => 'alternate',
3592 'type' => "application/$type+xml",
3599 * Add a local or specified stylesheet, with the given media options.
3600 * Meant primarily for internal use...
3602 * @param string $style URL to the file
3603 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3604 * @param string $condition For IE conditional comments, specifying an IE version
3605 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3607 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3609 // Even though we expect the media type to be lowercase, but here we
3610 // force it to lowercase to be safe.
3612 $options['media'] = $media;
3615 $options['condition'] = $condition;
3618 $options['dir'] = $dir;
3620 $this->styles
[$style] = $options;
3624 * Adds inline CSS styles
3625 * @param mixed $style_css Inline CSS
3626 * @param string $flip Set to 'flip' to flip the CSS if needed
3628 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3629 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3630 # If wanted, and the interface is right-to-left, flip the CSS
3631 $style_css = CSSJanus
::transform( $style_css, true, false );
3633 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3637 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3638 * These will be applied to various media & IE conditionals.
3642 public function buildCssLinks() {
3645 $this->getSkin()->setupSkinUserCss( $this );
3647 // Add ResourceLoader styles
3648 // Split the styles into these groups
3653 'private' => array(),
3654 'noscript' => array()
3657 $otherTags = array(); // Tags to append after the normal <link> tags
3658 $resourceLoader = $this->getResourceLoader();
3660 $moduleStyles = $this->getModuleStyles( true, 'top' );
3662 // Per-site custom styles
3663 $moduleStyles[] = 'site';
3664 $moduleStyles[] = 'noscript';
3665 $moduleStyles[] = 'user.groups';
3667 // Per-user custom styles
3668 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3669 && $this->userCanPreview()
3671 // We're on a preview of a CSS subpage
3672 // Exclude this page from the user module in case it's in there (bug 26283)
3673 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3674 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3676 $otherTags = array_merge( $otherTags, $link['html'] );
3678 // Load the previewed CSS
3679 // If needed, Janus it first. This is user-supplied CSS, so it's
3680 // assumed to be right for the content language directionality.
3681 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3682 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3683 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3685 $otherTags[] = Html
::inlineStyle( $previewedCSS ) . "\n";
3687 // Load the user styles normally
3688 $moduleStyles[] = 'user';
3691 // Per-user preference styles
3692 $moduleStyles[] = 'user.cssprefs';
3694 foreach ( $moduleStyles as $name ) {
3695 $module = $resourceLoader->getModule( $name );
3699 if ( $name === 'site' ) {
3700 // HACK: The site module shouldn't be fragmented with a cache group and
3701 // http request. But in order to ensure its styles are separated and after the
3702 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3703 // The scripts remain ungrouped and rides the bottom queue.
3704 $styles['site'][] = $name;
3707 $group = $module->getGroup();
3708 // Modules in groups other than the ones needing special treatment (see $styles assignment)
3709 // will be placed in the "other" style category.
3710 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3713 // We want site, private and user styles to override dynamically added
3714 // styles from modules, but we want dynamically added styles to override
3715 // statically added styles from other modules. So the order has to be
3716 // other, dynamic, site, private, user. Add statically added styles for
3718 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3719 // Add normal styles added through addStyle()/addInlineStyle() here
3720 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3721 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3722 // We use a <meta> tag with a made-up name for this because that's valid HTML
3723 $links[] = Html
::element(
3725 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3728 // Add site-specific and user-specific styles
3729 // 'private' at present only contains user.options, so put that before 'user'
3730 // Any future private modules will likely have a similar user-specific character
3731 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3732 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3733 ResourceLoaderModule
::TYPE_STYLES
3737 // Add stuff in $otherTags (previewed user CSS if applicable)
3738 return self
::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3744 public function buildCssLinksArray() {
3747 // Add any extension CSS
3748 foreach ( $this->mExtStyles
as $url ) {
3749 $this->addStyle( $url );
3751 $this->mExtStyles
= array();
3753 foreach ( $this->styles
as $file => $options ) {
3754 $link = $this->styleLink( $file, $options );
3756 $links[$file] = $link;
3763 * Generate \<link\> tags for stylesheets
3765 * @param string $style URL to the file
3766 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3767 * @return string HTML fragment
3769 protected function styleLink( $style, array $options ) {
3770 if ( isset( $options['dir'] ) ) {
3771 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3776 if ( isset( $options['media'] ) ) {
3777 $media = self
::transformCssMedia( $options['media'] );
3778 if ( is_null( $media ) ) {
3785 if ( substr( $style, 0, 1 ) == '/' ||
3786 substr( $style, 0, 5 ) == 'http:' ||
3787 substr( $style, 0, 6 ) == 'https:' ) {
3790 $config = $this->getConfig();
3791 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3794 $link = Html
::linkedStyle( $url, $media );
3796 if ( isset( $options['condition'] ) ) {
3797 $condition = htmlspecialchars( $options['condition'] );
3798 $link = "<!--[if $condition]>$link<![endif]-->";
3804 * Transform "media" attribute based on request parameters
3806 * @param string $media Current value of the "media" attribute
3807 * @return string Modified value of the "media" attribute, or null to skip
3810 public static function transformCssMedia( $media ) {
3813 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3814 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3816 // Switch in on-screen display for media testing
3818 'printable' => 'print',
3819 'handheld' => 'handheld',
3821 foreach ( $switches as $switch => $targetMedia ) {
3822 if ( $wgRequest->getBool( $switch ) ) {
3823 if ( $media == $targetMedia ) {
3825 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3826 // This regex will not attempt to understand a comma-separated media_query_list
3828 // Example supported values for $media:
3829 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3830 // Example NOT supported value for $media:
3831 // '3d-glasses, screen, print and resolution > 90dpi'
3833 // If it's a print request, we never want any kind of screen stylesheets
3834 // If it's a handheld request (currently the only other choice with a switch),
3835 // we don't want simple 'screen' but we might want screen queries that
3836 // have a max-width or something, so we'll pass all others on and let the
3837 // client do the query.
3838 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3849 * Add a wikitext-formatted message to the output.
3850 * This is equivalent to:
3852 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3854 public function addWikiMsg( /*...*/ ) {
3855 $args = func_get_args();
3856 $name = array_shift( $args );
3857 $this->addWikiMsgArray( $name, $args );
3861 * Add a wikitext-formatted message to the output.
3862 * Like addWikiMsg() except the parameters are taken as an array
3863 * instead of a variable argument list.
3865 * @param string $name
3866 * @param array $args
3868 public function addWikiMsgArray( $name, $args ) {
3869 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3873 * This function takes a number of message/argument specifications, wraps them in
3874 * some overall structure, and then parses the result and adds it to the output.
3876 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3877 * and so on. The subsequent arguments may be either
3878 * 1) strings, in which case they are message names, or
3879 * 2) arrays, in which case, within each array, the first element is the message
3880 * name, and subsequent elements are the parameters to that message.
3882 * Don't use this for messages that are not in the user's interface language.
3886 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3890 * $wgOut->addWikiText( "<div class='error'>\n"
3891 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3893 * The newline after the opening div is needed in some wikitext. See bug 19226.
3895 * @param string $wrap
3897 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3898 $msgSpecs = func_get_args();
3899 array_shift( $msgSpecs );
3900 $msgSpecs = array_values( $msgSpecs );
3902 foreach ( $msgSpecs as $n => $spec ) {
3903 if ( is_array( $spec ) ) {
3905 $name = array_shift( $args );
3906 if ( isset( $args['options'] ) ) {
3907 unset( $args['options'] );
3909 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3917 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3919 $this->addWikiText( $s );
3923 * Include jQuery core. Use this to avoid loading it multiple times
3924 * before we get a usable script loader.
3926 * @param array $modules List of jQuery modules which should be loaded
3927 * @return array The list of modules which were not loaded.
3929 * @deprecated since 1.17
3931 public function includeJQuery( array $modules = array() ) {
3936 * Enables/disables TOC, doesn't override __NOTOC__
3940 public function enableTOC( $flag = true ) {
3941 $this->mEnableTOC
= $flag;
3948 public function isTOCEnabled() {
3949 return $this->mEnableTOC
;
3953 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3957 public function enableSectionEditLinks( $flag = true ) {
3958 $this->mEnableSectionEditLinks
= $flag;
3965 public function sectionEditLinksEnabled() {
3966 return $this->mEnableSectionEditLinks
;
3970 * Helper function to setup the PHP implementation of OOUI to use in this request.
3973 * @param String $skinName The Skin name to determine the correct OOUI theme
3974 * @param String $dir Language direction
3976 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
3977 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
3978 // Make keys (skin names) lowercase for case-insensitive matching.
3979 $themes = array_change_key_case( $themes, CASE_LOWER
);
3980 $theme = isset( $themes[ $skinName ] ) ?
$themes[ $skinName ] : 'MediaWiki';
3981 // For example, 'OOUI\MediaWikiTheme'.
3982 $themeClass = "OOUI\\{$theme}Theme";
3983 OOUI\Theme
::setSingleton( new $themeClass() );
3984 OOUI\Element
::setDefaultDir( $dir );
3988 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3989 * MediaWiki and this OutputPage instance.
3993 public function enableOOUI() {
3995 strtolower( $this->getSkin()->getSkinName() ),
3996 $this->getLanguage()->getDir()
3998 $this->addModuleStyles( array(
4000 'oojs-ui.styles.icons',
4001 'oojs-ui.styles.indicators',
4002 'oojs-ui.styles.textures',
4003 'mediawiki.widgets.styles',