3 * Preparation for the final page rendering.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * This class should be covered by a general architecture document which does
25 * not exist as of January 2011. This is one of the Core classes and should
26 * be read at least once by any new developers.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
66 * Holds the debug lines that will be output as comments in page source if
67 * $wgDebugComments is enabled. See also $wgShowDebug.
68 * @deprecated since 1.20; use MWDebug class instead.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
103 * @var string Variable mLastModified and mEtag are used for sending cache control.
104 * The whole caching system should probably be moved into its own class.
106 protected $mLastModified = '';
109 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
110 * as a unique identifier for the content. It is later used by the client
111 * to compare its cached version with the server version. Client sends
112 * headers If-Match and If-None-Match containing its locally cached ETAG value.
114 * To get more information, you will have to look at HTTP/1.1 protocol which
115 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
125 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
126 private $mLanguageLinks = array();
129 * Used for JavaScript (pre resource loader)
130 * @todo We should split JS / CSS.
131 * mScripts content is inserted as is in "<head>" by Skin. This might
132 * contain either a link to a stylesheet or inline CSS.
134 private $mScripts = '';
136 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
137 protected $mInlineStyles = '';
140 private $mLinkColours;
143 * @var string Used by skin template.
144 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
146 public $mPageLinkTitle = '';
148 /** @var array Array of elements in "<head>". Parser might add its own headers! */
149 protected $mHeadItems = array();
151 // @todo FIXME: Next 5 variables probably come from the resource loader
154 protected $mModules = array();
157 protected $mModuleScripts = array();
160 protected $mModuleStyles = array();
163 protected $mModuleMessages = array();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
200 private $mContainsOldMagic = 0;
203 protected $mContainsNewMagic = 0;
206 * lazy initialised, use parserOptions()
209 protected $mParserOptions = null;
212 * Handles the Atom / RSS links.
213 * We probably only support Atom in 2011.
214 * @see $wgAdvertisedFeedTypes
216 private $mFeedLinks = array();
218 // Gwicke work on squid caching? Roughly from 2003.
219 protected $mEnableClientCache = true;
221 /** @var bool Flag if output should only contain the body of the article. */
222 private $mArticleBodyOnly = false;
225 protected $mNewSectionLink = false;
228 protected $mHideNewSectionLink = false;
231 * @var bool Comes from the parser. This was probably made to load CSS/JS
232 * only if we had "<gallery>". Used directly in CategoryPage.php.
233 * Looks like resource loader can replace this.
235 public $mNoGallery = false;
238 private $mPageTitleActionText = '';
241 private $mParseWarnings = array();
243 /** @var int Cache stuff. Looks like mEnableClientCache */
244 protected $mSquidMaxage = 0;
250 protected $mPreventClickjacking = true;
252 /** @var int To include the variable {{REVISIONID}} */
253 private $mRevisionId = null;
256 private $mRevisionTimestamp = null;
259 protected $mFileVersion = null;
262 * @var array An array of stylesheet filenames (relative from skins path),
263 * with options for CSS media, IE conditions, and RTL/LTR direction.
264 * For internal use; add settings in the skin via $this->addStyle()
266 * Style again! This seems like a code duplication since we already have
267 * mStyles. This is what makes Open Source amazing.
269 protected $styles = array();
272 * Whether jQuery is already handled.
274 protected $mJQueryDone = false;
276 private $mIndexPolicy = 'index';
277 private $mFollowPolicy = 'follow';
278 private $mVaryHeader = array(
279 'Accept-Encoding' => array( 'list-contains=gzip' ),
283 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
288 private $mRedirectedFrom = null;
291 * Additional key => value data
293 private $mProperties = array();
296 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
298 private $mTarget = null;
301 * @var bool Whether parser output should contain table of contents
303 private $mEnableTOC = true;
306 * @var bool Whether parser output should contain section edit links
308 private $mEnableSectionEditLinks = true;
311 * Constructor for OutputPage. This should not be called directly.
312 * Instead a new RequestContext should be created and it will implicitly create
313 * a OutputPage tied to that context.
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 HTTP status code to send with the output.
349 * @param int $statusCode
351 public function setStatusCode( $statusCode ) {
352 $this->mStatusCode
= $statusCode;
356 * Add a new "<meta>" tag
357 * To add an http-equiv meta tag, precede the name with "http:"
359 * @param string $name Tag name
360 * @param string $val Tag value
362 function addMeta( $name, $val ) {
363 array_push( $this->mMetatags
, array( $name, $val ) );
367 * Add a new \<link\> tag to the page header.
369 * Note: use setCanonicalUrl() for rel=canonical.
371 * @param array $linkarr Associative array of attributes.
373 function addLink( array $linkarr ) {
374 array_push( $this->mLinktags
, $linkarr );
378 * Add a new \<link\> with "rel" attribute set to "meta"
380 * @param array $linkarr Associative array mapping attribute names to their
381 * values, both keys and values will be escaped, and the
382 * "rel" attribute will be automatically added
384 function addMetadataLink( array $linkarr ) {
385 $linkarr['rel'] = $this->getMetadataAttribute();
386 $this->addLink( $linkarr );
390 * Set the URL to be used for the <link rel=canonical>. This should be used
391 * in preference to addLink(), to avoid duplicate link tags.
394 function setCanonicalUrl( $url ) {
395 $this->mCanonicalUrl
= $url;
399 * Get the value of the "rel" attribute for metadata links
403 public function getMetadataAttribute() {
404 # note: buggy CC software only reads first "meta" link
405 static $haveMeta = false;
407 return 'alternate meta';
415 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
417 * @param string $script Raw HTML
419 function addScript( $script ) {
420 $this->mScripts
.= $script . "\n";
424 * Register and add a stylesheet from an extension directory.
426 * @param string $url Path to sheet. Provide either a full url (beginning
427 * with 'http', etc) or a relative path from the document root
428 * (beginning with '/'). Otherwise it behaves identically to
429 * addStyle() and draws from the /skins folder.
431 public function addExtensionStyle( $url ) {
432 array_push( $this->mExtStyles
, $url );
436 * Get all styles added by extensions
440 function getExtStyle() {
441 return $this->mExtStyles
;
445 * Add a JavaScript file out of skins/common, or a given relative path.
447 * @param string $file Filename in skins/common or complete on-server path
449 * @param string $version Style version of the file. Defaults to $wgStyleVersion
451 public function addScriptFile( $file, $version = null ) {
452 global $wgStylePath, $wgStyleVersion;
453 // See if $file parameter is an absolute URL or begins with a slash
454 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
457 $path = "{$wgStylePath}/common/{$file}";
459 if ( is_null( $version ) ) {
460 $version = $wgStyleVersion;
462 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
466 * Add a self-contained script tag with the given contents
468 * @param string $script JavaScript text, no "<script>" tags
470 public function addInlineScript( $script ) {
471 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
475 * Get all registered JS and CSS tags for the header.
478 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
480 function getScript() {
481 wfDeprecated( __METHOD__
, '1.24' );
482 return $this->mScripts
. $this->getHeadItems();
486 * Filter an array of modules to remove insufficiently trustworthy members, and modules
487 * which are no longer registered (eg a page is cached before an extension is disabled)
488 * @param array $modules
489 * @param string|null $position If not null, only return modules with this position
490 * @param string $type
493 protected function filterModules( array $modules, $position = null,
494 $type = ResourceLoaderModule
::TYPE_COMBINED
496 $resourceLoader = $this->getResourceLoader();
497 $filteredModules = array();
498 foreach ( $modules as $val ) {
499 $module = $resourceLoader->getModule( $val );
500 if ( $module instanceof ResourceLoaderModule
501 && $module->getOrigin() <= $this->getAllowedModules( $type )
502 && ( is_null( $position ) ||
$module->getPosition() == $position )
503 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
505 $filteredModules[] = $val;
508 return $filteredModules;
512 * Get the list of modules to include on this page
514 * @param bool $filter Whether to filter out insufficiently trustworthy modules
515 * @param string|null $position If not null, only return modules with this position
516 * @param string $param
517 * @return array Array of module names
519 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
520 $modules = array_values( array_unique( $this->$param ) );
522 ?
$this->filterModules( $modules, $position )
527 * Add one or more modules recognized by the resource loader. Modules added
528 * through this function will be loaded by the resource loader when the
531 * @param string|array $modules Module name (string) or array of module names
533 public function addModules( $modules ) {
534 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
538 * Get the list of module JS to include on this page
540 * @param bool $filter
541 * @param string|null $position
543 * @return array Array of module names
545 public function getModuleScripts( $filter = false, $position = null ) {
546 return $this->getModules( $filter, $position, 'mModuleScripts' );
550 * Add only JS of one or more modules recognized by the resource loader. Module
551 * scripts added through this function will be loaded by the resource loader when
554 * @param string|array $modules Module name (string) or array of module names
556 public function addModuleScripts( $modules ) {
557 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
561 * Get the list of module CSS to include on this page
563 * @param bool $filter
564 * @param string|null $position
566 * @return array Array of module names
568 public function getModuleStyles( $filter = false, $position = null ) {
569 return $this->getModules( $filter, $position, 'mModuleStyles' );
573 * Add only CSS of one or more modules recognized by the resource loader.
575 * Module styles added through this function will be added using standard link CSS
576 * tags, rather than as a combined Javascript and CSS package. Thus, they will
577 * load when JavaScript is disabled (unless CSS also happens to be disabled).
579 * @param string|array $modules Module name (string) or array of module names
581 public function addModuleStyles( $modules ) {
582 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
586 * Get the list of module messages to include on this page
588 * @param bool $filter
589 * @param string|null $position
591 * @return array Array of module names
593 public function getModuleMessages( $filter = false, $position = null ) {
594 return $this->getModules( $filter, $position, 'mModuleMessages' );
598 * Add only messages of one or more modules recognized by the resource loader.
599 * Module messages added through this function will be loaded by the resource
600 * loader when the page loads.
602 * @param string|array $modules Module name (string) or array of module names
604 public function addModuleMessages( $modules ) {
605 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
609 * @return null|string ResourceLoader target
611 public function getTarget() {
612 return $this->mTarget
;
616 * Sets ResourceLoader target for load.php links. If null, will be omitted
618 * @param string|null $target
620 public function setTarget( $target ) {
621 $this->mTarget
= $target;
625 * Get an array of head items
629 function getHeadItemsArray() {
630 return $this->mHeadItems
;
634 * Get all header items in a string
637 * @deprecated since 1.24 Use OutputPage::headElement or
638 * if absolutely necessary use OutputPage::getHeadItemsArray
640 function getHeadItems() {
641 wfDeprecated( __METHOD__
, '1.24' );
643 foreach ( $this->mHeadItems
as $item ) {
650 * Add or replace an header item to the output
652 * @param string $name Item name
653 * @param string $value Raw HTML
655 public function addHeadItem( $name, $value ) {
656 $this->mHeadItems
[$name] = $value;
660 * Check if the header item $name is already set
662 * @param string $name Item name
665 public function hasHeadItem( $name ) {
666 return isset( $this->mHeadItems
[$name] );
670 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
672 * @param string $tag Value of "ETag" header
674 function setETag( $tag ) {
679 * Set whether the output should only contain the body of the article,
680 * without any skin, sidebar, etc.
681 * Used e.g. when calling with "action=render".
683 * @param bool $only Whether to output only the body of the article
685 public function setArticleBodyOnly( $only ) {
686 $this->mArticleBodyOnly
= $only;
690 * Return whether the output will contain only the body of the article
694 public function getArticleBodyOnly() {
695 return $this->mArticleBodyOnly
;
699 * Set an additional output property
702 * @param string $name
703 * @param mixed $value
705 public function setProperty( $name, $value ) {
706 $this->mProperties
[$name] = $value;
710 * Get an additional output property
713 * @param string $name
714 * @return mixed Property value or null if not found
716 public function getProperty( $name ) {
717 if ( isset( $this->mProperties
[$name] ) ) {
718 return $this->mProperties
[$name];
725 * checkLastModified tells the client to use the client-cached page if
726 * possible. If successful, the OutputPage is disabled so that
727 * any future call to OutputPage->output() have no effect.
729 * Side effect: sets mLastModified for Last-Modified header
731 * @param string $timestamp
733 * @return bool True if cache-ok headers was sent.
735 public function checkLastModified( $timestamp ) {
736 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
738 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
739 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
742 if ( !$wgCachePages ) {
743 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
747 $timestamp = wfTimestamp( TS_MW
, $timestamp );
748 $modifiedTimes = array(
749 'page' => $timestamp,
750 'user' => $this->getUser()->getTouched(),
751 'epoch' => $wgCacheEpoch
754 // bug 44570: the core page itself may not change, but resources might
755 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $wgSquidMaxage );
757 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
759 $maxModified = max( $modifiedTimes );
760 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
762 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
763 if ( $clientHeader === false ) {
764 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
768 # IE sends sizes after the date like this:
769 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
770 # this breaks strtotime().
771 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
773 wfSuppressWarnings(); // E_STRICT system time bitching
774 $clientHeaderTime = strtotime( $clientHeader );
776 if ( !$clientHeaderTime ) {
778 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
781 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
785 foreach ( $modifiedTimes as $name => $value ) {
786 if ( $info !== '' ) {
789 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
792 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
793 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
794 wfDebug( __METHOD__
. ": effective Last-Modified: " .
795 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
796 if ( $clientHeaderTime < $maxModified ) {
797 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
802 # Give a 304 response code and disable body output
803 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
804 ini_set( 'zlib.output_compression', 0 );
805 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
806 $this->sendCacheControl();
809 // Don't output a compressed blob when using ob_gzhandler;
810 // it's technically against HTTP spec and seems to confuse
811 // Firefox when the response gets split over two packets.
812 wfClearOutputBuffers();
818 * Override the last modified timestamp
820 * @param string $timestamp New timestamp, in a format readable by
823 public function setLastModified( $timestamp ) {
824 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
828 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
830 * @param string $policy The literal string to output as the contents of
831 * the meta tag. Will be parsed according to the spec and output in
835 public function setRobotPolicy( $policy ) {
836 $policy = Article
::formatRobotPolicy( $policy );
838 if ( isset( $policy['index'] ) ) {
839 $this->setIndexPolicy( $policy['index'] );
841 if ( isset( $policy['follow'] ) ) {
842 $this->setFollowPolicy( $policy['follow'] );
847 * Set the index policy for the page, but leave the follow policy un-
850 * @param string $policy Either 'index' or 'noindex'.
853 public function setIndexPolicy( $policy ) {
854 $policy = trim( $policy );
855 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
856 $this->mIndexPolicy
= $policy;
861 * Set the follow policy for the page, but leave the index policy un-
864 * @param string $policy Either 'follow' or 'nofollow'.
867 public function setFollowPolicy( $policy ) {
868 $policy = trim( $policy );
869 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
870 $this->mFollowPolicy
= $policy;
875 * Set the new value of the "action text", this will be added to the
876 * "HTML title", separated from it with " - ".
878 * @param string $text New value of the "action text"
880 public function setPageTitleActionText( $text ) {
881 $this->mPageTitleActionText
= $text;
885 * Get the value of the "action text"
889 public function getPageTitleActionText() {
890 return $this->mPageTitleActionText
;
894 * "HTML title" means the contents of "<title>".
895 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
897 * @param string|Message $name
899 public function setHTMLTitle( $name ) {
900 if ( $name instanceof Message
) {
901 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
903 $this->mHTMLtitle
= $name;
908 * Return the "HTML title", i.e. the content of the "<title>" tag.
912 public function getHTMLTitle() {
913 return $this->mHTMLtitle
;
917 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
921 public function setRedirectedFrom( $t ) {
922 $this->mRedirectedFrom
= $t;
926 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
927 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
928 * but not bad tags like \<script\>. This function automatically sets
929 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
930 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
931 * good tags like \<i\> will be dropped entirely.
933 * @param string|Message $name
935 public function setPageTitle( $name ) {
936 if ( $name instanceof Message
) {
937 $name = $name->setContext( $this->getContext() )->text();
940 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
941 # but leave "<i>foobar</i>" alone
942 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
943 $this->mPagetitle
= $nameWithTags;
945 # change "<i>foo&bar</i>" to "foo&bar"
947 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
948 ->inContentLanguage()
953 * Return the "page title", i.e. the content of the \<h1\> tag.
957 public function getPageTitle() {
958 return $this->mPagetitle
;
962 * Set the Title object to use
966 public function setTitle( Title
$t ) {
967 $this->getContext()->setTitle( $t );
971 * Replace the subtitle with $str
973 * @param string|Message $str New value of the subtitle. String should be safe HTML.
975 public function setSubtitle( $str ) {
976 $this->clearSubtitle();
977 $this->addSubtitle( $str );
981 * Add $str to the subtitle
983 * @deprecated since 1.19; use addSubtitle() instead
984 * @param string|Message $str String or Message to add to the subtitle
986 public function appendSubtitle( $str ) {
987 $this->addSubtitle( $str );
991 * Add $str to the subtitle
993 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
995 public function addSubtitle( $str ) {
996 if ( $str instanceof Message
) {
997 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
999 $this->mSubtitle
[] = $str;
1004 * Add a subtitle containing a backlink to a page
1006 * @param Title $title Title to link to
1007 * @param array $query Array of additional parameters to include in the link
1009 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1010 if ( $title->isRedirect() ) {
1011 $query['redirect'] = 'no';
1013 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1014 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1018 * Clear the subtitles
1020 public function clearSubtitle() {
1021 $this->mSubtitle
= array();
1029 public function getSubtitle() {
1030 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1034 * Set the page as printable, i.e. it'll be displayed with with all
1035 * print styles included
1037 public function setPrintable() {
1038 $this->mPrintable
= true;
1042 * Return whether the page is "printable"
1046 public function isPrintable() {
1047 return $this->mPrintable
;
1051 * Disable output completely, i.e. calling output() will have no effect
1053 public function disable() {
1054 $this->mDoNothing
= true;
1058 * Return whether the output will be completely disabled
1062 public function isDisabled() {
1063 return $this->mDoNothing
;
1067 * Show an "add new section" link?
1071 public function showNewSectionLink() {
1072 return $this->mNewSectionLink
;
1076 * Forcibly hide the new section link?
1080 public function forceHideNewSectionLink() {
1081 return $this->mHideNewSectionLink
;
1085 * Add or remove feed links in the page header
1086 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1087 * for the new version
1088 * @see addFeedLink()
1090 * @param bool $show True: add default feeds, false: remove all feeds
1092 public function setSyndicated( $show = true ) {
1094 $this->setFeedAppendQuery( false );
1096 $this->mFeedLinks
= array();
1101 * Add default feeds to the page header
1102 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1103 * for the new version
1104 * @see addFeedLink()
1106 * @param string $val Query to append to feed links or false to output
1109 public function setFeedAppendQuery( $val ) {
1110 global $wgAdvertisedFeedTypes;
1112 $this->mFeedLinks
= array();
1114 foreach ( $wgAdvertisedFeedTypes as $type ) {
1115 $query = "feed=$type";
1116 if ( is_string( $val ) ) {
1117 $query .= '&' . $val;
1119 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1124 * Add a feed link to the page header
1126 * @param string $format Feed type, should be a key of $wgFeedClasses
1127 * @param string $href URL
1129 public function addFeedLink( $format, $href ) {
1130 global $wgAdvertisedFeedTypes;
1132 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1133 $this->mFeedLinks
[$format] = $href;
1138 * Should we output feed links for this page?
1141 public function isSyndicated() {
1142 return count( $this->mFeedLinks
) > 0;
1146 * Return URLs for each supported syndication format for this page.
1147 * @return array Associating format keys with URLs
1149 public function getSyndicationLinks() {
1150 return $this->mFeedLinks
;
1154 * Will currently always return null
1158 public function getFeedAppendQuery() {
1159 return $this->mFeedLinksAppendQuery
;
1163 * Set whether the displayed content is related to the source of the
1164 * corresponding article on the wiki
1165 * Setting true will cause the change "article related" toggle to true
1169 public function setArticleFlag( $v ) {
1170 $this->mIsarticle
= $v;
1172 $this->mIsArticleRelated
= $v;
1177 * Return whether the content displayed page is related to the source of
1178 * the corresponding article on the wiki
1182 public function isArticle() {
1183 return $this->mIsarticle
;
1187 * Set whether this page is related an article on the wiki
1188 * Setting false will cause the change of "article flag" toggle to false
1192 public function setArticleRelated( $v ) {
1193 $this->mIsArticleRelated
= $v;
1195 $this->mIsarticle
= false;
1200 * Return whether this page is related an article on the wiki
1204 public function isArticleRelated() {
1205 return $this->mIsArticleRelated
;
1209 * Add new language links
1211 * @param array $newLinkArray Associative array mapping language code to the page
1214 public function addLanguageLinks( array $newLinkArray ) {
1215 $this->mLanguageLinks +
= $newLinkArray;
1219 * Reset the language links and add new language links
1221 * @param array $newLinkArray Associative array mapping language code to the page
1224 public function setLanguageLinks( array $newLinkArray ) {
1225 $this->mLanguageLinks
= $newLinkArray;
1229 * Get the list of language links
1231 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1233 public function getLanguageLinks() {
1234 return $this->mLanguageLinks
;
1238 * Add an array of categories, with names in the keys
1240 * @param array $categories Mapping category name => sort key
1242 public function addCategoryLinks( array $categories ) {
1243 global $wgContLang, $wgContentHandlerUseDB;
1245 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1249 # Add the links to a LinkBatch
1250 $arr = array( NS_CATEGORY
=> $categories );
1251 $lb = new LinkBatch
;
1252 $lb->setArray( $arr );
1254 # Fetch existence plus the hiddencat property
1255 $dbr = wfGetDB( DB_SLAVE
);
1256 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1257 'page_is_redirect', 'page_latest', 'pp_value' );
1259 if ( $wgContentHandlerUseDB ) {
1260 $fields[] = 'page_content_model';
1263 $res = $dbr->select( array( 'page', 'page_props' ),
1265 $lb->constructSet( 'page', $dbr ),
1268 array( 'page_props' => array( 'LEFT JOIN', array(
1269 'pp_propname' => 'hiddencat',
1274 # Add the results to the link cache
1275 $lb->addResultToCache( LinkCache
::singleton(), $res );
1277 # Set all the values to 'normal'.
1278 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1280 # Mark hidden categories
1281 foreach ( $res as $row ) {
1282 if ( isset( $row->pp_value
) ) {
1283 $categories[$row->page_title
] = 'hidden';
1287 # Add the remaining categories to the skin
1289 'OutputPageMakeCategoryLinks',
1290 array( &$this, $categories, &$this->mCategoryLinks
) )
1292 foreach ( $categories as $category => $type ) {
1293 $origcategory = $category;
1294 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1298 $wgContLang->findVariantLink( $category, $title, true );
1299 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1302 $text = $wgContLang->convertHtml( $title->getText() );
1303 $this->mCategories
[] = $title->getText();
1304 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1310 * Reset the category links (but not the category list) and add $categories
1312 * @param array $categories Mapping category name => sort key
1314 public function setCategoryLinks( array $categories ) {
1315 $this->mCategoryLinks
= array();
1316 $this->addCategoryLinks( $categories );
1320 * Get the list of category links, in a 2-D array with the following format:
1321 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1322 * hidden categories) and $link a HTML fragment with a link to the category
1327 public function getCategoryLinks() {
1328 return $this->mCategoryLinks
;
1332 * Get the list of category names this page belongs to
1334 * @return array Array of strings
1336 public function getCategories() {
1337 return $this->mCategories
;
1341 * Do not allow scripts which can be modified by wiki users to load on this page;
1342 * only allow scripts bundled with, or generated by, the software.
1344 public function disallowUserJs() {
1345 $this->reduceAllowedModules(
1346 ResourceLoaderModule
::TYPE_SCRIPTS
,
1347 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1352 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1353 * @see ResourceLoaderModule::$origin
1354 * @param string $type ResourceLoaderModule TYPE_ constant
1355 * @return int ResourceLoaderModule ORIGIN_ class constant
1357 public function getAllowedModules( $type ) {
1358 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1359 return min( array_values( $this->mAllowedModules
) );
1361 return isset( $this->mAllowedModules
[$type] )
1362 ?
$this->mAllowedModules
[$type]
1363 : ResourceLoaderModule
::ORIGIN_ALL
;
1368 * Set the highest level of CSS/JS untrustworthiness allowed
1369 * @param string $type ResourceLoaderModule TYPE_ constant
1370 * @param int $level ResourceLoaderModule class constant
1372 public function setAllowedModules( $type, $level ) {
1373 $this->mAllowedModules
[$type] = $level;
1377 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1378 * @param string $type
1379 * @param int $level ResourceLoaderModule class constant
1381 public function reduceAllowedModules( $type, $level ) {
1382 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1386 * Prepend $text to the body HTML
1388 * @param string $text HTML
1390 public function prependHTML( $text ) {
1391 $this->mBodytext
= $text . $this->mBodytext
;
1395 * Append $text to the body HTML
1397 * @param string $text HTML
1399 public function addHTML( $text ) {
1400 $this->mBodytext
.= $text;
1404 * Shortcut for adding an Html::element via addHTML.
1408 * @param string $element
1409 * @param array $attribs
1410 * @param string $contents
1412 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1413 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1417 * Clear the body HTML
1419 public function clearHTML() {
1420 $this->mBodytext
= '';
1426 * @return string HTML
1428 public function getHTML() {
1429 return $this->mBodytext
;
1433 * Get/set the ParserOptions object to use for wikitext parsing
1435 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1436 * current ParserOption object
1437 * @return ParserOptions
1439 public function parserOptions( $options = null ) {
1440 if ( !$this->mParserOptions
) {
1441 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1442 $this->mParserOptions
->setEditSection( false );
1444 return wfSetVar( $this->mParserOptions
, $options );
1448 * Set the revision ID which will be seen by the wiki text parser
1449 * for things such as embedded {{REVISIONID}} variable use.
1451 * @param int|null $revid An positive integer, or null
1452 * @return mixed Previous value
1454 public function setRevisionId( $revid ) {
1455 $val = is_null( $revid ) ?
null : intval( $revid );
1456 return wfSetVar( $this->mRevisionId
, $val );
1460 * Get the displayed revision ID
1464 public function getRevisionId() {
1465 return $this->mRevisionId
;
1469 * Set the timestamp of the revision which will be displayed. This is used
1470 * to avoid a extra DB call in Skin::lastModified().
1472 * @param string|null $timestamp
1473 * @return mixed Previous value
1475 public function setRevisionTimestamp( $timestamp ) {
1476 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1480 * Get the timestamp of displayed revision.
1481 * This will be null if not filled by setRevisionTimestamp().
1483 * @return string|null
1485 public function getRevisionTimestamp() {
1486 return $this->mRevisionTimestamp
;
1490 * Set the displayed file version
1492 * @param File|bool $file
1493 * @return mixed Previous value
1495 public function setFileVersion( $file ) {
1497 if ( $file instanceof File
&& $file->exists() ) {
1498 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1500 return wfSetVar( $this->mFileVersion
, $val, true );
1504 * Get the displayed file version
1506 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1508 public function getFileVersion() {
1509 return $this->mFileVersion
;
1513 * Get the templates used on this page
1515 * @return array (namespace => dbKey => revId)
1518 public function getTemplateIds() {
1519 return $this->mTemplateIds
;
1523 * Get the files used on this page
1525 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1528 public function getFileSearchOptions() {
1529 return $this->mImageTimeKeys
;
1533 * Convert wikitext to HTML and add it to the buffer
1534 * Default assumes that the current page title will be used.
1536 * @param string $text
1537 * @param bool $linestart Is this the start of a line?
1538 * @param bool $interface Is this text in the user interface language?
1540 public function addWikiText( $text, $linestart = true, $interface = true ) {
1541 $title = $this->getTitle(); // Work around E_STRICT
1543 throw new MWException( 'Title is null' );
1545 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1549 * Add wikitext with a custom Title object
1551 * @param string $text Wikitext
1552 * @param Title $title
1553 * @param bool $linestart Is this the start of a line?
1555 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1556 $this->addWikiTextTitle( $text, $title, $linestart );
1560 * Add wikitext with a custom Title object and tidy enabled.
1562 * @param string $text Wikitext
1563 * @param Title $title
1564 * @param bool $linestart Is this the start of a line?
1566 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1567 $this->addWikiTextTitle( $text, $title, $linestart, true );
1571 * Add wikitext with tidy enabled
1573 * @param string $text Wikitext
1574 * @param bool $linestart Is this the start of a line?
1576 public function addWikiTextTidy( $text, $linestart = true ) {
1577 $title = $this->getTitle();
1578 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1582 * Add wikitext with a custom Title object
1584 * @param string $text Wikitext
1585 * @param Title $title
1586 * @param bool $linestart Is this the start of a line?
1587 * @param bool $tidy Whether to use tidy
1588 * @param bool $interface Whether it is an interface message
1589 * (for example disables conversion)
1591 public function addWikiTextTitle( $text, Title
$title, $linestart,
1592 $tidy = false, $interface = false
1596 wfProfileIn( __METHOD__
);
1598 $popts = $this->parserOptions();
1599 $oldTidy = $popts->setTidy( $tidy );
1600 $popts->setInterfaceMessage( (bool)$interface );
1602 $parserOutput = $wgParser->getFreshParser()->parse(
1603 $text, $title, $popts,
1604 $linestart, true, $this->mRevisionId
1607 $popts->setTidy( $oldTidy );
1609 $this->addParserOutput( $parserOutput );
1611 wfProfileOut( __METHOD__
);
1615 * Add a ParserOutput object, but without Html.
1617 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1618 * @param ParserOutput $parserOutput
1620 public function addParserOutputNoText( &$parserOutput ) {
1621 $this->addParserOutputMetadata( $parserOutput );
1625 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1626 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1630 * @param ParserOutput $parserOutput
1632 public function addParserOutputMetadata( &$parserOutput ) {
1633 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1634 $this->addCategoryLinks( $parserOutput->getCategories() );
1635 $this->mNewSectionLink
= $parserOutput->getNewSection();
1636 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1638 $this->mParseWarnings
= $parserOutput->getWarnings();
1639 if ( !$parserOutput->isCacheable() ) {
1640 $this->enableClientCache( false );
1642 $this->mNoGallery
= $parserOutput->getNoGallery();
1643 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1644 $this->addModules( $parserOutput->getModules() );
1645 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1646 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1647 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1648 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1649 $this->mPreventClickjacking
= $this->mPreventClickjacking
1650 ||
$parserOutput->preventClickjacking();
1652 // Template versioning...
1653 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1654 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1655 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1657 $this->mTemplateIds
[$ns] = $dbks;
1660 // File versioning...
1661 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1662 $this->mImageTimeKeys
[$dbk] = $data;
1665 // Hooks registered in the object
1666 global $wgParserOutputHooks;
1667 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1668 list( $hookName, $data ) = $hookInfo;
1669 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1670 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1674 // Link flags are ignored for now, but may in the future be
1675 // used to mark individual language links.
1676 $linkFlags = array();
1677 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1678 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1682 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1683 * ParserOutput object, without any other metadata.
1686 * @param ParserOutput $parserOutput
1688 public function addParserOutputContent( &$parserOutput ) {
1689 $this->addParserOutputText( $parserOutput );
1691 $this->addModules( $parserOutput->getModules() );
1692 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1693 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1694 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1696 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1700 * Add the HTML associated with a ParserOutput object, without any metadata.
1703 * @param ParserOutput $parserOutput
1705 public function addParserOutputText( &$parserOutput ) {
1706 $text = $parserOutput->getText();
1707 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1708 $this->addHTML( $text );
1712 * Add everything from a ParserOutput object.
1714 * @param ParserOutput $parserOutput
1716 function addParserOutput( &$parserOutput ) {
1717 $this->addParserOutputMetadata( $parserOutput );
1718 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1720 // Touch section edit links only if not previously disabled
1721 if ( $parserOutput->getEditSectionTokens() ) {
1722 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1725 $this->addParserOutputText( $parserOutput );
1729 * Add the output of a QuickTemplate to the output buffer
1731 * @param QuickTemplate $template
1733 public function addTemplate( &$template ) {
1734 $this->addHTML( $template->getHTML() );
1738 * Parse wikitext and return the HTML.
1740 * @param string $text
1741 * @param bool $linestart Is this the start of a line?
1742 * @param bool $interface Use interface language ($wgLang instead of
1743 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1744 * This also disables LanguageConverter.
1745 * @param Language $language Target language object, will override $interface
1746 * @throws MWException
1747 * @return string HTML
1749 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1752 if ( is_null( $this->getTitle() ) ) {
1753 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1756 $popts = $this->parserOptions();
1758 $popts->setInterfaceMessage( true );
1760 if ( $language !== null ) {
1761 $oldLang = $popts->setTargetLanguage( $language );
1764 $parserOutput = $wgParser->getFreshParser()->parse(
1765 $text, $this->getTitle(), $popts,
1766 $linestart, true, $this->mRevisionId
1770 $popts->setInterfaceMessage( false );
1772 if ( $language !== null ) {
1773 $popts->setTargetLanguage( $oldLang );
1776 return $parserOutput->getText();
1780 * Parse wikitext, strip paragraphs, and return the HTML.
1782 * @param string $text
1783 * @param bool $linestart Is this the start of a line?
1784 * @param bool $interface Use interface language ($wgLang instead of
1785 * $wgContLang) while parsing language sensitive magic
1786 * words like GRAMMAR and PLURAL
1787 * @return string HTML
1789 public function parseInline( $text, $linestart = true, $interface = false ) {
1790 $parsed = $this->parse( $text, $linestart, $interface );
1791 return Parser
::stripOuterParagraph( $parsed );
1795 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1797 * @param int $maxage Maximum cache time on the Squid, in seconds.
1799 public function setSquidMaxage( $maxage ) {
1800 $this->mSquidMaxage
= $maxage;
1804 * Use enableClientCache(false) to force it to send nocache headers
1806 * @param bool $state
1810 public function enableClientCache( $state ) {
1811 return wfSetVar( $this->mEnableClientCache
, $state );
1815 * Get the list of cookies that will influence on the cache
1819 function getCacheVaryCookies() {
1820 global $wgCookiePrefix, $wgCacheVaryCookies;
1822 if ( $cookies === null ) {
1823 $cookies = array_merge(
1825 "{$wgCookiePrefix}Token",
1826 "{$wgCookiePrefix}LoggedOut",
1832 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1838 * Check if the request has a cache-varying cookie header
1839 * If it does, it's very important that we don't allow public caching
1843 function haveCacheVaryCookies() {
1844 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1845 if ( $cookieHeader === false ) {
1848 $cvCookies = $this->getCacheVaryCookies();
1849 foreach ( $cvCookies as $cookieName ) {
1850 # Check for a simple string match, like the way squid does it
1851 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1852 wfDebug( __METHOD__
. ": found $cookieName\n" );
1856 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1861 * Add an HTTP header that will influence on the cache
1863 * @param string $header Header name
1864 * @param array|null $option
1865 * @todo FIXME: Document the $option parameter; it appears to be for
1866 * X-Vary-Options but what format is acceptable?
1868 public function addVaryHeader( $header, $option = null ) {
1869 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1870 $this->mVaryHeader
[$header] = (array)$option;
1871 } elseif ( is_array( $option ) ) {
1872 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1873 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1875 $this->mVaryHeader
[$header] = $option;
1878 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1882 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1883 * such as Accept-Encoding or Cookie
1887 public function getVaryHeader() {
1888 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1892 * Get a complete X-Vary-Options header
1896 public function getXVO() {
1897 $cvCookies = $this->getCacheVaryCookies();
1899 $cookiesOption = array();
1900 foreach ( $cvCookies as $cookieName ) {
1901 $cookiesOption[] = 'string-contains=' . $cookieName;
1903 $this->addVaryHeader( 'Cookie', $cookiesOption );
1906 foreach ( $this->mVaryHeader
as $header => $option ) {
1907 $newheader = $header;
1908 if ( is_array( $option ) && count( $option ) > 0 ) {
1909 $newheader .= ';' . implode( ';', $option );
1911 $headers[] = $newheader;
1913 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1919 * bug 21672: Add Accept-Language to Vary and XVO headers
1920 * if there's no 'variant' parameter existed in GET.
1923 * /w/index.php?title=Main_page should always be served; but
1924 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1926 function addAcceptLanguage() {
1927 $title = $this->getTitle();
1928 if ( !$title instanceof Title
) {
1932 $lang = $title->getPageLanguage();
1933 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1934 $variants = $lang->getVariants();
1935 $aloption = array();
1936 foreach ( $variants as $variant ) {
1937 if ( $variant === $lang->getCode() ) {
1940 $aloption[] = 'string-contains=' . $variant;
1942 // IE and some other browsers use BCP 47 standards in
1943 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1944 // We should handle these too.
1945 $variantBCP47 = wfBCP47( $variant );
1946 if ( $variantBCP47 !== $variant ) {
1947 $aloption[] = 'string-contains=' . $variantBCP47;
1951 $this->addVaryHeader( 'Accept-Language', $aloption );
1956 * Set a flag which will cause an X-Frame-Options header appropriate for
1957 * edit pages to be sent. The header value is controlled by
1958 * $wgEditPageFrameOptions.
1960 * This is the default for special pages. If you display a CSRF-protected
1961 * form on an ordinary view page, then you need to call this function.
1963 * @param bool $enable
1965 public function preventClickjacking( $enable = true ) {
1966 $this->mPreventClickjacking
= $enable;
1970 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1971 * This can be called from pages which do not contain any CSRF-protected
1974 public function allowClickjacking() {
1975 $this->mPreventClickjacking
= false;
1979 * Get the prevent-clickjacking flag
1984 public function getPreventClickjacking() {
1985 return $this->mPreventClickjacking
;
1989 * Get the X-Frame-Options header value (without the name part), or false
1990 * if there isn't one. This is used by Skin to determine whether to enable
1991 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1995 public function getFrameOptions() {
1996 global $wgBreakFrames, $wgEditPageFrameOptions;
1997 if ( $wgBreakFrames ) {
1999 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
2000 return $wgEditPageFrameOptions;
2006 * Send cache control HTTP headers
2008 public function sendCacheControl() {
2009 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
2011 $response = $this->getRequest()->response();
2012 if ( $wgUseETag && $this->mETag
) {
2013 $response->header( "ETag: $this->mETag" );
2016 $this->addVaryHeader( 'Cookie' );
2017 $this->addAcceptLanguage();
2019 # don't serve compressed data to clients who can't handle it
2020 # maintain different caches for logged-in users and non-logged in ones
2021 $response->header( $this->getVaryHeader() );
2024 # Add an X-Vary-Options header for Squid with Wikimedia patches
2025 $response->header( $this->getXVO() );
2028 if ( $this->mEnableClientCache
) {
2030 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
2031 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2034 # We'll purge the proxy cache explicitly, but require end user agents
2035 # to revalidate against the proxy on each visit.
2036 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2037 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2038 # start with a shorter timeout for initial testing
2039 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2040 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage
2041 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2042 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2044 # We'll purge the proxy cache for anons explicitly, but require end user agents
2045 # to revalidate against the proxy on each visit.
2046 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2047 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2048 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2049 # start with a shorter timeout for initial testing
2050 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2051 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2052 . ', must-revalidate, max-age=0' );
2055 # We do want clients to cache if they can, but they *must* check for updates
2056 # on revisiting the page.
2057 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2058 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2059 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2061 if ( $this->mLastModified
) {
2062 $response->header( "Last-Modified: {$this->mLastModified}" );
2065 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2067 # In general, the absence of a last modified header should be enough to prevent
2068 # the client from using its cache. We send a few other things just to make sure.
2069 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2070 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2071 $response->header( 'Pragma: no-cache' );
2076 * Finally, all the text has been munged and accumulated into
2077 * the object, let's actually output it:
2079 public function output() {
2080 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
2081 $wgResponsiveImages;
2083 if ( $this->mDoNothing
) {
2087 wfProfileIn( __METHOD__
);
2089 $response = $this->getRequest()->response();
2091 if ( $this->mRedirect
!= '' ) {
2092 # Standards require redirect URLs to be absolute
2093 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2095 $redirect = $this->mRedirect
;
2096 $code = $this->mRedirectCode
;
2098 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2099 if ( $code == '301' ||
$code == '303' ) {
2100 if ( !$wgDebugRedirects ) {
2101 $message = HttpStatus
::getMessage( $code );
2102 $response->header( "HTTP/1.1 $code $message" );
2104 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2106 if ( $wgVaryOnXFP ) {
2107 $this->addVaryHeader( 'X-Forwarded-Proto' );
2109 $this->sendCacheControl();
2111 $response->header( "Content-Type: text/html; charset=utf-8" );
2112 if ( $wgDebugRedirects ) {
2113 $url = htmlspecialchars( $redirect );
2114 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2115 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2116 print "</body>\n</html>\n";
2118 $response->header( 'Location: ' . $redirect );
2122 wfProfileOut( __METHOD__
);
2124 } elseif ( $this->mStatusCode
) {
2125 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2127 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2131 # Buffer output; final headers may depend on later processing
2134 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2135 $response->header( 'Content-language: ' . $wgLanguageCode );
2137 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2138 // jQuery etc. can work correctly.
2139 $response->header( 'X-UA-Compatible: IE=Edge' );
2141 // Prevent framing, if requested
2142 $frameOptions = $this->getFrameOptions();
2143 if ( $frameOptions ) {
2144 $response->header( "X-Frame-Options: $frameOptions" );
2147 if ( $this->mArticleBodyOnly
) {
2148 echo $this->mBodytext
;
2151 $sk = $this->getSkin();
2152 // add skin specific modules
2153 $modules = $sk->getDefaultModules();
2155 // enforce various default modules for all skins
2156 $coreModules = array(
2157 // keep this list as small as possible
2158 'mediawiki.page.startup',
2162 // Support for high-density display images if enabled
2163 if ( $wgResponsiveImages ) {
2164 $coreModules[] = 'mediawiki.hidpi';
2167 $this->addModules( $coreModules );
2168 foreach ( $modules as $group ) {
2169 $this->addModules( $group );
2171 MWDebug
::addModules( $this );
2173 // Hook that allows last minute changes to the output page, e.g.
2174 // adding of CSS or Javascript by extensions.
2175 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2177 wfProfileIn( 'Output-skin' );
2179 wfProfileOut( 'Output-skin' );
2182 // This hook allows last minute changes to final overall output by modifying output buffer
2183 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2185 $this->sendCacheControl();
2189 wfProfileOut( __METHOD__
);
2193 * Actually output something with print.
2195 * @param string $ins The string to output
2196 * @deprecated since 1.22 Use echo yourself.
2198 public function out( $ins ) {
2199 wfDeprecated( __METHOD__
, '1.22' );
2204 * Produce a "user is blocked" page.
2205 * @deprecated since 1.18
2207 function blockedPage() {
2208 throw new UserBlockedError( $this->getUser()->mBlock
);
2212 * Prepare this object to display an error page; disable caching and
2213 * indexing, clear the current text and redirect, set the page's title
2214 * and optionally an custom HTML title (content of the "<title>" tag).
2216 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2217 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2218 * optional, if not passed the "<title>" attribute will be
2219 * based on $pageTitle
2221 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2222 $this->setPageTitle( $pageTitle );
2223 if ( $htmlTitle !== false ) {
2224 $this->setHTMLTitle( $htmlTitle );
2226 $this->setRobotPolicy( 'noindex,nofollow' );
2227 $this->setArticleRelated( false );
2228 $this->enableClientCache( false );
2229 $this->mRedirect
= '';
2230 $this->clearSubtitle();
2235 * Output a standard error page
2237 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2238 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2239 * showErrorPage( 'titlemsg', $messageObject );
2240 * showErrorPage( $titleMessageObject, $messageObject );
2242 * @param string|Message $title Message key (string) for page title, or a Message object
2243 * @param string|Message $msg Message key (string) for page text, or a Message object
2244 * @param array $params Message parameters; ignored if $msg is a Message object
2246 public function showErrorPage( $title, $msg, $params = array() ) {
2247 if ( !$title instanceof Message
) {
2248 $title = $this->msg( $title );
2251 $this->prepareErrorPage( $title );
2253 if ( $msg instanceof Message
) {
2254 if ( $params !== array() ) {
2255 trigger_error( 'Argument ignored: $params. The message parameters argument '
2256 . 'is discarded when the $msg argument is a Message object instead of '
2257 . 'a string.', E_USER_NOTICE
);
2259 $this->addHTML( $msg->parseAsBlock() );
2261 $this->addWikiMsgArray( $msg, $params );
2264 $this->returnToMain();
2268 * Output a standard permission error page
2270 * @param array $errors Error message keys
2271 * @param string $action Action that was denied or null if unknown
2273 public function showPermissionsErrorPage( array $errors, $action = null ) {
2274 // For some action (read, edit, create and upload), display a "login to do this action"
2275 // error if all of the following conditions are met:
2276 // 1. the user is not logged in
2277 // 2. the only error is insufficient permissions (i.e. no block or something else)
2278 // 3. the error can be avoided simply by logging in
2279 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2280 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2281 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2282 && ( User
::groupHasPermission( 'user', $action )
2283 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2285 $displayReturnto = null;
2287 # Due to bug 32276, if a user does not have read permissions,
2288 # $this->getTitle() will just give Special:Badtitle, which is
2289 # not especially useful as a returnto parameter. Use the title
2290 # from the request instead, if there was one.
2291 $request = $this->getRequest();
2292 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2293 if ( $action == 'edit' ) {
2294 $msg = 'whitelistedittext';
2295 $displayReturnto = $returnto;
2296 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2297 $msg = 'nocreatetext';
2298 } elseif ( $action == 'upload' ) {
2299 $msg = 'uploadnologintext';
2301 $msg = 'loginreqpagetext';
2302 $displayReturnto = Title
::newMainPage();
2308 $query['returnto'] = $returnto->getPrefixedText();
2310 if ( !$request->wasPosted() ) {
2311 $returntoquery = $request->getValues();
2312 unset( $returntoquery['title'] );
2313 unset( $returntoquery['returnto'] );
2314 unset( $returntoquery['returntoquery'] );
2315 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2318 $loginLink = Linker
::linkKnown(
2319 SpecialPage
::getTitleFor( 'Userlogin' ),
2320 $this->msg( 'loginreqlink' )->escaped(),
2325 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2326 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2328 # Don't return to a page the user can't read otherwise
2329 # we'll end up in a pointless loop
2330 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2331 $this->returnToMain( null, $displayReturnto );
2334 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2335 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2340 * Display an error page indicating that a given version of MediaWiki is
2341 * required to use it
2343 * @param mixed $version The version of MediaWiki needed to use the page
2345 public function versionRequired( $version ) {
2346 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2348 $this->addWikiMsg( 'versionrequiredtext', $version );
2349 $this->returnToMain();
2353 * Display an error page noting that a given permission bit is required.
2354 * @deprecated since 1.18, just throw the exception directly
2355 * @param string $permission Key required
2356 * @throws PermissionsError
2358 public function permissionRequired( $permission ) {
2359 throw new PermissionsError( $permission );
2363 * Produce the stock "please login to use the wiki" page
2365 * @deprecated since 1.19; throw the exception directly
2367 public function loginToUse() {
2368 throw new PermissionsError( 'read' );
2372 * Format a list of error messages
2374 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2375 * @param string $action Action that was denied or null if unknown
2376 * @return string The wikitext error-messages, formatted into a list.
2378 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2379 if ( $action == null ) {
2380 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2382 $action_desc = $this->msg( "action-$action" )->plain();
2384 'permissionserrorstext-withaction',
2387 )->plain() . "\n\n";
2390 if ( count( $errors ) > 1 ) {
2391 $text .= '<ul class="permissions-errors">' . "\n";
2393 foreach ( $errors as $error ) {
2395 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2400 $text .= "<div class=\"permissions-errors\">\n" .
2401 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2409 * Display a page stating that the Wiki is in read-only mode,
2410 * and optionally show the source of the page that the user
2411 * was trying to edit. Should only be called (for this
2412 * purpose) after wfReadOnly() has returned true.
2414 * For historical reasons, this function is _also_ used to
2415 * show the error message when a user tries to edit a page
2416 * they are not allowed to edit. (Unless it's because they're
2417 * blocked, then we show blockedPage() instead.) In this
2418 * case, the second parameter should be set to true and a list
2419 * of reasons supplied as the third parameter.
2421 * @todo Needs to be split into multiple functions.
2423 * @param string $source Source code to show (or null).
2424 * @param bool $protected Is this a permissions error?
2425 * @param array $reasons List of reasons for this error, as returned by
2426 * Title::getUserPermissionsErrors().
2427 * @param string $action Action that was denied or null if unknown
2428 * @throws ReadOnlyError
2430 public function readOnlyPage( $source = null, $protected = false,
2431 array $reasons = array(), $action = null
2433 $this->setRobotPolicy( 'noindex,nofollow' );
2434 $this->setArticleRelated( false );
2436 // If no reason is given, just supply a default "I can't let you do
2437 // that, Dave" message. Should only occur if called by legacy code.
2438 if ( $protected && empty( $reasons ) ) {
2439 $reasons[] = array( 'badaccess-group0' );
2442 if ( !empty( $reasons ) ) {
2443 // Permissions error
2445 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2446 $this->addBacklinkSubtitle( $this->getTitle() );
2448 $this->setPageTitle( $this->msg( 'badaccess' ) );
2450 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2452 // Wiki is read only
2453 throw new ReadOnlyError
;
2456 // Show source, if supplied
2457 if ( is_string( $source ) ) {
2458 $this->addWikiMsg( 'viewsourcetext' );
2460 $pageLang = $this->getTitle()->getPageLanguage();
2462 'id' => 'wpTextbox1',
2463 'name' => 'wpTextbox1',
2464 'cols' => $this->getUser()->getOption( 'cols' ),
2465 'rows' => $this->getUser()->getOption( 'rows' ),
2466 'readonly' => 'readonly',
2467 'lang' => $pageLang->getHtmlCode(),
2468 'dir' => $pageLang->getDir(),
2470 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2472 // Show templates used by this article
2473 $templates = Linker
::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2474 $this->addHTML( "<div class='templatesUsed'>
2480 # If the title doesn't exist, it's fairly pointless to print a return
2481 # link to it. After all, you just tried editing it and couldn't, so
2482 # what's there to do there?
2483 if ( $this->getTitle()->exists() ) {
2484 $this->returnToMain( null, $this->getTitle() );
2489 * Turn off regular page output and return an error response
2490 * for when rate limiting has triggered.
2492 public function rateLimited() {
2493 throw new ThrottledError
;
2497 * Show a warning about slave lag
2499 * If the lag is higher than $wgSlaveLagCritical seconds,
2500 * then the warning is a bit more obvious. If the lag is
2501 * lower than $wgSlaveLagWarning, then no warning is shown.
2503 * @param int $lag Slave lag
2505 public function showLagWarning( $lag ) {
2506 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2507 if ( $lag >= $wgSlaveLagWarning ) {
2508 $message = $lag < $wgSlaveLagCritical
2511 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2512 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2516 public function showFatalError( $message ) {
2517 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2519 $this->addHTML( $message );
2522 public function showUnexpectedValueError( $name, $val ) {
2523 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2526 public function showFileCopyError( $old, $new ) {
2527 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2530 public function showFileRenameError( $old, $new ) {
2531 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2534 public function showFileDeleteError( $name ) {
2535 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2538 public function showFileNotFoundError( $name ) {
2539 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2543 * Add a "return to" link pointing to a specified title
2545 * @param Title $title Title to link
2546 * @param array $query Query string parameters
2547 * @param string $text Text of the link (input is not escaped)
2548 * @param array $options Options array to pass to Linker
2550 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2551 $link = $this->msg( 'returnto' )->rawParams(
2552 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2553 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2557 * Add a "return to" link pointing to a specified title,
2558 * or the title indicated in the request, or else the main page
2560 * @param mixed $unused
2561 * @param Title|string $returnto Title or String to return to
2562 * @param string $returntoquery Query string for the return to link
2564 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2565 if ( $returnto == null ) {
2566 $returnto = $this->getRequest()->getText( 'returnto' );
2569 if ( $returntoquery == null ) {
2570 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2573 if ( $returnto === '' ) {
2574 $returnto = Title
::newMainPage();
2577 if ( is_object( $returnto ) ) {
2578 $titleObj = $returnto;
2580 $titleObj = Title
::newFromText( $returnto );
2582 if ( !is_object( $titleObj ) ) {
2583 $titleObj = Title
::newMainPage();
2586 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2590 * @param Skin $sk The given Skin
2591 * @param bool $includeStyle Unused
2592 * @return string The doctype, opening "<html>", and head element.
2594 public function headElement( Skin
$sk, $includeStyle = true ) {
2595 global $wgContLang, $wgMimeType;
2597 $userdir = $this->getLanguage()->getDir();
2598 $sitedir = $wgContLang->getDir();
2600 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2602 if ( $this->getHTMLTitle() == '' ) {
2603 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2606 $openHead = Html
::openElement( 'head' );
2608 # Don't bother with the newline if $head == ''
2609 $ret .= "$openHead\n";
2612 if ( !Html
::isXmlMimeType( $wgMimeType ) ) {
2613 // Add <meta charset="UTF-8">
2614 // This should be before <title> since it defines the charset used by
2615 // text including the text inside <title>.
2616 // The spec recommends defining XHTML5's charset using the XML declaration
2618 // Our XML declaration is output by Html::htmlHeader.
2619 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2620 // http://www.whatwg.org/html/semantics.html#charset
2621 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2624 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2626 foreach ( $this->getHeadLinksArray() as $item ) {
2627 $ret .= $item . "\n";
2630 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2631 $ret .= $this->buildCssLinks();
2633 $ret .= $this->getHeadScripts() . "\n";
2635 foreach ( $this->mHeadItems
as $item ) {
2636 $ret .= $item . "\n";
2639 $closeHead = Html
::closeElement( 'head' );
2641 $ret .= "$closeHead\n";
2644 $bodyClasses = array();
2645 $bodyClasses[] = 'mediawiki';
2647 # Classes for LTR/RTL directionality support
2648 $bodyClasses[] = $userdir;
2649 $bodyClasses[] = "sitedir-$sitedir";
2651 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2652 # A <body> class is probably not the best way to do this . . .
2653 $bodyClasses[] = 'capitalize-all-nouns';
2656 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2657 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2659 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2661 $bodyAttrs = array();
2662 // While the implode() is not strictly needed, it's used for backwards compatibility
2663 // (this used to be built as a string and hooks likely still expect that).
2664 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2666 // Allow skins and extensions to add body attributes they need
2667 $sk->addToBodyAttributes( $this, $bodyAttrs );
2668 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2670 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2676 * Get a ResourceLoader object associated with this OutputPage
2678 * @return ResourceLoader
2680 public function getResourceLoader() {
2681 if ( is_null( $this->mResourceLoader
) ) {
2682 $this->mResourceLoader
= new ResourceLoader();
2684 return $this->mResourceLoader
;
2689 * @param array|string $modules One or more module names
2690 * @param string $only ResourceLoaderModule TYPE_ class constant
2691 * @param bool $useESI
2692 * @param array $extraQuery Array with extra query parameters to add to each
2693 * request. array( param => value ).
2694 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2695 * call rather than a "<script src='...'>" tag.
2696 * @return string The html "<script>", "<link>" and "<style>" tags
2698 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2699 array $extraQuery = array(), $loadCall = false
2701 global $wgResourceLoaderUseESI;
2703 $modules = (array)$modules;
2707 'states' => array(),
2710 if ( !count( $modules ) ) {
2714 if ( count( $modules ) > 1 ) {
2715 // Remove duplicate module requests
2716 $modules = array_unique( $modules );
2717 // Sort module names so requests are more uniform
2720 if ( ResourceLoader
::inDebugMode() ) {
2721 // Recursively call us for every item
2722 foreach ( $modules as $name ) {
2723 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2724 $links['html'] .= $link['html'];
2725 $links['states'] +
= $link['states'];
2731 if ( !is_null( $this->mTarget
) ) {
2732 $extraQuery['target'] = $this->mTarget
;
2735 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2736 $sortedModules = array();
2737 $resourceLoader = $this->getResourceLoader();
2738 foreach ( $modules as $name ) {
2739 $module = $resourceLoader->getModule( $name );
2740 # Check that we're allowed to include this module on this page
2742 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2743 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2744 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2745 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2746 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2747 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2748 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2753 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2756 foreach ( $sortedModules as $source => $groups ) {
2757 foreach ( $groups as $group => $grpModules ) {
2758 // Special handling for user-specific groups
2760 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2761 $user = $this->getUser()->getName();
2764 // Create a fake request based on the one we are about to make so modules return
2765 // correct timestamp and emptiness data
2766 $query = ResourceLoader
::makeLoaderQuery(
2767 array(), // modules; not determined yet
2768 $this->getLanguage()->getCode(),
2769 $this->getSkin()->getSkinName(),
2771 null, // version; not determined yet
2772 ResourceLoader
::inDebugMode(),
2773 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2774 $this->isPrintable(),
2775 $this->getRequest()->getBool( 'handheld' ),
2778 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2780 // Extract modules that know they're empty
2781 foreach ( $grpModules as $key => $module ) {
2782 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2783 // If we're only getting the styles, we don't need to do anything for empty modules.
2784 if ( $module->isKnownEmpty( $context ) ) {
2785 unset( $grpModules[$key] );
2786 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2787 $links['states'][$key] = 'ready';
2792 // If there are no non-empty modules, skip this group
2793 if ( count( $grpModules ) === 0 ) {
2797 // Inline private modules. These can't be loaded through load.php for security
2798 // reasons, see bug 34907. Note that these modules should be loaded from
2799 // getHeadScripts() before the first loader call. Otherwise other modules can't
2800 // properly use them as dependencies (bug 30914)
2801 if ( $group === 'private' ) {
2802 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2803 $links['html'] .= Html
::inlineStyle(
2804 $resourceLoader->makeModuleResponse( $context, $grpModules )
2807 $links['html'] .= Html
::inlineScript(
2808 $resourceLoader->makeModuleResponse( $context, $grpModules )
2811 $links['html'] .= "\n";
2815 // Special handling for the user group; because users might change their stuff
2816 // on-wiki like user pages, or user preferences; we need to find the highest
2817 // timestamp of these user-changeable modules so we can ensure cache misses on change
2818 // This should NOT be done for the site group (bug 27564) because anons get that too
2819 // and we shouldn't be putting timestamps in Squid-cached HTML
2821 if ( $group === 'user' ) {
2822 // Get the maximum timestamp
2824 foreach ( $grpModules as $module ) {
2825 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2827 // Add a version parameter so cache will break when things change
2828 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2831 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2832 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2833 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2835 if ( $useESI && $wgResourceLoaderUseESI ) {
2836 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2837 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2838 $link = Html
::inlineStyle( $esi );
2840 $link = Html
::inlineScript( $esi );
2843 // Automatically select style/script elements
2844 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2845 $link = Html
::linkedStyle( $url );
2846 } elseif ( $loadCall ) {
2847 $link = Html
::inlineScript(
2848 ResourceLoader
::makeLoaderConditionalScript(
2849 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2853 $link = Html
::linkedScript( $url );
2855 // For modules requested directly in the html via <link> or <script>,
2856 // tell mw.loader they are being loading to prevent duplicate requests.
2857 foreach ( $grpModules as $key => $module ) {
2858 // Don't output state=loading for the startup module..
2859 if ( $key !== 'startup' ) {
2860 $links['states'][$key] = 'loading';
2866 if ( $group == 'noscript' ) {
2867 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2869 $links['html'] .= $link . "\n";
2878 * Build html output from an array of links from makeResourceLoaderLink.
2879 * @param array $links
2880 * @return string HTML
2882 protected static function getHtmlFromLoaderLinks( array $links ) {
2885 foreach ( $links as $link ) {
2886 if ( !is_array( $link ) ) {
2889 $html .= $link['html'];
2890 $states +
= $link['states'];
2894 if ( count( $states ) ) {
2895 $html = Html
::inlineScript(
2896 ResourceLoader
::makeLoaderConditionalScript(
2897 ResourceLoader
::makeLoaderStateScript( $states )
2906 * JS stuff to put in the "<head>". This is the startup module, config
2907 * vars and modules marked with position 'top'
2909 * @return string HTML fragment
2911 function getHeadScripts() {
2912 global $wgResourceLoaderExperimentalAsyncLoading;
2914 // Startup - this will immediately load jquery and mediawiki modules
2916 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2918 // Load config before anything else
2919 $links[] = Html
::inlineScript(
2920 ResourceLoader
::makeLoaderConditionalScript(
2921 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2925 // Load embeddable private modules before any loader links
2926 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2927 // in mw.loader.implement() calls and deferred until mw.user is available
2928 $embedScripts = array( 'user.options', 'user.tokens' );
2929 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2931 // Scripts and messages "only" requests marked for top inclusion
2932 // Messages should go first
2933 $links[] = $this->makeResourceLoaderLink(
2934 $this->getModuleMessages( true, 'top' ),
2935 ResourceLoaderModule
::TYPE_MESSAGES
2937 $links[] = $this->makeResourceLoaderLink(
2938 $this->getModuleScripts( true, 'top' ),
2939 ResourceLoaderModule
::TYPE_SCRIPTS
2942 // Modules requests - let the client calculate dependencies and batch requests as it likes
2943 // Only load modules that have marked themselves for loading at the top
2944 $modules = $this->getModules( true, 'top' );
2946 $links[] = Html
::inlineScript(
2947 ResourceLoader
::makeLoaderConditionalScript(
2948 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2953 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2954 $links[] = $this->getScriptsForBottomQueue( true );
2957 return self
::getHtmlFromLoaderLinks( $links );
2961 * JS stuff to put at the 'bottom', which can either be the bottom of the
2962 * "<body>" or the bottom of the "<head>" depending on
2963 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2964 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2967 * @param bool $inHead If true, this HTML goes into the "<head>",
2968 * if false it goes into the "<body>".
2971 function getScriptsForBottomQueue( $inHead ) {
2972 global $wgAllowUserJs;
2974 // Scripts and messages "only" requests marked for bottom inclusion
2975 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2976 // Messages should go first
2978 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2979 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2980 /* $loadCall = */ $inHead
2982 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2983 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2984 /* $loadCall = */ $inHead
2987 // Modules requests - let the client calculate dependencies and batch requests as it likes
2988 // Only load modules that have marked themselves for loading at the bottom
2989 $modules = $this->getModules( true, 'bottom' );
2991 $links[] = Html
::inlineScript(
2992 ResourceLoader
::makeLoaderConditionalScript(
2993 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2999 $links[] = "\n" . $this->mScripts
;
3001 // Add site JS if enabled
3002 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3003 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3006 // Add user JS if enabled
3008 && $this->getUser()->isLoggedIn()
3009 && $this->getTitle()
3010 && $this->getTitle()->isJsSubpage()
3011 && $this->userCanPreview()
3013 # XXX: additional security check/prompt?
3014 // We're on a preview of a JS subpage
3015 // Exclude this page from the user module in case it's in there (bug 26283)
3016 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3017 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3019 // Load the previewed JS
3020 $links[] = Html
::inlineScript( "\n"
3021 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3023 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3024 // asynchronously and may arrive *after* the inline script here. So the previewed code
3025 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3027 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3028 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3029 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3033 // Group JS is only enabled if site JS is enabled.
3034 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3035 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3038 return self
::getHtmlFromLoaderLinks( $links );
3042 * JS stuff to put at the bottom of the "<body>"
3045 function getBottomScripts() {
3046 global $wgResourceLoaderExperimentalAsyncLoading;
3048 // Optimise jQuery ready event cross-browser.
3049 // This also enforces $.isReady to be true at </body> which fixes the
3050 // mw.loader bug in Firefox with using document.write between </body>
3051 // and the DOMContentReady event (bug 47457).
3052 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3054 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
3055 $html .= $this->getScriptsForBottomQueue( false );
3062 * Get the javascript config vars to include on this page
3064 * @return array Array of javascript config vars
3067 public function getJsConfigVars() {
3068 return $this->mJsConfigVars
;
3072 * Add one or more variables to be set in mw.config in JavaScript
3074 * @param string|array $keys Key or array of key/value pairs
3075 * @param mixed $value [optional] Value of the configuration variable
3077 public function addJsConfigVars( $keys, $value = null ) {
3078 if ( is_array( $keys ) ) {
3079 foreach ( $keys as $key => $value ) {
3080 $this->mJsConfigVars
[$key] = $value;
3085 $this->mJsConfigVars
[$keys] = $value;
3089 * Get an array containing the variables to be set in mw.config in JavaScript.
3091 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3092 * - in other words, page-independent/site-wide variables (without state).
3093 * You will only be adding bloat to the html page and causing page caches to
3094 * have to be purged on configuration changes.
3097 private function getJSVars() {
3102 $canonicalSpecialPageName = false; # bug 21115
3104 $title = $this->getTitle();
3105 $ns = $title->getNamespace();
3106 $canonicalNamespace = MWNamespace
::exists( $ns )
3107 ? MWNamespace
::getCanonicalName( $ns )
3108 : $title->getNsText();
3110 $sk = $this->getSkin();
3111 // Get the relevant title so that AJAX features can use the correct page name
3112 // when making API requests from certain special pages (bug 34972).
3113 $relevantTitle = $sk->getRelevantTitle();
3114 $relevantUser = $sk->getRelevantUser();
3116 if ( $ns == NS_SPECIAL
) {
3117 list( $canonicalSpecialPageName, /*...*/ ) =
3118 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3119 } elseif ( $this->canUseWikiPage() ) {
3120 $wikiPage = $this->getWikiPage();
3121 $curRevisionId = $wikiPage->getLatest();
3122 $articleId = $wikiPage->getId();
3125 $lang = $title->getPageLanguage();
3127 // Pre-process information
3128 $separatorTransTable = $lang->separatorTransformTable();
3129 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3130 $compactSeparatorTransTable = array(
3131 implode( "\t", array_keys( $separatorTransTable ) ),
3132 implode( "\t", $separatorTransTable ),
3134 $digitTransTable = $lang->digitTransformTable();
3135 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3136 $compactDigitTransTable = array(
3137 implode( "\t", array_keys( $digitTransTable ) ),
3138 implode( "\t", $digitTransTable ),
3141 $user = $this->getUser();
3144 'wgCanonicalNamespace' => $canonicalNamespace,
3145 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3146 'wgNamespaceNumber' => $title->getNamespace(),
3147 'wgPageName' => $title->getPrefixedDBkey(),
3148 'wgTitle' => $title->getText(),
3149 'wgCurRevisionId' => $curRevisionId,
3150 'wgRevisionId' => (int)$this->getRevisionId(),
3151 'wgArticleId' => $articleId,
3152 'wgIsArticle' => $this->isArticle(),
3153 'wgIsRedirect' => $title->isRedirect(),
3154 'wgAction' => Action
::getActionName( $this->getContext() ),
3155 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3156 'wgUserGroups' => $user->getEffectiveGroups(),
3157 'wgCategories' => $this->getCategories(),
3158 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3159 'wgPageContentLanguage' => $lang->getCode(),
3160 'wgPageContentModel' => $title->getContentModel(),
3161 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3162 'wgDigitTransformTable' => $compactDigitTransTable,
3163 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3164 'wgMonthNames' => $lang->getMonthNamesArray(),
3165 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3166 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3169 if ( $user->isLoggedIn() ) {
3170 $vars['wgUserId'] = $user->getId();
3171 $vars['wgUserEditCount'] = $user->getEditCount();
3172 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3173 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3174 // Get the revision ID of the oldest new message on the user's talk
3175 // page. This can be used for constructing new message alerts on
3177 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3180 if ( $wgContLang->hasVariants() ) {
3181 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3183 // Same test as SkinTemplate
3184 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3185 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3187 foreach ( $title->getRestrictionTypes() as $type ) {
3188 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3191 if ( $title->isMainPage() ) {
3192 $vars['wgIsMainPage'] = true;
3195 if ( $this->mRedirectedFrom
) {
3196 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3199 if ( $relevantUser ) {
3200 $vars['wgRelevantUserName'] = $relevantUser->getName();
3203 // Allow extensions to add their custom variables to the mw.config map.
3204 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3205 // page-dependant but site-wide (without state).
3206 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3207 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3209 // Merge in variables from addJsConfigVars last
3210 return array_merge( $vars, $this->getJsConfigVars() );
3214 * To make it harder for someone to slip a user a fake
3215 * user-JavaScript or user-CSS preview, a random token
3216 * is associated with the login session. If it's not
3217 * passed back with the preview request, we won't render
3222 public function userCanPreview() {
3223 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3224 ||
!$this->getRequest()->wasPosted()
3225 ||
!$this->getUser()->matchEditToken(
3226 $this->getRequest()->getVal( 'wpEditToken' ) )
3230 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3234 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3238 * @return array Array in format "link name or number => 'link html'".
3240 public function getHeadLinksArray() {
3241 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3242 $wgSitename, $wgVersion,
3243 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3244 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3245 $wgRightsPage, $wgRightsUrl;
3249 $canonicalUrl = $this->mCanonicalUrl
;
3251 $tags['meta-generator'] = Html
::element( 'meta', array(
3252 'name' => 'generator',
3253 'content' => "MediaWiki $wgVersion",
3256 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3257 if ( $p !== 'index,follow' ) {
3258 // http://www.robotstxt.org/wc/meta-user.html
3259 // Only show if it's different from the default robots policy
3260 $tags['meta-robots'] = Html
::element( 'meta', array(
3266 foreach ( $this->mMetatags
as $tag ) {
3267 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3269 $tag[0] = substr( $tag[0], 5 );
3273 $tagName = "meta-{$tag[0]}";
3274 if ( isset( $tags[$tagName] ) ) {
3275 $tagName .= $tag[1];
3277 $tags[$tagName] = Html
::element( 'meta',
3280 'content' => $tag[1]
3285 foreach ( $this->mLinktags
as $tag ) {
3286 $tags[] = Html
::element( 'link', $tag );
3289 # Universal edit button
3290 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3291 $user = $this->getUser();
3292 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3293 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3294 // Original UniversalEditButton
3295 $msg = $this->msg( 'edit' )->text();
3296 $tags['universal-edit-button'] = Html
::element( 'link', array(
3297 'rel' => 'alternate',
3298 'type' => 'application/x-wiki',
3300 'href' => $this->getTitle()->getEditURL(),
3302 // Alternate edit link
3303 $tags['alternative-edit'] = Html
::element( 'link', array(
3306 'href' => $this->getTitle()->getEditURL(),
3311 # Generally the order of the favicon and apple-touch-icon links
3312 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3313 # uses whichever one appears later in the HTML source. Make sure
3314 # apple-touch-icon is specified first to avoid this.
3315 if ( $wgAppleTouchIcon !== false ) {
3316 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3317 'rel' => 'apple-touch-icon',
3318 'href' => $wgAppleTouchIcon
3322 if ( $wgFavicon !== false ) {
3323 $tags['favicon'] = Html
::element( 'link', array(
3324 'rel' => 'shortcut icon',
3325 'href' => $wgFavicon
3329 # OpenSearch description link
3330 $tags['opensearch'] = Html
::element( 'link', array(
3332 'type' => 'application/opensearchdescription+xml',
3333 'href' => wfScript( 'opensearch_desc' ),
3334 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3337 if ( $wgEnableAPI ) {
3338 # Real Simple Discovery link, provides auto-discovery information
3339 # for the MediaWiki API (and potentially additional custom API
3340 # support such as WordPress or Twitter-compatible APIs for a
3341 # blogging extension, etc)
3342 $tags['rsd'] = Html
::element( 'link', array(
3344 'type' => 'application/rsd+xml',
3345 // Output a protocol-relative URL here if $wgServer is protocol-relative
3346 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3347 'href' => wfExpandUrl( wfAppendQuery(
3349 array( 'action' => 'rsd' ) ),
3356 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3357 $lang = $this->getTitle()->getPageLanguage();
3358 if ( $lang->hasVariants() ) {
3360 $urlvar = $lang->getURLVariant();
3363 $variants = $lang->getVariants();
3364 foreach ( $variants as $_v ) {
3365 $tags["variant-$_v"] = Html
::element( 'link', array(
3366 'rel' => 'alternate',
3367 'hreflang' => wfBCP47( $_v ),
3368 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3372 $canonicalUrl = $this->getTitle()->getLocalURL();
3379 if ( $wgRightsPage ) {
3380 $copy = Title
::newFromText( $wgRightsPage );
3383 $copyright = $copy->getLocalURL();
3387 if ( !$copyright && $wgRightsUrl ) {
3388 $copyright = $wgRightsUrl;
3392 $tags['copyright'] = Html
::element( 'link', array(
3393 'rel' => 'copyright',
3394 'href' => $copyright )
3400 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3401 # Use the page name for the title. In principle, this could
3402 # lead to issues with having the same name for different feeds
3403 # corresponding to the same page, but we can't avoid that at
3406 $tags[] = $this->feedLink(
3409 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3410 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3414 # Recent changes feed should appear on every page (except recentchanges,
3415 # that would be redundant). Put it after the per-page feed to avoid
3416 # changing existing behavior. It's still available, probably via a
3417 # menu in your browser. Some sites might have a different feed they'd
3418 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3419 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3420 # If so, use it instead.
3421 if ( $wgOverrideSiteFeed ) {
3422 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3423 // Note, this->feedLink escapes the url.
3424 $tags[] = $this->feedLink(
3427 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3430 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3431 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3432 foreach ( $wgAdvertisedFeedTypes as $format ) {
3433 $tags[] = $this->feedLink(
3435 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3436 # For grep: 'site-rss-feed', 'site-atom-feed'
3437 $this->msg( "site-{$format}-feed", $wgSitename )->text()
3444 global $wgEnableCanonicalServerLink;
3445 if ( $wgEnableCanonicalServerLink ) {
3446 if ( $canonicalUrl !== false ) {
3447 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3449 $reqUrl = $this->getRequest()->getRequestURL();
3450 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3453 if ( $canonicalUrl !== false ) {
3454 $tags[] = Html
::element( 'link', array(
3455 'rel' => 'canonical',
3456 'href' => $canonicalUrl
3464 * @return string HTML tag links to be put in the header.
3465 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3466 * OutputPage::getHeadLinksArray directly.
3468 public function getHeadLinks() {
3469 wfDeprecated( __METHOD__
, '1.24' );
3470 return implode( "\n", $this->getHeadLinksArray() );
3474 * Generate a "<link rel/>" for a feed.
3476 * @param string $type Feed type
3477 * @param string $url URL to the feed
3478 * @param string $text Value of the "title" attribute
3479 * @return string HTML fragment
3481 private function feedLink( $type, $url, $text ) {
3482 return Html
::element( 'link', array(
3483 'rel' => 'alternate',
3484 'type' => "application/$type+xml",
3491 * Add a local or specified stylesheet, with the given media options.
3492 * Meant primarily for internal use...
3494 * @param string $style URL to the file
3495 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3496 * @param string $condition For IE conditional comments, specifying an IE version
3497 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3499 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3501 // Even though we expect the media type to be lowercase, but here we
3502 // force it to lowercase to be safe.
3504 $options['media'] = $media;
3507 $options['condition'] = $condition;
3510 $options['dir'] = $dir;
3512 $this->styles
[$style] = $options;
3516 * Adds inline CSS styles
3517 * @param mixed $style_css Inline CSS
3518 * @param string $flip Set to 'flip' to flip the CSS if needed
3520 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3521 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3522 # If wanted, and the interface is right-to-left, flip the CSS
3523 $style_css = CSSJanus
::transform( $style_css, true, false );
3525 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3529 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3530 * These will be applied to various media & IE conditionals.
3534 public function buildCssLinks() {
3535 global $wgAllowUserCss, $wgContLang;
3537 $this->getSkin()->setupSkinUserCss( $this );
3539 // Add ResourceLoader styles
3540 // Split the styles into these groups
3545 'private' => array(),
3546 'noscript' => array()
3549 $otherTags = ''; // Tags to append after the normal <link> tags
3550 $resourceLoader = $this->getResourceLoader();
3552 $moduleStyles = $this->getModuleStyles();
3554 // Per-site custom styles
3555 $moduleStyles[] = 'site';
3556 $moduleStyles[] = 'noscript';
3557 $moduleStyles[] = 'user.groups';
3559 // Per-user custom styles
3560 if ( $wgAllowUserCss && $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3561 // We're on a preview of a CSS subpage
3562 // Exclude this page from the user module in case it's in there (bug 26283)
3563 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3564 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3566 $otherTags .= $link['html'];
3568 // Load the previewed CSS
3569 // If needed, Janus it first. This is user-supplied CSS, so it's
3570 // assumed to be right for the content language directionality.
3571 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3572 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3573 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3575 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3577 // Load the user styles normally
3578 $moduleStyles[] = 'user';
3581 // Per-user preference styles
3582 $moduleStyles[] = 'user.cssprefs';
3584 foreach ( $moduleStyles as $name ) {
3585 $module = $resourceLoader->getModule( $name );
3589 $group = $module->getGroup();
3590 // Modules in groups different than the ones listed on top (see $styles assignment)
3591 // will be placed in the "other" group
3592 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3595 // We want site, private and user styles to override dynamically added
3596 // styles from modules, but we want dynamically added styles to override
3597 // statically added styles from other modules. So the order has to be
3598 // other, dynamic, site, private, user. Add statically added styles for
3600 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3601 // Add normal styles added through addStyle()/addInlineStyle() here
3602 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3603 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3604 // We use a <meta> tag with a made-up name for this because that's valid HTML
3605 $links[] = Html
::element(
3607 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3610 // Add site, private and user styles
3611 // 'private' at present only contains user.options, so put that before 'user'
3612 // Any future private modules will likely have a similar user-specific character
3613 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3614 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3615 ResourceLoaderModule
::TYPE_STYLES
3619 // Add stuff in $otherTags (previewed user CSS if applicable)
3620 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3626 public function buildCssLinksArray() {
3629 // Add any extension CSS
3630 foreach ( $this->mExtStyles
as $url ) {
3631 $this->addStyle( $url );
3633 $this->mExtStyles
= array();
3635 foreach ( $this->styles
as $file => $options ) {
3636 $link = $this->styleLink( $file, $options );
3638 $links[$file] = $link;
3645 * Generate \<link\> tags for stylesheets
3647 * @param string $style URL to the file
3648 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3649 * @return string HTML fragment
3651 protected function styleLink( $style, array $options ) {
3652 if ( isset( $options['dir'] ) ) {
3653 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3658 if ( isset( $options['media'] ) ) {
3659 $media = self
::transformCssMedia( $options['media'] );
3660 if ( is_null( $media ) ) {
3667 if ( substr( $style, 0, 1 ) == '/' ||
3668 substr( $style, 0, 5 ) == 'http:' ||
3669 substr( $style, 0, 6 ) == 'https:' ) {
3672 global $wgStylePath, $wgStyleVersion;
3673 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3676 $link = Html
::linkedStyle( $url, $media );
3678 if ( isset( $options['condition'] ) ) {
3679 $condition = htmlspecialchars( $options['condition'] );
3680 $link = "<!--[if $condition]>$link<![endif]-->";
3686 * Transform "media" attribute based on request parameters
3688 * @param string $media Current value of the "media" attribute
3689 * @return string Modified value of the "media" attribute, or null to skip
3692 public static function transformCssMedia( $media ) {
3695 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3696 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3698 // Switch in on-screen display for media testing
3700 'printable' => 'print',
3701 'handheld' => 'handheld',
3703 foreach ( $switches as $switch => $targetMedia ) {
3704 if ( $wgRequest->getBool( $switch ) ) {
3705 if ( $media == $targetMedia ) {
3707 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3708 // This regex will not attempt to understand a comma-separated media_query_list
3710 // Example supported values for $media:
3711 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3712 // Example NOT supported value for $media:
3713 // '3d-glasses, screen, print and resolution > 90dpi'
3715 // If it's a print request, we never want any kind of screen stylesheets
3716 // If it's a handheld request (currently the only other choice with a switch),
3717 // we don't want simple 'screen' but we might want screen queries that
3718 // have a max-width or something, so we'll pass all others on and let the
3719 // client do the query.
3720 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3731 * Add a wikitext-formatted message to the output.
3732 * This is equivalent to:
3734 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3736 public function addWikiMsg( /*...*/ ) {
3737 $args = func_get_args();
3738 $name = array_shift( $args );
3739 $this->addWikiMsgArray( $name, $args );
3743 * Add a wikitext-formatted message to the output.
3744 * Like addWikiMsg() except the parameters are taken as an array
3745 * instead of a variable argument list.
3747 * @param string $name
3748 * @param array $args
3750 public function addWikiMsgArray( $name, $args ) {
3751 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3755 * This function takes a number of message/argument specifications, wraps them in
3756 * some overall structure, and then parses the result and adds it to the output.
3758 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3759 * on. The subsequent arguments may either be strings, in which case they are the
3760 * message names, or arrays, in which case the first element is the message name,
3761 * and subsequent elements are the parameters to that message.
3763 * Don't use this for messages that are not in users interface language.
3767 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3771 * $wgOut->addWikiText( "<div class='error'>\n"
3772 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3774 * The newline after opening div is needed in some wikitext. See bug 19226.
3776 * @param string $wrap
3778 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3779 $msgSpecs = func_get_args();
3780 array_shift( $msgSpecs );
3781 $msgSpecs = array_values( $msgSpecs );
3783 foreach ( $msgSpecs as $n => $spec ) {
3784 if ( is_array( $spec ) ) {
3786 $name = array_shift( $args );
3787 if ( isset( $args['options'] ) ) {
3788 unset( $args['options'] );
3790 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3798 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3800 $this->addWikiText( $s );
3804 * Include jQuery core. Use this to avoid loading it multiple times
3805 * before we get a usable script loader.
3807 * @param array $modules List of jQuery modules which should be loaded
3808 * @return array The list of modules which were not loaded.
3810 * @deprecated since 1.17
3812 public function includeJQuery( array $modules = array() ) {
3817 * Enables/disables TOC, doesn't override __NOTOC__
3821 public function enableTOC( $flag = true ) {
3822 $this->mEnableTOC
= $flag;
3829 public function isTOCEnabled() {
3830 return $this->mEnableTOC
;
3834 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3838 public function enableSectionEditLinks( $flag = true ) {
3839 $this->mEnableSectionEditLinks
= $flag;
3846 public function sectionEditLinksEnabled() {
3847 return $this->mEnableSectionEditLinks
;