Add parser tests for bug 52468 and bug 52363.
[mediawiki.git] / includes / OutputPage.php
blob83a7d3f77ac54d1e11ffd8197e12631db7593977
1 <?php
2 /**
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
20 * @file
23 /**
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
34 * in November 2010.
36 * @todo document
38 class OutputPage extends ContextSource {
39 /// Should be private. Used with addMeta() which adds "<meta>"
40 var $mMetatags = array();
42 var $mLinktags = array();
43 var $mCanonicalUrl = false;
45 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
46 var $mExtStyles = array();
48 /// Should be private - has getter and setter. Contains the HTML title
49 var $mPagetitle = '';
51 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
52 var $mBodytext = '';
54 /**
55 * Holds the debug lines that will be output as comments in page source if
56 * $wgDebugComments is enabled. See also $wgShowDebug.
57 * @deprecated since 1.20; use MWDebug class instead.
59 public $mDebugtext = '';
61 /// Should be private. Stores contents of "<title>" tag
62 var $mHTMLtitle = '';
64 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
65 var $mIsarticle = false;
67 /**
68 * Should be private. Has get/set methods properly documented.
69 * Stores "article flag" toggle.
71 var $mIsArticleRelated = true;
73 /**
74 * Should be private. We have to set isPrintable(). Some pages should
75 * never be printed (ex: redirections).
77 var $mPrintable = false;
79 /**
80 * Should be private. We have set/get/append methods.
82 * Contains the page subtitle. Special pages usually have some links here.
83 * Don't confuse with site subtitle added by skins.
85 private $mSubtitle = array();
87 var $mRedirect = '';
88 var $mStatusCode;
90 /**
91 * mLastModified and mEtag are used for sending cache control.
92 * The whole caching system should probably be moved into its own class.
94 var $mLastModified = '';
96 /**
97 * Should be private. No getter but used in sendCacheControl();
98 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
99 * as a unique identifier for the content. It is later used by the client
100 * to compare its cached version with the server version. Client sends
101 * headers If-Match and If-None-Match containing its locally cached ETAG value.
103 * To get more information, you will have to look at HTTP/1.1 protocol which
104 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
106 var $mETag = false;
108 var $mCategoryLinks = array();
109 var $mCategories = array();
111 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
112 var $mLanguageLinks = array();
115 * Should be private. Used for JavaScript (pre resource loader)
116 * We should split js / css.
117 * mScripts content is inserted as is in "<head>" by Skin. This might
118 * contains either a link to a stylesheet or inline css.
120 var $mScripts = '';
123 * Inline CSS styles. Use addInlineStyle() sparingly
125 var $mInlineStyles = '';
128 var $mLinkColours;
131 * Used by skin template.
132 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
134 var $mPageLinkTitle = '';
136 /// Array of elements in "<head>". Parser might add its own headers!
137 var $mHeadItems = array();
139 // @todo FIXME: Next variables probably comes from the resource loader
140 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
141 var $mResourceLoader;
142 var $mJsConfigVars = array();
144 /** @todo FIXME: Is this still used ?*/
145 var $mInlineMsg = array();
147 var $mTemplateIds = array();
148 var $mImageTimeKeys = array();
150 var $mRedirectCode = '';
152 var $mFeedLinksAppendQuery = null;
154 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
155 # @see ResourceLoaderModule::$origin
156 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
157 protected $mAllowedModules = array(
158 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
162 * @EasterEgg I just love the name for this self documenting variable.
163 * @todo document
165 var $mDoNothing = false;
167 // Parser related.
168 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
171 * lazy initialised, use parserOptions()
172 * @var ParserOptions
174 protected $mParserOptions = null;
177 * Handles the atom / rss links.
178 * We probably only support atom in 2011.
179 * Looks like a private variable.
180 * @see $wgAdvertisedFeedTypes
182 var $mFeedLinks = array();
184 // Gwicke work on squid caching? Roughly from 2003.
185 var $mEnableClientCache = true;
188 * Flag if output should only contain the body of the article.
189 * Should be private.
191 var $mArticleBodyOnly = false;
193 var $mNewSectionLink = false;
194 var $mHideNewSectionLink = false;
197 * Comes from the parser. This was probably made to load CSS/JS only
198 * if we had "<gallery>". Used directly in CategoryPage.php
199 * Looks like resource loader can replace this.
201 var $mNoGallery = false;
203 // should be private.
204 var $mPageTitleActionText = '';
205 var $mParseWarnings = array();
207 // Cache stuff. Looks like mEnableClientCache
208 var $mSquidMaxage = 0;
210 // @todo document
211 var $mPreventClickjacking = true;
213 /// should be private. To include the variable {{REVISIONID}}
214 var $mRevisionId = null;
215 private $mRevisionTimestamp = null;
217 var $mFileVersion = null;
220 * An array of stylesheet filenames (relative from skins path), with options
221 * for CSS media, IE conditions, and RTL/LTR direction.
222 * For internal use; add settings in the skin via $this->addStyle()
224 * Style again! This seems like a code duplication since we already have
225 * mStyles. This is what makes OpenSource amazing.
227 var $styles = array();
230 * Whether jQuery is already handled.
232 protected $mJQueryDone = false;
234 private $mIndexPolicy = 'index';
235 private $mFollowPolicy = 'follow';
236 private $mVaryHeader = array(
237 'Accept-Encoding' => array( 'list-contains=gzip' ),
241 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
242 * of the redirect.
244 * @var Title
246 private $mRedirectedFrom = null;
249 * Additional key => value data
251 private $mProperties = array();
254 * @var string|null: ResourceLoader target for load.php links. If null, will be omitted
256 private $mTarget = null;
259 * Constructor for OutputPage. This should not be called directly.
260 * Instead a new RequestContext should be created and it will implicitly create
261 * a OutputPage tied to that context.
263 function __construct( IContextSource $context = null ) {
264 if ( $context === null ) {
265 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
266 wfDeprecated( __METHOD__, '1.18' );
267 } else {
268 $this->setContext( $context );
273 * Redirect to $url rather than displaying the normal page
275 * @param string $url URL
276 * @param string $responsecode HTTP status code
278 public function redirect( $url, $responsecode = '302' ) {
279 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
280 $this->mRedirect = str_replace( "\n", '', $url );
281 $this->mRedirectCode = $responsecode;
285 * Get the URL to redirect to, or an empty string if not redirect URL set
287 * @return String
289 public function getRedirect() {
290 return $this->mRedirect;
294 * Set the HTTP status code to send with the output.
296 * @param $statusCode Integer
298 public function setStatusCode( $statusCode ) {
299 $this->mStatusCode = $statusCode;
303 * Add a new "<meta>" tag
304 * To add an http-equiv meta tag, precede the name with "http:"
306 * @param string $name tag name
307 * @param string $val tag value
309 function addMeta( $name, $val ) {
310 array_push( $this->mMetatags, array( $name, $val ) );
314 * Add a new \<link\> tag to the page header.
316 * Note: use setCanonicalUrl() for rel=canonical.
318 * @param array $linkarr associative array of attributes.
320 function addLink( $linkarr ) {
321 array_push( $this->mLinktags, $linkarr );
325 * Add a new \<link\> with "rel" attribute set to "meta"
327 * @param array $linkarr associative array mapping attribute names to their
328 * values, both keys and values will be escaped, and the
329 * "rel" attribute will be automatically added
331 function addMetadataLink( $linkarr ) {
332 $linkarr['rel'] = $this->getMetadataAttribute();
333 $this->addLink( $linkarr );
337 * Set the URL to be used for the <link rel=canonical>. This should be used
338 * in preference to addLink(), to avoid duplicate link tags.
340 function setCanonicalUrl( $url ) {
341 $this->mCanonicalUrl = $url;
345 * Get the value of the "rel" attribute for metadata links
347 * @return String
349 public function getMetadataAttribute() {
350 # note: buggy CC software only reads first "meta" link
351 static $haveMeta = false;
352 if ( $haveMeta ) {
353 return 'alternate meta';
354 } else {
355 $haveMeta = true;
356 return 'meta';
361 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
363 * @param string $script raw HTML
365 function addScript( $script ) {
366 $this->mScripts .= $script . "\n";
370 * Register and add a stylesheet from an extension directory.
372 * @param string $url path to sheet. Provide either a full url (beginning
373 * with 'http', etc) or a relative path from the document root
374 * (beginning with '/'). Otherwise it behaves identically to
375 * addStyle() and draws from the /skins folder.
377 public function addExtensionStyle( $url ) {
378 array_push( $this->mExtStyles, $url );
382 * Get all styles added by extensions
384 * @return Array
386 function getExtStyle() {
387 return $this->mExtStyles;
391 * Add a JavaScript file out of skins/common, or a given relative path.
393 * @param string $file filename in skins/common or complete on-server path
394 * (/foo/bar.js)
395 * @param string $version style version of the file. Defaults to $wgStyleVersion
397 public function addScriptFile( $file, $version = null ) {
398 global $wgStylePath, $wgStyleVersion;
399 // See if $file parameter is an absolute URL or begins with a slash
400 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
401 $path = $file;
402 } else {
403 $path = "{$wgStylePath}/common/{$file}";
405 if ( is_null( $version ) ) {
406 $version = $wgStyleVersion;
408 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
412 * Add a self-contained script tag with the given contents
414 * @param string $script JavaScript text, no "<script>" tags
416 public function addInlineScript( $script ) {
417 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
421 * Get all registered JS and CSS tags for the header.
423 * @return String
425 function getScript() {
426 return $this->mScripts . $this->getHeadItems();
430 * Filter an array of modules to remove insufficiently trustworthy members, and modules
431 * which are no longer registered (eg a page is cached before an extension is disabled)
432 * @param $modules Array
433 * @param string $position if not null, only return modules with this position
434 * @param $type string
435 * @return Array
437 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ) {
438 $resourceLoader = $this->getResourceLoader();
439 $filteredModules = array();
440 foreach ( $modules as $val ) {
441 $module = $resourceLoader->getModule( $val );
442 if ( $module instanceof ResourceLoaderModule
443 && $module->getOrigin() <= $this->getAllowedModules( $type )
444 && ( is_null( $position ) || $module->getPosition() == $position )
445 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) ) )
447 $filteredModules[] = $val;
450 return $filteredModules;
454 * Get the list of modules to include on this page
456 * @param bool $filter whether to filter out insufficiently trustworthy modules
457 * @param string $position if not null, only return modules with this position
458 * @param $param string
459 * @return Array of module names
461 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
462 $modules = array_values( array_unique( $this->$param ) );
463 return $filter
464 ? $this->filterModules( $modules, $position )
465 : $modules;
469 * Add one or more modules recognized by the resource loader. Modules added
470 * through this function will be loaded by the resource loader when the
471 * page loads.
473 * @param $modules Mixed: module name (string) or array of module names
475 public function addModules( $modules ) {
476 $this->mModules = array_merge( $this->mModules, (array)$modules );
480 * Get the list of module JS to include on this page
482 * @param $filter
483 * @param $position
485 * @return array of module names
487 public function getModuleScripts( $filter = false, $position = null ) {
488 return $this->getModules( $filter, $position, 'mModuleScripts' );
492 * Add only JS of one or more modules recognized by the resource loader. Module
493 * scripts added through this function will be loaded by the resource loader when
494 * the page loads.
496 * @param $modules Mixed: module name (string) or array of module names
498 public function addModuleScripts( $modules ) {
499 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
503 * Get the list of module CSS to include on this page
505 * @param $filter
506 * @param $position
508 * @return Array of module names
510 public function getModuleStyles( $filter = false, $position = null ) {
511 return $this->getModules( $filter, $position, 'mModuleStyles' );
515 * Add only CSS of one or more modules recognized by the resource loader.
517 * Module styles added through this function will be added using standard link CSS
518 * tags, rather than as a combined Javascript and CSS package. Thus, they will
519 * load when JavaScript is disabled (unless CSS also happens to be disabled).
521 * @param $modules Mixed: module name (string) or array of module names
523 public function addModuleStyles( $modules ) {
524 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
528 * Get the list of module messages to include on this page
530 * @param $filter
531 * @param $position
533 * @return Array of module names
535 public function getModuleMessages( $filter = false, $position = null ) {
536 return $this->getModules( $filter, $position, 'mModuleMessages' );
540 * Add only messages of one or more modules recognized by the resource loader.
541 * Module messages added through this function will be loaded by the resource
542 * loader when the page loads.
544 * @param $modules Mixed: module name (string) or array of module names
546 public function addModuleMessages( $modules ) {
547 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
551 * @return null|string: ResourceLoader target
553 public function getTarget() {
554 return $this->mTarget;
558 * Sets ResourceLoader target for load.php links. If null, will be omitted
560 * @param $target string|null
562 public function setTarget( $target ) {
563 $this->mTarget = $target;
567 * Get an array of head items
569 * @return Array
571 function getHeadItemsArray() {
572 return $this->mHeadItems;
576 * Get all header items in a string
578 * @return String
580 function getHeadItems() {
581 $s = '';
582 foreach ( $this->mHeadItems as $item ) {
583 $s .= $item;
585 return $s;
589 * Add or replace an header item to the output
591 * @param string $name item name
592 * @param string $value raw HTML
594 public function addHeadItem( $name, $value ) {
595 $this->mHeadItems[$name] = $value;
599 * Check if the header item $name is already set
601 * @param string $name item name
602 * @return Boolean
604 public function hasHeadItem( $name ) {
605 return isset( $this->mHeadItems[$name] );
609 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
611 * @param string $tag value of "ETag" header
613 function setETag( $tag ) {
614 $this->mETag = $tag;
618 * Set whether the output should only contain the body of the article,
619 * without any skin, sidebar, etc.
620 * Used e.g. when calling with "action=render".
622 * @param $only Boolean: whether to output only the body of the article
624 public function setArticleBodyOnly( $only ) {
625 $this->mArticleBodyOnly = $only;
629 * Return whether the output will contain only the body of the article
631 * @return Boolean
633 public function getArticleBodyOnly() {
634 return $this->mArticleBodyOnly;
638 * Set an additional output property
639 * @since 1.21
641 * @param string $name
642 * @param mixed $value
644 public function setProperty( $name, $value ) {
645 $this->mProperties[$name] = $value;
649 * Get an additional output property
650 * @since 1.21
652 * @param $name
653 * @return mixed: Property value or null if not found
655 public function getProperty( $name ) {
656 if ( isset( $this->mProperties[$name] ) ) {
657 return $this->mProperties[$name];
658 } else {
659 return null;
664 * checkLastModified tells the client to use the client-cached page if
665 * possible. If successful, the OutputPage is disabled so that
666 * any future call to OutputPage->output() have no effect.
668 * Side effect: sets mLastModified for Last-Modified header
670 * @param $timestamp string
672 * @return Boolean: true iff cache-ok headers was sent.
674 public function checkLastModified( $timestamp ) {
675 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
677 if ( !$timestamp || $timestamp == '19700101000000' ) {
678 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
679 return false;
681 if ( !$wgCachePages ) {
682 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
683 return false;
685 if ( $this->getUser()->getOption( 'nocache' ) ) {
686 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
687 return false;
690 $timestamp = wfTimestamp( TS_MW, $timestamp );
691 $modifiedTimes = array(
692 'page' => $timestamp,
693 'user' => $this->getUser()->getTouched(),
694 'epoch' => $wgCacheEpoch
696 if ( $wgUseSquid ) {
697 // bug 44570: the core page itself may not change, but resources might
698 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $wgSquidMaxage );
700 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
702 $maxModified = max( $modifiedTimes );
703 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
705 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
706 if ( $clientHeader === false ) {
707 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
708 return false;
711 # IE sends sizes after the date like this:
712 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
713 # this breaks strtotime().
714 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
716 wfSuppressWarnings(); // E_STRICT system time bitching
717 $clientHeaderTime = strtotime( $clientHeader );
718 wfRestoreWarnings();
719 if ( !$clientHeaderTime ) {
720 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
721 return false;
723 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
725 # Make debug info
726 $info = '';
727 foreach ( $modifiedTimes as $name => $value ) {
728 if ( $info !== '' ) {
729 $info .= ', ';
731 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
734 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
735 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
736 wfDebug( __METHOD__ . ": effective Last-Modified: " .
737 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
738 if ( $clientHeaderTime < $maxModified ) {
739 wfDebug( __METHOD__ . ": STALE, $info\n", false );
740 return false;
743 # Not modified
744 # Give a 304 response code and disable body output
745 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
746 ini_set( 'zlib.output_compression', 0 );
747 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
748 $this->sendCacheControl();
749 $this->disable();
751 // Don't output a compressed blob when using ob_gzhandler;
752 // it's technically against HTTP spec and seems to confuse
753 // Firefox when the response gets split over two packets.
754 wfClearOutputBuffers();
756 return true;
760 * Override the last modified timestamp
762 * @param string $timestamp new timestamp, in a format readable by
763 * wfTimestamp()
765 public function setLastModified( $timestamp ) {
766 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
770 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
772 * @param string $policy the literal string to output as the contents of
773 * the meta tag. Will be parsed according to the spec and output in
774 * standardized form.
775 * @return null
777 public function setRobotPolicy( $policy ) {
778 $policy = Article::formatRobotPolicy( $policy );
780 if ( isset( $policy['index'] ) ) {
781 $this->setIndexPolicy( $policy['index'] );
783 if ( isset( $policy['follow'] ) ) {
784 $this->setFollowPolicy( $policy['follow'] );
789 * Set the index policy for the page, but leave the follow policy un-
790 * touched.
792 * @param string $policy Either 'index' or 'noindex'.
793 * @return null
795 public function setIndexPolicy( $policy ) {
796 $policy = trim( $policy );
797 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
798 $this->mIndexPolicy = $policy;
803 * Set the follow policy for the page, but leave the index policy un-
804 * touched.
806 * @param string $policy either 'follow' or 'nofollow'.
807 * @return null
809 public function setFollowPolicy( $policy ) {
810 $policy = trim( $policy );
811 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
812 $this->mFollowPolicy = $policy;
817 * Set the new value of the "action text", this will be added to the
818 * "HTML title", separated from it with " - ".
820 * @param string $text new value of the "action text"
822 public function setPageTitleActionText( $text ) {
823 $this->mPageTitleActionText = $text;
827 * Get the value of the "action text"
829 * @return String
831 public function getPageTitleActionText() {
832 if ( isset( $this->mPageTitleActionText ) ) {
833 return $this->mPageTitleActionText;
835 return '';
839 * "HTML title" means the contents of "<title>".
840 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
842 * @param $name string
844 public function setHTMLTitle( $name ) {
845 if ( $name instanceof Message ) {
846 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
847 } else {
848 $this->mHTMLtitle = $name;
853 * Return the "HTML title", i.e. the content of the "<title>" tag.
855 * @return String
857 public function getHTMLTitle() {
858 return $this->mHTMLtitle;
862 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
864 * @param $t Title
866 public function setRedirectedFrom( $t ) {
867 $this->mRedirectedFrom = $t;
871 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
872 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
873 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
874 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
876 * @param $name string|Message
878 public function setPageTitle( $name ) {
879 if ( $name instanceof Message ) {
880 $name = $name->setContext( $this->getContext() )->text();
883 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
884 # but leave "<i>foobar</i>" alone
885 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
886 $this->mPagetitle = $nameWithTags;
888 # change "<i>foo&amp;bar</i>" to "foo&bar"
889 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) ) );
893 * Return the "page title", i.e. the content of the \<h1\> tag.
895 * @return String
897 public function getPageTitle() {
898 return $this->mPagetitle;
902 * Set the Title object to use
904 * @param $t Title object
906 public function setTitle( Title $t ) {
907 $this->getContext()->setTitle( $t );
911 * Replace the subtitle with $str
913 * @param string|Message $str new value of the subtitle. String should be safe HTML.
915 public function setSubtitle( $str ) {
916 $this->clearSubtitle();
917 $this->addSubtitle( $str );
921 * Add $str to the subtitle
923 * @deprecated in 1.19; use addSubtitle() instead
924 * @param string|Message $str to add to the subtitle
926 public function appendSubtitle( $str ) {
927 $this->addSubtitle( $str );
931 * Add $str to the subtitle
933 * @param string|Message $str to add to the subtitle. String should be safe HTML.
935 public function addSubtitle( $str ) {
936 if ( $str instanceof Message ) {
937 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
938 } else {
939 $this->mSubtitle[] = $str;
944 * Add a subtitle containing a backlink to a page
946 * @param $title Title to link to
948 public function addBacklinkSubtitle( Title $title ) {
949 $query = array();
950 if ( $title->isRedirect() ) {
951 $query['redirect'] = 'no';
953 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker::link( $title, null, array(), $query ) ) );
957 * Clear the subtitles
959 public function clearSubtitle() {
960 $this->mSubtitle = array();
964 * Get the subtitle
966 * @return String
968 public function getSubtitle() {
969 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
973 * Set the page as printable, i.e. it'll be displayed with with all
974 * print styles included
976 public function setPrintable() {
977 $this->mPrintable = true;
981 * Return whether the page is "printable"
983 * @return Boolean
985 public function isPrintable() {
986 return $this->mPrintable;
990 * Disable output completely, i.e. calling output() will have no effect
992 public function disable() {
993 $this->mDoNothing = true;
997 * Return whether the output will be completely disabled
999 * @return Boolean
1001 public function isDisabled() {
1002 return $this->mDoNothing;
1006 * Show an "add new section" link?
1008 * @return Boolean
1010 public function showNewSectionLink() {
1011 return $this->mNewSectionLink;
1015 * Forcibly hide the new section link?
1017 * @return Boolean
1019 public function forceHideNewSectionLink() {
1020 return $this->mHideNewSectionLink;
1024 * Add or remove feed links in the page header
1025 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1026 * for the new version
1027 * @see addFeedLink()
1029 * @param $show Boolean: true: add default feeds, false: remove all feeds
1031 public function setSyndicated( $show = true ) {
1032 if ( $show ) {
1033 $this->setFeedAppendQuery( false );
1034 } else {
1035 $this->mFeedLinks = array();
1040 * Add default feeds to the page header
1041 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1042 * for the new version
1043 * @see addFeedLink()
1045 * @param string $val query to append to feed links or false to output
1046 * default links
1048 public function setFeedAppendQuery( $val ) {
1049 global $wgAdvertisedFeedTypes;
1051 $this->mFeedLinks = array();
1053 foreach ( $wgAdvertisedFeedTypes as $type ) {
1054 $query = "feed=$type";
1055 if ( is_string( $val ) ) {
1056 $query .= '&' . $val;
1058 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1063 * Add a feed link to the page header
1065 * @param string $format feed type, should be a key of $wgFeedClasses
1066 * @param string $href URL
1068 public function addFeedLink( $format, $href ) {
1069 global $wgAdvertisedFeedTypes;
1071 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1072 $this->mFeedLinks[$format] = $href;
1077 * Should we output feed links for this page?
1078 * @return Boolean
1080 public function isSyndicated() {
1081 return count( $this->mFeedLinks ) > 0;
1085 * Return URLs for each supported syndication format for this page.
1086 * @return array associating format keys with URLs
1088 public function getSyndicationLinks() {
1089 return $this->mFeedLinks;
1093 * Will currently always return null
1095 * @return null
1097 public function getFeedAppendQuery() {
1098 return $this->mFeedLinksAppendQuery;
1102 * Set whether the displayed content is related to the source of the
1103 * corresponding article on the wiki
1104 * Setting true will cause the change "article related" toggle to true
1106 * @param $v Boolean
1108 public function setArticleFlag( $v ) {
1109 $this->mIsarticle = $v;
1110 if ( $v ) {
1111 $this->mIsArticleRelated = $v;
1116 * Return whether the content displayed page is related to the source of
1117 * the corresponding article on the wiki
1119 * @return Boolean
1121 public function isArticle() {
1122 return $this->mIsarticle;
1126 * Set whether this page is related an article on the wiki
1127 * Setting false will cause the change of "article flag" toggle to false
1129 * @param $v Boolean
1131 public function setArticleRelated( $v ) {
1132 $this->mIsArticleRelated = $v;
1133 if ( !$v ) {
1134 $this->mIsarticle = false;
1139 * Return whether this page is related an article on the wiki
1141 * @return Boolean
1143 public function isArticleRelated() {
1144 return $this->mIsArticleRelated;
1148 * Add new language links
1150 * @param array $newLinkArray Associative array mapping language code to the page
1151 * name
1153 public function addLanguageLinks( $newLinkArray ) {
1154 $this->mLanguageLinks += $newLinkArray;
1158 * Reset the language links and add new language links
1160 * @param array $newLinkArray Associative array mapping language code to the page
1161 * name
1163 public function setLanguageLinks( $newLinkArray ) {
1164 $this->mLanguageLinks = $newLinkArray;
1168 * Get the list of language links
1170 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1172 public function getLanguageLinks() {
1173 return $this->mLanguageLinks;
1177 * Add an array of categories, with names in the keys
1179 * @param array $categories mapping category name => sort key
1181 public function addCategoryLinks( $categories ) {
1182 global $wgContLang;
1184 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1185 return;
1188 # Add the links to a LinkBatch
1189 $arr = array( NS_CATEGORY => $categories );
1190 $lb = new LinkBatch;
1191 $lb->setArray( $arr );
1193 # Fetch existence plus the hiddencat property
1194 $dbr = wfGetDB( DB_SLAVE );
1195 $res = $dbr->select( array( 'page', 'page_props' ),
1196 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1197 $lb->constructSet( 'page', $dbr ),
1198 __METHOD__,
1199 array(),
1200 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1203 # Add the results to the link cache
1204 $lb->addResultToCache( LinkCache::singleton(), $res );
1206 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1207 $categories = array_combine(
1208 array_keys( $categories ),
1209 array_fill( 0, count( $categories ), 'normal' )
1212 # Mark hidden categories
1213 foreach ( $res as $row ) {
1214 if ( isset( $row->pp_value ) ) {
1215 $categories[$row->page_title] = 'hidden';
1219 # Add the remaining categories to the skin
1220 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1221 foreach ( $categories as $category => $type ) {
1222 $origcategory = $category;
1223 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1224 $wgContLang->findVariantLink( $category, $title, true );
1225 if ( $category != $origcategory ) {
1226 if ( array_key_exists( $category, $categories ) ) {
1227 continue;
1230 $text = $wgContLang->convertHtml( $title->getText() );
1231 $this->mCategories[] = $title->getText();
1232 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1238 * Reset the category links (but not the category list) and add $categories
1240 * @param array $categories mapping category name => sort key
1242 public function setCategoryLinks( $categories ) {
1243 $this->mCategoryLinks = array();
1244 $this->addCategoryLinks( $categories );
1248 * Get the list of category links, in a 2-D array with the following format:
1249 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1250 * hidden categories) and $link a HTML fragment with a link to the category
1251 * page
1253 * @return Array
1255 public function getCategoryLinks() {
1256 return $this->mCategoryLinks;
1260 * Get the list of category names this page belongs to
1262 * @return Array of strings
1264 public function getCategories() {
1265 return $this->mCategories;
1269 * Do not allow scripts which can be modified by wiki users to load on this page;
1270 * only allow scripts bundled with, or generated by, the software.
1272 public function disallowUserJs() {
1273 $this->reduceAllowedModules(
1274 ResourceLoaderModule::TYPE_SCRIPTS,
1275 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1280 * Return whether user JavaScript is allowed for this page
1281 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1282 * trustworthiness is identified and enforced automagically.
1283 * @return Boolean
1285 public function isUserJsAllowed() {
1286 wfDeprecated( __METHOD__, '1.18' );
1287 return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
1291 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1292 * @see ResourceLoaderModule::$origin
1293 * @param string $type ResourceLoaderModule TYPE_ constant
1294 * @return Int ResourceLoaderModule ORIGIN_ class constant
1296 public function getAllowedModules( $type ) {
1297 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1298 return min( array_values( $this->mAllowedModules ) );
1299 } else {
1300 return isset( $this->mAllowedModules[$type] )
1301 ? $this->mAllowedModules[$type]
1302 : ResourceLoaderModule::ORIGIN_ALL;
1307 * Set the highest level of CSS/JS untrustworthiness allowed
1308 * @param $type String ResourceLoaderModule TYPE_ constant
1309 * @param $level Int ResourceLoaderModule class constant
1311 public function setAllowedModules( $type, $level ) {
1312 $this->mAllowedModules[$type] = $level;
1316 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1317 * @param $type String
1318 * @param $level Int ResourceLoaderModule class constant
1320 public function reduceAllowedModules( $type, $level ) {
1321 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1325 * Prepend $text to the body HTML
1327 * @param string $text HTML
1329 public function prependHTML( $text ) {
1330 $this->mBodytext = $text . $this->mBodytext;
1334 * Append $text to the body HTML
1336 * @param string $text HTML
1338 public function addHTML( $text ) {
1339 $this->mBodytext .= $text;
1343 * Shortcut for adding an Html::element via addHTML.
1345 * @since 1.19
1347 * @param $element string
1348 * @param $attribs array
1349 * @param $contents string
1351 public function addElement( $element, $attribs = array(), $contents = '' ) {
1352 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1356 * Clear the body HTML
1358 public function clearHTML() {
1359 $this->mBodytext = '';
1363 * Get the body HTML
1365 * @return String: HTML
1367 public function getHTML() {
1368 return $this->mBodytext;
1372 * Get/set the ParserOptions object to use for wikitext parsing
1374 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1375 * current ParserOption object
1376 * @return ParserOptions object
1378 public function parserOptions( $options = null ) {
1379 if ( !$this->mParserOptions ) {
1380 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1381 $this->mParserOptions->setEditSection( false );
1383 return wfSetVar( $this->mParserOptions, $options );
1387 * Set the revision ID which will be seen by the wiki text parser
1388 * for things such as embedded {{REVISIONID}} variable use.
1390 * @param $revid Mixed: an positive integer, or null
1391 * @return Mixed: previous value
1393 public function setRevisionId( $revid ) {
1394 $val = is_null( $revid ) ? null : intval( $revid );
1395 return wfSetVar( $this->mRevisionId, $val );
1399 * Get the displayed revision ID
1401 * @return Integer
1403 public function getRevisionId() {
1404 return $this->mRevisionId;
1408 * Set the timestamp of the revision which will be displayed. This is used
1409 * to avoid a extra DB call in Skin::lastModified().
1411 * @param $timestamp Mixed: string, or null
1412 * @return Mixed: previous value
1414 public function setRevisionTimestamp( $timestamp ) {
1415 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1419 * Get the timestamp of displayed revision.
1420 * This will be null if not filled by setRevisionTimestamp().
1422 * @return String or null
1424 public function getRevisionTimestamp() {
1425 return $this->mRevisionTimestamp;
1429 * Set the displayed file version
1431 * @param $file File|bool
1432 * @return Mixed: previous value
1434 public function setFileVersion( $file ) {
1435 $val = null;
1436 if ( $file instanceof File && $file->exists() ) {
1437 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1439 return wfSetVar( $this->mFileVersion, $val, true );
1443 * Get the displayed file version
1445 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1447 public function getFileVersion() {
1448 return $this->mFileVersion;
1452 * Get the templates used on this page
1454 * @return Array (namespace => dbKey => revId)
1455 * @since 1.18
1457 public function getTemplateIds() {
1458 return $this->mTemplateIds;
1462 * Get the files used on this page
1464 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1465 * @since 1.18
1467 public function getFileSearchOptions() {
1468 return $this->mImageTimeKeys;
1472 * Convert wikitext to HTML and add it to the buffer
1473 * Default assumes that the current page title will be used.
1475 * @param $text String
1476 * @param $linestart Boolean: is this the start of a line?
1477 * @param $interface Boolean: is this text in the user interface language?
1479 public function addWikiText( $text, $linestart = true, $interface = true ) {
1480 $title = $this->getTitle(); // Work around E_STRICT
1481 if ( !$title ) {
1482 throw new MWException( 'Title is null' );
1484 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1488 * Add wikitext with a custom Title object
1490 * @param string $text wikitext
1491 * @param $title Title object
1492 * @param $linestart Boolean: is this the start of a line?
1494 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1495 $this->addWikiTextTitle( $text, $title, $linestart );
1499 * Add wikitext with a custom Title object and tidy enabled.
1501 * @param string $text wikitext
1502 * @param $title Title object
1503 * @param $linestart Boolean: is this the start of a line?
1505 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1506 $this->addWikiTextTitle( $text, $title, $linestart, true );
1510 * Add wikitext with tidy enabled
1512 * @param string $text wikitext
1513 * @param $linestart Boolean: is this the start of a line?
1515 public function addWikiTextTidy( $text, $linestart = true ) {
1516 $title = $this->getTitle();
1517 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1521 * Add wikitext with a custom Title object
1523 * @param string $text wikitext
1524 * @param $title Title object
1525 * @param $linestart Boolean: is this the start of a line?
1526 * @param $tidy Boolean: whether to use tidy
1527 * @param $interface Boolean: whether it is an interface message
1528 * (for example disables conversion)
1530 public function addWikiTextTitle( $text, Title $title, $linestart, $tidy = false, $interface = false ) {
1531 global $wgParser;
1533 wfProfileIn( __METHOD__ );
1535 $popts = $this->parserOptions();
1536 $oldTidy = $popts->setTidy( $tidy );
1537 $popts->setInterfaceMessage( (bool) $interface );
1539 $parserOutput = $wgParser->parse(
1540 $text, $title, $popts,
1541 $linestart, true, $this->mRevisionId
1544 $popts->setTidy( $oldTidy );
1546 $this->addParserOutput( $parserOutput );
1548 wfProfileOut( __METHOD__ );
1552 * Add a ParserOutput object, but without Html
1554 * @param $parserOutput ParserOutput object
1556 public function addParserOutputNoText( &$parserOutput ) {
1557 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1558 $this->addCategoryLinks( $parserOutput->getCategories() );
1559 $this->mNewSectionLink = $parserOutput->getNewSection();
1560 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1562 $this->mParseWarnings = $parserOutput->getWarnings();
1563 if ( !$parserOutput->isCacheable() ) {
1564 $this->enableClientCache( false );
1566 $this->mNoGallery = $parserOutput->getNoGallery();
1567 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1568 $this->addModules( $parserOutput->getModules() );
1569 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1570 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1571 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1573 // Template versioning...
1574 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1575 if ( isset( $this->mTemplateIds[$ns] ) ) {
1576 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1577 } else {
1578 $this->mTemplateIds[$ns] = $dbks;
1581 // File versioning...
1582 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1583 $this->mImageTimeKeys[$dbk] = $data;
1586 // Hooks registered in the object
1587 global $wgParserOutputHooks;
1588 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1589 list( $hookName, $data ) = $hookInfo;
1590 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1591 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1595 // Link flags are ignored for now, but may in the future be
1596 // used to mark individual language links.
1597 $linkFlags = array();
1598 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1599 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1603 * Add a ParserOutput object
1605 * @param $parserOutput ParserOutput
1607 function addParserOutput( &$parserOutput ) {
1608 $this->addParserOutputNoText( $parserOutput );
1609 $text = $parserOutput->getText();
1610 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1611 $this->addHTML( $text );
1615 * Add the output of a QuickTemplate to the output buffer
1617 * @param $template QuickTemplate
1619 public function addTemplate( &$template ) {
1620 ob_start();
1621 $template->execute();
1622 $this->addHTML( ob_get_contents() );
1623 ob_end_clean();
1627 * Parse wikitext and return the HTML.
1629 * @param $text String
1630 * @param $linestart Boolean: is this the start of a line?
1631 * @param $interface Boolean: use interface language ($wgLang instead of
1632 * $wgContLang) while parsing language sensitive magic
1633 * words like GRAMMAR and PLURAL. This also disables
1634 * LanguageConverter.
1635 * @param $language Language object: target language object, will override
1636 * $interface
1637 * @throws MWException
1638 * @return String: HTML
1640 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1641 global $wgParser;
1643 if ( is_null( $this->getTitle() ) ) {
1644 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1647 $popts = $this->parserOptions();
1648 if ( $interface ) {
1649 $popts->setInterfaceMessage( true );
1651 if ( $language !== null ) {
1652 $oldLang = $popts->setTargetLanguage( $language );
1655 $parserOutput = $wgParser->parse(
1656 $text, $this->getTitle(), $popts,
1657 $linestart, true, $this->mRevisionId
1660 if ( $interface ) {
1661 $popts->setInterfaceMessage( false );
1663 if ( $language !== null ) {
1664 $popts->setTargetLanguage( $oldLang );
1667 return $parserOutput->getText();
1671 * Parse wikitext, strip paragraphs, and return the HTML.
1673 * @param $text String
1674 * @param $linestart Boolean: is this the start of a line?
1675 * @param $interface Boolean: use interface language ($wgLang instead of
1676 * $wgContLang) while parsing language sensitive magic
1677 * words like GRAMMAR and PLURAL
1678 * @return String: HTML
1680 public function parseInline( $text, $linestart = true, $interface = false ) {
1681 $parsed = $this->parse( $text, $linestart, $interface );
1683 $m = array();
1684 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1685 $parsed = $m[1];
1688 return $parsed;
1692 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1694 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1696 public function setSquidMaxage( $maxage ) {
1697 $this->mSquidMaxage = $maxage;
1701 * Use enableClientCache(false) to force it to send nocache headers
1703 * @param $state bool
1705 * @return bool
1707 public function enableClientCache( $state ) {
1708 return wfSetVar( $this->mEnableClientCache, $state );
1712 * Get the list of cookies that will influence on the cache
1714 * @return Array
1716 function getCacheVaryCookies() {
1717 global $wgCookiePrefix, $wgCacheVaryCookies;
1718 static $cookies;
1719 if ( $cookies === null ) {
1720 $cookies = array_merge(
1721 array(
1722 "{$wgCookiePrefix}Token",
1723 "{$wgCookiePrefix}LoggedOut",
1724 session_name()
1726 $wgCacheVaryCookies
1728 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1730 return $cookies;
1734 * Check if the request has a cache-varying cookie header
1735 * If it does, it's very important that we don't allow public caching
1737 * @return Boolean
1739 function haveCacheVaryCookies() {
1740 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1741 if ( $cookieHeader === false ) {
1742 return false;
1744 $cvCookies = $this->getCacheVaryCookies();
1745 foreach ( $cvCookies as $cookieName ) {
1746 # Check for a simple string match, like the way squid does it
1747 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1748 wfDebug( __METHOD__ . ": found $cookieName\n" );
1749 return true;
1752 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1753 return false;
1757 * Add an HTTP header that will influence on the cache
1759 * @param string $header header name
1760 * @param $option Array|null
1761 * @todo FIXME: Document the $option parameter; it appears to be for
1762 * X-Vary-Options but what format is acceptable?
1764 public function addVaryHeader( $header, $option = null ) {
1765 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1766 $this->mVaryHeader[$header] = (array)$option;
1767 } elseif ( is_array( $option ) ) {
1768 if ( is_array( $this->mVaryHeader[$header] ) ) {
1769 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1770 } else {
1771 $this->mVaryHeader[$header] = $option;
1774 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1778 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1779 * such as Accept-Encoding or Cookie
1781 * @return String
1783 public function getVaryHeader() {
1784 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1788 * Get a complete X-Vary-Options header
1790 * @return String
1792 public function getXVO() {
1793 $cvCookies = $this->getCacheVaryCookies();
1795 $cookiesOption = array();
1796 foreach ( $cvCookies as $cookieName ) {
1797 $cookiesOption[] = 'string-contains=' . $cookieName;
1799 $this->addVaryHeader( 'Cookie', $cookiesOption );
1801 $headers = array();
1802 foreach ( $this->mVaryHeader as $header => $option ) {
1803 $newheader = $header;
1804 if ( is_array( $option ) && count( $option ) > 0 ) {
1805 $newheader .= ';' . implode( ';', $option );
1807 $headers[] = $newheader;
1809 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1811 return $xvo;
1815 * bug 21672: Add Accept-Language to Vary and XVO headers
1816 * if there's no 'variant' parameter existed in GET.
1818 * For example:
1819 * /w/index.php?title=Main_page should always be served; but
1820 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1822 function addAcceptLanguage() {
1823 $lang = $this->getTitle()->getPageLanguage();
1824 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1825 $variants = $lang->getVariants();
1826 $aloption = array();
1827 foreach ( $variants as $variant ) {
1828 if ( $variant === $lang->getCode() ) {
1829 continue;
1830 } else {
1831 $aloption[] = 'string-contains=' . $variant;
1833 // IE and some other browsers use BCP 47 standards in
1834 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1835 // We should handle these too.
1836 $variantBCP47 = wfBCP47( $variant );
1837 if ( $variantBCP47 !== $variant ) {
1838 $aloption[] = 'string-contains=' . $variantBCP47;
1842 $this->addVaryHeader( 'Accept-Language', $aloption );
1847 * Set a flag which will cause an X-Frame-Options header appropriate for
1848 * edit pages to be sent. The header value is controlled by
1849 * $wgEditPageFrameOptions.
1851 * This is the default for special pages. If you display a CSRF-protected
1852 * form on an ordinary view page, then you need to call this function.
1854 * @param $enable bool
1856 public function preventClickjacking( $enable = true ) {
1857 $this->mPreventClickjacking = $enable;
1861 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1862 * This can be called from pages which do not contain any CSRF-protected
1863 * HTML form.
1865 public function allowClickjacking() {
1866 $this->mPreventClickjacking = false;
1870 * Get the X-Frame-Options header value (without the name part), or false
1871 * if there isn't one. This is used by Skin to determine whether to enable
1872 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1874 * @return string
1876 public function getFrameOptions() {
1877 global $wgBreakFrames, $wgEditPageFrameOptions;
1878 if ( $wgBreakFrames ) {
1879 return 'DENY';
1880 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1881 return $wgEditPageFrameOptions;
1883 return false;
1887 * Send cache control HTTP headers
1889 public function sendCacheControl() {
1890 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1892 $response = $this->getRequest()->response();
1893 if ( $wgUseETag && $this->mETag ) {
1894 $response->header( "ETag: $this->mETag" );
1897 $this->addVaryHeader( 'Cookie' );
1898 $this->addAcceptLanguage();
1900 # don't serve compressed data to clients who can't handle it
1901 # maintain different caches for logged-in users and non-logged in ones
1902 $response->header( $this->getVaryHeader() );
1904 if ( $wgUseXVO ) {
1905 # Add an X-Vary-Options header for Squid with Wikimedia patches
1906 $response->header( $this->getXVO() );
1909 if ( $this->mEnableClientCache ) {
1910 if (
1911 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1912 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1914 if ( $wgUseESI ) {
1915 # We'll purge the proxy cache explicitly, but require end user agents
1916 # to revalidate against the proxy on each visit.
1917 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1918 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1919 # start with a shorter timeout for initial testing
1920 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1921 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
1922 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1923 } else {
1924 # We'll purge the proxy cache for anons explicitly, but require end user agents
1925 # to revalidate against the proxy on each visit.
1926 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1927 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1928 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1929 # start with a shorter timeout for initial testing
1930 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1931 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0' );
1933 } else {
1934 # We do want clients to cache if they can, but they *must* check for updates
1935 # on revisiting the page.
1936 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1937 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1938 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1940 if ( $this->mLastModified ) {
1941 $response->header( "Last-Modified: {$this->mLastModified}" );
1943 } else {
1944 wfDebug( __METHOD__ . ": no caching **\n", false );
1946 # In general, the absence of a last modified header should be enough to prevent
1947 # the client from using its cache. We send a few other things just to make sure.
1948 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1949 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1950 $response->header( 'Pragma: no-cache' );
1955 * Get the message associated with the HTTP response code $code
1957 * @param $code Integer: status code
1958 * @return String or null: message or null if $code is not in the list of
1959 * messages
1961 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1963 public static function getStatusMessage( $code ) {
1964 wfDeprecated( __METHOD__, '1.18' );
1965 return HttpStatus::getMessage( $code );
1969 * Finally, all the text has been munged and accumulated into
1970 * the object, let's actually output it:
1972 public function output() {
1973 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP,
1974 $wgUseAjax, $wgResponsiveImages;
1976 if ( $this->mDoNothing ) {
1977 return;
1980 wfProfileIn( __METHOD__ );
1982 $response = $this->getRequest()->response();
1984 if ( $this->mRedirect != '' ) {
1985 # Standards require redirect URLs to be absolute
1986 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1988 $redirect = $this->mRedirect;
1989 $code = $this->mRedirectCode;
1991 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1992 if ( $code == '301' || $code == '303' ) {
1993 if ( !$wgDebugRedirects ) {
1994 $message = HttpStatus::getMessage( $code );
1995 $response->header( "HTTP/1.1 $code $message" );
1997 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1999 if ( $wgVaryOnXFP ) {
2000 $this->addVaryHeader( 'X-Forwarded-Proto' );
2002 $this->sendCacheControl();
2004 $response->header( "Content-Type: text/html; charset=utf-8" );
2005 if ( $wgDebugRedirects ) {
2006 $url = htmlspecialchars( $redirect );
2007 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2008 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2009 print "</body>\n</html>\n";
2010 } else {
2011 $response->header( 'Location: ' . $redirect );
2015 wfProfileOut( __METHOD__ );
2016 return;
2017 } elseif ( $this->mStatusCode ) {
2018 $message = HttpStatus::getMessage( $this->mStatusCode );
2019 if ( $message ) {
2020 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2024 # Buffer output; final headers may depend on later processing
2025 ob_start();
2027 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2028 $response->header( 'Content-language: ' . $wgLanguageCode );
2030 // Prevent framing, if requested
2031 $frameOptions = $this->getFrameOptions();
2032 if ( $frameOptions ) {
2033 $response->header( "X-Frame-Options: $frameOptions" );
2036 if ( $this->mArticleBodyOnly ) {
2037 echo $this->mBodytext;
2038 } else {
2040 $sk = $this->getSkin();
2041 // add skin specific modules
2042 $modules = $sk->getDefaultModules();
2044 // enforce various default modules for all skins
2045 $coreModules = array(
2046 // keep this list as small as possible
2047 'mediawiki.page.startup',
2048 'mediawiki.user',
2051 // Support for high-density display images if enabled
2052 if ( $wgResponsiveImages ) {
2053 $coreModules[] = 'mediawiki.hidpi';
2056 $this->addModules( $coreModules );
2057 foreach ( $modules as $group ) {
2058 $this->addModules( $group );
2060 MWDebug::addModules( $this );
2061 if ( $wgUseAjax ) {
2062 // FIXME: deprecate? - not clear why this is useful
2063 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2066 // Hook that allows last minute changes to the output page, e.g.
2067 // adding of CSS or Javascript by extensions.
2068 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2070 wfProfileIn( 'Output-skin' );
2071 $sk->outputPage();
2072 wfProfileOut( 'Output-skin' );
2075 // This hook allows last minute changes to final overall output by modifying output buffer
2076 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2078 $this->sendCacheControl();
2080 ob_end_flush();
2082 wfProfileOut( __METHOD__ );
2086 * Actually output something with print.
2088 * @param string $ins the string to output
2089 * @deprecated since 1.22 Use echo yourself.
2091 public function out( $ins ) {
2092 wfDeprecated( __METHOD__, '1.22' );
2093 print $ins;
2097 * Produce a "user is blocked" page.
2098 * @deprecated since 1.18
2100 function blockedPage() {
2101 throw new UserBlockedError( $this->getUser()->mBlock );
2105 * Prepare this object to display an error page; disable caching and
2106 * indexing, clear the current text and redirect, set the page's title
2107 * and optionally an custom HTML title (content of the "<title>" tag).
2109 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2110 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2111 * optional, if not passed the "<title>" attribute will be
2112 * based on $pageTitle
2114 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2115 $this->setPageTitle( $pageTitle );
2116 if ( $htmlTitle !== false ) {
2117 $this->setHTMLTitle( $htmlTitle );
2119 $this->setRobotPolicy( 'noindex,nofollow' );
2120 $this->setArticleRelated( false );
2121 $this->enableClientCache( false );
2122 $this->mRedirect = '';
2123 $this->clearSubtitle();
2124 $this->clearHTML();
2128 * Output a standard error page
2130 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2131 * showErrorPage( 'titlemsg', $messageObject );
2132 * showErrorPage( $titleMessageObj, $messageObject );
2134 * @param $title Mixed: message key (string) for page title, or a Message object
2135 * @param $msg Mixed: message key (string) for page text, or a Message object
2136 * @param array $params message parameters; ignored if $msg is a Message object
2138 public function showErrorPage( $title, $msg, $params = array() ) {
2139 if ( !$title instanceof Message ) {
2140 $title = $this->msg( $title );
2143 $this->prepareErrorPage( $title );
2145 if ( $msg instanceof Message ) {
2146 $this->addHTML( $msg->parseAsBlock() );
2147 } else {
2148 $this->addWikiMsgArray( $msg, $params );
2151 $this->returnToMain();
2155 * Output a standard permission error page
2157 * @param array $errors error message keys
2158 * @param string $action action that was denied or null if unknown
2160 public function showPermissionsErrorPage( $errors, $action = null ) {
2161 // For some action (read, edit, create and upload), display a "login to do this action"
2162 // error if all of the following conditions are met:
2163 // 1. the user is not logged in
2164 // 2. the only error is insufficient permissions (i.e. no block or something else)
2165 // 3. the error can be avoided simply by logging in
2166 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2167 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2168 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2169 && ( User::groupHasPermission( 'user', $action )
2170 || User::groupHasPermission( 'autoconfirmed', $action ) )
2172 $displayReturnto = null;
2174 # Due to bug 32276, if a user does not have read permissions,
2175 # $this->getTitle() will just give Special:Badtitle, which is
2176 # not especially useful as a returnto parameter. Use the title
2177 # from the request instead, if there was one.
2178 $request = $this->getRequest();
2179 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2180 if ( $action == 'edit' ) {
2181 $msg = 'whitelistedittext';
2182 $displayReturnto = $returnto;
2183 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2184 $msg = 'nocreatetext';
2185 } elseif ( $action == 'upload' ) {
2186 $msg = 'uploadnologintext';
2187 } else { # Read
2188 $msg = 'loginreqpagetext';
2189 $displayReturnto = Title::newMainPage();
2192 $query = array();
2194 if ( $returnto ) {
2195 $query['returnto'] = $returnto->getPrefixedText();
2197 if ( !$request->wasPosted() ) {
2198 $returntoquery = $request->getValues();
2199 unset( $returntoquery['title'] );
2200 unset( $returntoquery['returnto'] );
2201 unset( $returntoquery['returntoquery'] );
2202 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2205 $loginLink = Linker::linkKnown(
2206 SpecialPage::getTitleFor( 'Userlogin' ),
2207 $this->msg( 'loginreqlink' )->escaped(),
2208 array(),
2209 $query
2212 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2213 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2215 # Don't return to a page the user can't read otherwise
2216 # we'll end up in a pointless loop
2217 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2218 $this->returnToMain( null, $displayReturnto );
2220 } else {
2221 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2222 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2227 * Display an error page indicating that a given version of MediaWiki is
2228 * required to use it
2230 * @param $version Mixed: the version of MediaWiki needed to use the page
2232 public function versionRequired( $version ) {
2233 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2235 $this->addWikiMsg( 'versionrequiredtext', $version );
2236 $this->returnToMain();
2240 * Display an error page noting that a given permission bit is required.
2241 * @deprecated since 1.18, just throw the exception directly
2242 * @param string $permission key required
2243 * @throws PermissionsError
2245 public function permissionRequired( $permission ) {
2246 throw new PermissionsError( $permission );
2250 * Produce the stock "please login to use the wiki" page
2252 * @deprecated in 1.19; throw the exception directly
2254 public function loginToUse() {
2255 throw new PermissionsError( 'read' );
2259 * Format a list of error messages
2261 * @param array $errors of arrays returned by Title::getUserPermissionsErrors
2262 * @param string $action action that was denied or null if unknown
2263 * @return String: the wikitext error-messages, formatted into a list.
2265 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2266 if ( $action == null ) {
2267 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2268 } else {
2269 $action_desc = $this->msg( "action-$action" )->plain();
2270 $text = $this->msg(
2271 'permissionserrorstext-withaction',
2272 count( $errors ),
2273 $action_desc
2274 )->plain() . "\n\n";
2277 if ( count( $errors ) > 1 ) {
2278 $text .= '<ul class="permissions-errors">' . "\n";
2280 foreach ( $errors as $error ) {
2281 $text .= '<li>';
2282 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2283 $text .= "</li>\n";
2285 $text .= '</ul>';
2286 } else {
2287 $text .= "<div class=\"permissions-errors\">\n" .
2288 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2289 "\n</div>";
2292 return $text;
2296 * Display a page stating that the Wiki is in read-only mode,
2297 * and optionally show the source of the page that the user
2298 * was trying to edit. Should only be called (for this
2299 * purpose) after wfReadOnly() has returned true.
2301 * For historical reasons, this function is _also_ used to
2302 * show the error message when a user tries to edit a page
2303 * they are not allowed to edit. (Unless it's because they're
2304 * blocked, then we show blockedPage() instead.) In this
2305 * case, the second parameter should be set to true and a list
2306 * of reasons supplied as the third parameter.
2308 * @todo Needs to be split into multiple functions.
2310 * @param $source String: source code to show (or null).
2311 * @param $protected Boolean: is this a permissions error?
2312 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2313 * @param $action String: action that was denied or null if unknown
2314 * @throws ReadOnlyError
2316 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2317 $this->setRobotPolicy( 'noindex,nofollow' );
2318 $this->setArticleRelated( false );
2320 // If no reason is given, just supply a default "I can't let you do
2321 // that, Dave" message. Should only occur if called by legacy code.
2322 if ( $protected && empty( $reasons ) ) {
2323 $reasons[] = array( 'badaccess-group0' );
2326 if ( !empty( $reasons ) ) {
2327 // Permissions error
2328 if ( $source ) {
2329 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2330 $this->addBacklinkSubtitle( $this->getTitle() );
2331 } else {
2332 $this->setPageTitle( $this->msg( 'badaccess' ) );
2334 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2335 } else {
2336 // Wiki is read only
2337 throw new ReadOnlyError;
2340 // Show source, if supplied
2341 if ( is_string( $source ) ) {
2342 $this->addWikiMsg( 'viewsourcetext' );
2344 $pageLang = $this->getTitle()->getPageLanguage();
2345 $params = array(
2346 'id' => 'wpTextbox1',
2347 'name' => 'wpTextbox1',
2348 'cols' => $this->getUser()->getOption( 'cols' ),
2349 'rows' => $this->getUser()->getOption( 'rows' ),
2350 'readonly' => 'readonly',
2351 'lang' => $pageLang->getHtmlCode(),
2352 'dir' => $pageLang->getDir(),
2354 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2356 // Show templates used by this article
2357 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2358 $this->addHTML( "<div class='templatesUsed'>
2359 $templates
2360 </div>
2361 " );
2364 # If the title doesn't exist, it's fairly pointless to print a return
2365 # link to it. After all, you just tried editing it and couldn't, so
2366 # what's there to do there?
2367 if ( $this->getTitle()->exists() ) {
2368 $this->returnToMain( null, $this->getTitle() );
2373 * Turn off regular page output and return an error response
2374 * for when rate limiting has triggered.
2376 public function rateLimited() {
2377 throw new ThrottledError;
2381 * Show a warning about slave lag
2383 * If the lag is higher than $wgSlaveLagCritical seconds,
2384 * then the warning is a bit more obvious. If the lag is
2385 * lower than $wgSlaveLagWarning, then no warning is shown.
2387 * @param $lag Integer: slave lag
2389 public function showLagWarning( $lag ) {
2390 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2391 if ( $lag >= $wgSlaveLagWarning ) {
2392 $message = $lag < $wgSlaveLagCritical
2393 ? 'lag-warn-normal'
2394 : 'lag-warn-high';
2395 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2396 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2400 public function showFatalError( $message ) {
2401 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2403 $this->addHTML( $message );
2406 public function showUnexpectedValueError( $name, $val ) {
2407 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2410 public function showFileCopyError( $old, $new ) {
2411 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2414 public function showFileRenameError( $old, $new ) {
2415 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2418 public function showFileDeleteError( $name ) {
2419 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2422 public function showFileNotFoundError( $name ) {
2423 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2427 * Add a "return to" link pointing to a specified title
2429 * @param $title Title to link
2430 * @param array $query query string parameters
2431 * @param string $text text of the link (input is not escaped)
2432 * @param $options Options array to pass to Linker
2434 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2435 if ( in_array( 'http', $options ) ) {
2436 $proto = PROTO_HTTP;
2437 } elseif ( in_array( 'https', $options ) ) {
2438 $proto = PROTO_HTTPS;
2439 } else {
2440 $proto = PROTO_RELATIVE;
2443 $link = $this->msg( 'returnto' )->rawParams(
2444 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2445 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2449 * Add a "return to" link pointing to a specified title,
2450 * or the title indicated in the request, or else the main page
2452 * @param $unused
2453 * @param $returnto Title or String to return to
2454 * @param string $returntoquery query string for the return to link
2456 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2457 if ( $returnto == null ) {
2458 $returnto = $this->getRequest()->getText( 'returnto' );
2461 if ( $returntoquery == null ) {
2462 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2465 if ( $returnto === '' ) {
2466 $returnto = Title::newMainPage();
2469 if ( is_object( $returnto ) ) {
2470 $titleObj = $returnto;
2471 } else {
2472 $titleObj = Title::newFromText( $returnto );
2474 if ( !is_object( $titleObj ) ) {
2475 $titleObj = Title::newMainPage();
2478 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2482 * @param $sk Skin The given Skin
2483 * @param $includeStyle Boolean: unused
2484 * @return String: The doctype, opening "<html>", and head element.
2486 public function headElement( Skin $sk, $includeStyle = true ) {
2487 global $wgContLang, $wgMimeType;
2489 $userdir = $this->getLanguage()->getDir();
2490 $sitedir = $wgContLang->getDir();
2492 if ( $sk->commonPrintStylesheet() ) {
2493 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2496 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2498 if ( $this->getHTMLTitle() == '' ) {
2499 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2502 $openHead = Html::openElement( 'head' );
2503 if ( $openHead ) {
2504 # Don't bother with the newline if $head == ''
2505 $ret .= "$openHead\n";
2508 if ( !Html::isXmlMimeType( $wgMimeType ) ) {
2509 // Add <meta charset="UTF-8">
2510 // This should be before <title> since it defines the charset used by
2511 // text including the text inside <title>.
2512 // The spec recommends defining XHTML5's charset using the XML declaration
2513 // instead of meta.
2514 // Our XML declaration is output by Html::htmlHeader.
2515 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2516 // http://www.whatwg.org/html/semantics.html#charset
2517 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
2520 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2522 $ret .= implode( "\n", array(
2523 $this->getHeadLinks(),
2524 $this->buildCssLinks(),
2525 $this->getHeadScripts(),
2526 $this->getHeadItems()
2527 ) );
2529 $closeHead = Html::closeElement( 'head' );
2530 if ( $closeHead ) {
2531 $ret .= "$closeHead\n";
2534 $bodyClasses = array();
2535 $bodyClasses[] = 'mediawiki';
2537 # Classes for LTR/RTL directionality support
2538 $bodyClasses[] = $userdir;
2539 $bodyClasses[] = "sitedir-$sitedir";
2541 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2542 # A <body> class is probably not the best way to do this . . .
2543 $bodyClasses[] = 'capitalize-all-nouns';
2546 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2547 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2548 $bodyClasses[] = 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2550 $bodyAttrs = array();
2551 // While the implode() is not strictly needed, it's used for backwards compatibility
2552 // (this used to be built as a string and hooks likely still expect that).
2553 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2555 // Allow skins and extensions to add body attributes they need
2556 $sk->addToBodyAttributes( $this, $bodyAttrs );
2557 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2559 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2561 return $ret;
2565 * Get a ResourceLoader object associated with this OutputPage
2567 * @return ResourceLoader
2569 public function getResourceLoader() {
2570 if ( is_null( $this->mResourceLoader ) ) {
2571 $this->mResourceLoader = new ResourceLoader();
2573 return $this->mResourceLoader;
2577 * TODO: Document
2578 * @param $modules Array/string with the module name(s)
2579 * @param string $only ResourceLoaderModule TYPE_ class constant
2580 * @param $useESI boolean
2581 * @param array $extraQuery with extra query parameters to add to each request. array( param => value )
2582 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2583 * @return string html "<script>" and "<style>" tags
2585 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2586 global $wgResourceLoaderUseESI;
2588 $modules = (array) $modules;
2590 if ( !count( $modules ) ) {
2591 return '';
2594 if ( count( $modules ) > 1 ) {
2595 // Remove duplicate module requests
2596 $modules = array_unique( $modules );
2597 // Sort module names so requests are more uniform
2598 sort( $modules );
2600 if ( ResourceLoader::inDebugMode() ) {
2601 // Recursively call us for every item
2602 $links = '';
2603 foreach ( $modules as $name ) {
2604 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2606 return $links;
2609 if ( !is_null( $this->mTarget ) ) {
2610 $extraQuery['target'] = $this->mTarget;
2613 // Create keyed-by-group list of module objects from modules list
2614 $groups = array();
2615 $resourceLoader = $this->getResourceLoader();
2616 foreach ( $modules as $name ) {
2617 $module = $resourceLoader->getModule( $name );
2618 # Check that we're allowed to include this module on this page
2619 if ( !$module
2620 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2621 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2622 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2623 && $only == ResourceLoaderModule::TYPE_STYLES )
2624 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2626 continue;
2629 $group = $module->getGroup();
2630 if ( !isset( $groups[$group] ) ) {
2631 $groups[$group] = array();
2633 $groups[$group][$name] = $module;
2636 $links = '';
2637 foreach ( $groups as $group => $grpModules ) {
2638 // Special handling for user-specific groups
2639 $user = null;
2640 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2641 $user = $this->getUser()->getName();
2644 // Create a fake request based on the one we are about to make so modules return
2645 // correct timestamp and emptiness data
2646 $query = ResourceLoader::makeLoaderQuery(
2647 array(), // modules; not determined yet
2648 $this->getLanguage()->getCode(),
2649 $this->getSkin()->getSkinName(),
2650 $user,
2651 null, // version; not determined yet
2652 ResourceLoader::inDebugMode(),
2653 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2654 $this->isPrintable(),
2655 $this->getRequest()->getBool( 'handheld' ),
2656 $extraQuery
2658 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2659 // Extract modules that know they're empty
2660 $emptyModules = array();
2661 foreach ( $grpModules as $key => $module ) {
2662 if ( $module->isKnownEmpty( $context ) ) {
2663 $emptyModules[$key] = 'ready';
2664 unset( $grpModules[$key] );
2667 // Inline empty modules: since they're empty, just mark them as 'ready'
2668 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2669 // If we're only getting the styles, we don't need to do anything for empty modules.
2670 $links .= Html::inlineScript(
2671 ResourceLoader::makeLoaderConditionalScript(
2672 ResourceLoader::makeLoaderStateScript( $emptyModules )
2674 ) . "\n";
2677 // If there are no modules left, skip this group
2678 if ( count( $grpModules ) === 0 ) {
2679 continue;
2682 // Inline private modules. These can't be loaded through load.php for security
2683 // reasons, see bug 34907. Note that these modules should be loaded from
2684 // getHeadScripts() before the first loader call. Otherwise other modules can't
2685 // properly use them as dependencies (bug 30914)
2686 if ( $group === 'private' ) {
2687 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2688 $links .= Html::inlineStyle(
2689 $resourceLoader->makeModuleResponse( $context, $grpModules )
2691 } else {
2692 $links .= Html::inlineScript(
2693 ResourceLoader::makeLoaderConditionalScript(
2694 $resourceLoader->makeModuleResponse( $context, $grpModules )
2698 $links .= "\n";
2699 continue;
2701 // Special handling for the user group; because users might change their stuff
2702 // on-wiki like user pages, or user preferences; we need to find the highest
2703 // timestamp of these user-changeable modules so we can ensure cache misses on change
2704 // This should NOT be done for the site group (bug 27564) because anons get that too
2705 // and we shouldn't be putting timestamps in Squid-cached HTML
2706 $version = null;
2707 if ( $group === 'user' ) {
2708 // Get the maximum timestamp
2709 $timestamp = 1;
2710 foreach ( $grpModules as $module ) {
2711 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2713 // Add a version parameter so cache will break when things change
2714 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2717 $url = ResourceLoader::makeLoaderURL(
2718 array_keys( $grpModules ),
2719 $this->getLanguage()->getCode(),
2720 $this->getSkin()->getSkinName(),
2721 $user,
2722 $version,
2723 ResourceLoader::inDebugMode(),
2724 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2725 $this->isPrintable(),
2726 $this->getRequest()->getBool( 'handheld' ),
2727 $extraQuery
2729 if ( $useESI && $wgResourceLoaderUseESI ) {
2730 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2731 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2732 $link = Html::inlineStyle( $esi );
2733 } else {
2734 $link = Html::inlineScript( $esi );
2736 } else {
2737 // Automatically select style/script elements
2738 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2739 $link = Html::linkedStyle( $url );
2740 } elseif ( $loadCall ) {
2741 $link = Html::inlineScript(
2742 ResourceLoader::makeLoaderConditionalScript(
2743 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2746 } else {
2747 $link = Html::linkedScript( $url );
2751 if ( $group == 'noscript' ) {
2752 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2753 } else {
2754 $links .= $link . "\n";
2757 return $links;
2761 * JS stuff to put in the "<head>". This is the startup module, config
2762 * vars and modules marked with position 'top'
2764 * @return String: HTML fragment
2766 function getHeadScripts() {
2767 global $wgResourceLoaderExperimentalAsyncLoading;
2769 // Startup - this will immediately load jquery and mediawiki modules
2770 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2772 // Load config before anything else
2773 $scripts .= Html::inlineScript(
2774 ResourceLoader::makeLoaderConditionalScript(
2775 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2779 // Load embeddable private modules before any loader links
2780 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2781 // in mw.loader.implement() calls and deferred until mw.user is available
2782 $embedScripts = array( 'user.options', 'user.tokens' );
2783 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2785 // Script and Messages "only" requests marked for top inclusion
2786 // Messages should go first
2787 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2788 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2790 // Modules requests - let the client calculate dependencies and batch requests as it likes
2791 // Only load modules that have marked themselves for loading at the top
2792 $modules = $this->getModules( true, 'top' );
2793 if ( $modules ) {
2794 $scripts .= Html::inlineScript(
2795 ResourceLoader::makeLoaderConditionalScript(
2796 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2801 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2802 $scripts .= $this->getScriptsForBottomQueue( true );
2805 return $scripts;
2809 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2810 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2811 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2812 * user preferences, site JS and user JS
2814 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2815 * @return string
2817 function getScriptsForBottomQueue( $inHead ) {
2818 global $wgUseSiteJs, $wgAllowUserJs;
2820 // Script and Messages "only" requests marked for bottom inclusion
2821 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2822 // Messages should go first
2823 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2824 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2825 /* $loadCall = */ $inHead
2827 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2828 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2829 /* $loadCall = */ $inHead
2832 // Modules requests - let the client calculate dependencies and batch requests as it likes
2833 // Only load modules that have marked themselves for loading at the bottom
2834 $modules = $this->getModules( true, 'bottom' );
2835 if ( $modules ) {
2836 $scripts .= Html::inlineScript(
2837 ResourceLoader::makeLoaderConditionalScript(
2838 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2843 // Legacy Scripts
2844 $scripts .= "\n" . $this->mScripts;
2846 $defaultModules = array();
2848 // Add site JS if enabled
2849 if ( $wgUseSiteJs ) {
2850 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2851 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2853 $defaultModules['site'] = 'loading';
2854 } else {
2855 // Site module is empty, save request by marking ready in advance (bug 46857)
2856 $defaultModules['site'] = 'ready';
2859 // Add user JS if enabled
2860 if ( $wgAllowUserJs ) {
2861 if ( $this->getUser()->isLoggedIn() ) {
2862 if ( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2863 # XXX: additional security check/prompt?
2864 // We're on a preview of a JS subpage
2865 // Exclude this page from the user module in case it's in there (bug 26283)
2866 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2867 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2869 // Load the previewed JS
2870 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2871 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2872 // asynchronously and may arrive *after* the inline script here. So the previewed code
2873 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2874 } else {
2875 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2876 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2877 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2880 $defaultModules['user'] = 'loading';
2881 } else {
2882 // Non-logged-in users have an empty user module.
2883 // Save request by marking ready in advance (bug 46857)
2884 $defaultModules['user'] = 'ready';
2886 } else {
2887 // User modules are disabled on this wiki.
2888 // Save request by marking ready in advance (bug 46857)
2889 $defaultModules['user'] = 'ready';
2892 // Group JS is only enabled if site JS is enabled.
2893 if ( $wgUseSiteJs ) {
2894 if ( $this->getUser()->isLoggedIn() ) {
2895 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2896 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2898 $defaultModules['user.groups'] = 'loading';
2899 } else {
2900 // Non-logged-in users have no user.groups module.
2901 // Save request by marking ready in advance (bug 46857)
2902 $defaultModules['user.groups'] = 'ready';
2904 } else {
2905 // Site (and group JS) disabled
2906 $defaultModules['user.groups'] = 'ready';
2909 $loaderInit = '';
2910 if ( $inHead ) {
2911 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2912 foreach ( $defaultModules as $m => $state ) {
2913 if ( $state == 'loading' ) {
2914 unset( $defaultModules[$m] );
2918 if ( count( $defaultModules ) > 0 ) {
2919 $loaderInit = Html::inlineScript(
2920 ResourceLoader::makeLoaderConditionalScript(
2921 ResourceLoader::makeLoaderStateScript( $defaultModules )
2923 ) . "\n";
2925 return $loaderInit . $scripts;
2929 * JS stuff to put at the bottom of the "<body>"
2930 * @return string
2932 function getBottomScripts() {
2933 global $wgResourceLoaderExperimentalAsyncLoading;
2935 // Optimise jQuery ready event cross-browser.
2936 // This also enforces $.isReady to be true at </body> which fixes the
2937 // mw.loader bug in Firefox with using document.write between </body>
2938 // and the DOMContentReady event (bug 47457).
2939 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
2941 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2942 $html .= $this->getScriptsForBottomQueue( false );
2945 return $html;
2949 * Add one or more variables to be set in mw.config in JavaScript.
2951 * @param $keys {String|Array} Key or array of key/value pairs.
2952 * @param $value {Mixed} [optional] Value of the configuration variable.
2954 public function addJsConfigVars( $keys, $value = null ) {
2955 if ( is_array( $keys ) ) {
2956 foreach ( $keys as $key => $value ) {
2957 $this->mJsConfigVars[$key] = $value;
2959 return;
2962 $this->mJsConfigVars[$keys] = $value;
2966 * Get an array containing the variables to be set in mw.config in JavaScript.
2968 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2969 * This is only public until that function is removed. You have been warned.
2971 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
2972 * - in other words, page-independent/site-wide variables (without state).
2973 * You will only be adding bloat to the html page and causing page caches to
2974 * have to be purged on configuration changes.
2975 * @return array
2977 public function getJSVars() {
2978 global $wgContLang;
2980 $latestRevID = 0;
2981 $pageID = 0;
2982 $canonicalName = false; # bug 21115
2984 $title = $this->getTitle();
2985 $ns = $title->getNamespace();
2986 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2988 // Get the relevant title so that AJAX features can use the correct page name
2989 // when making API requests from certain special pages (bug 34972).
2990 $relevantTitle = $this->getSkin()->getRelevantTitle();
2992 if ( $ns == NS_SPECIAL ) {
2993 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2994 } elseif ( $this->canUseWikiPage() ) {
2995 $wikiPage = $this->getWikiPage();
2996 $latestRevID = $wikiPage->getLatest();
2997 $pageID = $wikiPage->getId();
3000 $lang = $title->getPageLanguage();
3002 // Pre-process information
3003 $separatorTransTable = $lang->separatorTransformTable();
3004 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3005 $compactSeparatorTransTable = array(
3006 implode( "\t", array_keys( $separatorTransTable ) ),
3007 implode( "\t", $separatorTransTable ),
3009 $digitTransTable = $lang->digitTransformTable();
3010 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3011 $compactDigitTransTable = array(
3012 implode( "\t", array_keys( $digitTransTable ) ),
3013 implode( "\t", $digitTransTable ),
3016 $user = $this->getUser();
3018 $vars = array(
3019 'wgCanonicalNamespace' => $nsname,
3020 'wgCanonicalSpecialPageName' => $canonicalName,
3021 'wgNamespaceNumber' => $title->getNamespace(),
3022 'wgPageName' => $title->getPrefixedDBkey(),
3023 'wgTitle' => $title->getText(),
3024 'wgCurRevisionId' => $latestRevID,
3025 'wgArticleId' => $pageID,
3026 'wgIsArticle' => $this->isArticle(),
3027 'wgIsRedirect' => $title->isRedirect(),
3028 'wgAction' => Action::getActionName( $this->getContext() ),
3029 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3030 'wgUserGroups' => $user->getEffectiveGroups(),
3031 'wgCategories' => $this->getCategories(),
3032 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3033 'wgPageContentLanguage' => $lang->getCode(),
3034 'wgPageContentModel' => $title->getContentModel(),
3035 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3036 'wgDigitTransformTable' => $compactDigitTransTable,
3037 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3038 'wgMonthNames' => $lang->getMonthNamesArray(),
3039 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3040 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3042 if ( $user->isLoggedIn() ) {
3043 $vars['wgUserId'] = $user->getId();
3044 $vars['wgUserEditCount'] = $user->getEditCount();
3045 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3046 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3047 // Get the revision ID of the oldest new message on the user's talk
3048 // page. This can be used for constructing new message alerts on
3049 // the client side.
3050 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3052 if ( $wgContLang->hasVariants() ) {
3053 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3055 // Same test as SkinTemplate
3056 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user ) && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3057 foreach ( $title->getRestrictionTypes() as $type ) {
3058 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3060 if ( $title->isMainPage() ) {
3061 $vars['wgIsMainPage'] = true;
3063 if ( $this->mRedirectedFrom ) {
3064 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3067 // Allow extensions to add their custom variables to the mw.config map.
3068 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3069 // page-dependant but site-wide (without state).
3070 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3071 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3073 // Merge in variables from addJsConfigVars last
3074 return array_merge( $vars, $this->mJsConfigVars );
3078 * To make it harder for someone to slip a user a fake
3079 * user-JavaScript or user-CSS preview, a random token
3080 * is associated with the login session. If it's not
3081 * passed back with the preview request, we won't render
3082 * the code.
3084 * @return bool
3086 public function userCanPreview() {
3087 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3088 || !$this->getRequest()->wasPosted()
3089 || !$this->getUser()->matchEditToken(
3090 $this->getRequest()->getVal( 'wpEditToken' ) )
3092 return false;
3094 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3095 return false;
3098 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3102 * @return array in format "link name or number => 'link html'".
3104 public function getHeadLinksArray() {
3105 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3106 $wgSitename, $wgVersion,
3107 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3108 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3109 $wgRightsPage, $wgRightsUrl;
3111 $tags = array();
3113 $canonicalUrl = $this->mCanonicalUrl;
3115 $tags['meta-generator'] = Html::element( 'meta', array(
3116 'name' => 'generator',
3117 'content' => "MediaWiki $wgVersion",
3118 ) );
3120 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3121 if ( $p !== 'index,follow' ) {
3122 // http://www.robotstxt.org/wc/meta-user.html
3123 // Only show if it's different from the default robots policy
3124 $tags['meta-robots'] = Html::element( 'meta', array(
3125 'name' => 'robots',
3126 'content' => $p,
3127 ) );
3130 foreach ( $this->mMetatags as $tag ) {
3131 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3132 $a = 'http-equiv';
3133 $tag[0] = substr( $tag[0], 5 );
3134 } else {
3135 $a = 'name';
3137 $tagName = "meta-{$tag[0]}";
3138 if ( isset( $tags[$tagName] ) ) {
3139 $tagName .= $tag[1];
3141 $tags[$tagName] = Html::element( 'meta',
3142 array(
3143 $a => $tag[0],
3144 'content' => $tag[1]
3149 foreach ( $this->mLinktags as $tag ) {
3150 $tags[] = Html::element( 'link', $tag );
3153 # Universal edit button
3154 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3155 $user = $this->getUser();
3156 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3157 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3158 // Original UniversalEditButton
3159 $msg = $this->msg( 'edit' )->text();
3160 $tags['universal-edit-button'] = Html::element( 'link', array(
3161 'rel' => 'alternate',
3162 'type' => 'application/x-wiki',
3163 'title' => $msg,
3164 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3165 ) );
3166 // Alternate edit link
3167 $tags['alternative-edit'] = Html::element( 'link', array(
3168 'rel' => 'edit',
3169 'title' => $msg,
3170 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3171 ) );
3175 # Generally the order of the favicon and apple-touch-icon links
3176 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3177 # uses whichever one appears later in the HTML source. Make sure
3178 # apple-touch-icon is specified first to avoid this.
3179 if ( $wgAppleTouchIcon !== false ) {
3180 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3183 if ( $wgFavicon !== false ) {
3184 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3187 # OpenSearch description link
3188 $tags['opensearch'] = Html::element( 'link', array(
3189 'rel' => 'search',
3190 'type' => 'application/opensearchdescription+xml',
3191 'href' => wfScript( 'opensearch_desc' ),
3192 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3193 ) );
3195 if ( $wgEnableAPI ) {
3196 # Real Simple Discovery link, provides auto-discovery information
3197 # for the MediaWiki API (and potentially additional custom API
3198 # support such as WordPress or Twitter-compatible APIs for a
3199 # blogging extension, etc)
3200 $tags['rsd'] = Html::element( 'link', array(
3201 'rel' => 'EditURI',
3202 'type' => 'application/rsd+xml',
3203 // Output a protocol-relative URL here if $wgServer is protocol-relative
3204 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3205 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3206 ) );
3209 # Language variants
3210 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3211 $lang = $this->getTitle()->getPageLanguage();
3212 if ( $lang->hasVariants() ) {
3214 $urlvar = $lang->getURLVariant();
3216 if ( !$urlvar ) {
3217 $variants = $lang->getVariants();
3218 foreach ( $variants as $_v ) {
3219 $tags["variant-$_v"] = Html::element( 'link', array(
3220 'rel' => 'alternate',
3221 'hreflang' => wfBCP47( $_v ),
3222 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3225 } else {
3226 $canonicalUrl = $this->getTitle()->getLocalURL();
3231 # Copyright
3232 $copyright = '';
3233 if ( $wgRightsPage ) {
3234 $copy = Title::newFromText( $wgRightsPage );
3236 if ( $copy ) {
3237 $copyright = $copy->getLocalURL();
3241 if ( !$copyright && $wgRightsUrl ) {
3242 $copyright = $wgRightsUrl;
3245 if ( $copyright ) {
3246 $tags['copyright'] = Html::element( 'link', array(
3247 'rel' => 'copyright',
3248 'href' => $copyright )
3252 # Feeds
3253 if ( $wgFeed ) {
3254 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3255 # Use the page name for the title. In principle, this could
3256 # lead to issues with having the same name for different feeds
3257 # corresponding to the same page, but we can't avoid that at
3258 # this low a level.
3260 $tags[] = $this->feedLink(
3261 $format,
3262 $link,
3263 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3264 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3268 # Recent changes feed should appear on every page (except recentchanges,
3269 # that would be redundant). Put it after the per-page feed to avoid
3270 # changing existing behavior. It's still available, probably via a
3271 # menu in your browser. Some sites might have a different feed they'd
3272 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3273 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3274 # If so, use it instead.
3275 if ( $wgOverrideSiteFeed ) {
3276 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3277 // Note, this->feedLink escapes the url.
3278 $tags[] = $this->feedLink(
3279 $type,
3280 $feedUrl,
3281 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3284 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3285 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3286 foreach ( $wgAdvertisedFeedTypes as $format ) {
3287 $tags[] = $this->feedLink(
3288 $format,
3289 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3290 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3296 # Canonical URL
3297 global $wgEnableCanonicalServerLink;
3298 if ( $wgEnableCanonicalServerLink ) {
3299 if ( $canonicalUrl !== false ) {
3300 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3301 } else {
3302 $reqUrl = $this->getRequest()->getRequestURL();
3303 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3306 if ( $canonicalUrl !== false ) {
3307 $tags[] = Html::element( 'link', array(
3308 'rel' => 'canonical',
3309 'href' => $canonicalUrl
3310 ) );
3313 return $tags;
3317 * @return string HTML tag links to be put in the header.
3319 public function getHeadLinks() {
3320 return implode( "\n", $this->getHeadLinksArray() );
3324 * Generate a "<link rel/>" for a feed.
3326 * @param string $type feed type
3327 * @param string $url URL to the feed
3328 * @param string $text value of the "title" attribute
3329 * @return String: HTML fragment
3331 private function feedLink( $type, $url, $text ) {
3332 return Html::element( 'link', array(
3333 'rel' => 'alternate',
3334 'type' => "application/$type+xml",
3335 'title' => $text,
3336 'href' => $url )
3341 * Add a local or specified stylesheet, with the given media options.
3342 * Meant primarily for internal use...
3344 * @param string $style URL to the file
3345 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3346 * @param string $condition for IE conditional comments, specifying an IE version
3347 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3349 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3350 $options = array();
3351 // Even though we expect the media type to be lowercase, but here we
3352 // force it to lowercase to be safe.
3353 if ( $media ) {
3354 $options['media'] = $media;
3356 if ( $condition ) {
3357 $options['condition'] = $condition;
3359 if ( $dir ) {
3360 $options['dir'] = $dir;
3362 $this->styles[$style] = $options;
3366 * Adds inline CSS styles
3367 * @param $style_css Mixed: inline CSS
3368 * @param string $flip Set to 'flip' to flip the CSS if needed
3370 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3371 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3372 # If wanted, and the interface is right-to-left, flip the CSS
3373 $style_css = CSSJanus::transform( $style_css, true, false );
3375 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3379 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3380 * These will be applied to various media & IE conditionals.
3382 * @return string
3384 public function buildCssLinks() {
3385 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3387 $this->getSkin()->setupSkinUserCss( $this );
3389 // Add ResourceLoader styles
3390 // Split the styles into four groups
3391 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3392 $otherTags = ''; // Tags to append after the normal <link> tags
3393 $resourceLoader = $this->getResourceLoader();
3395 $moduleStyles = $this->getModuleStyles();
3397 // Per-site custom styles
3398 if ( $wgUseSiteCss ) {
3399 $moduleStyles[] = 'site';
3400 $moduleStyles[] = 'noscript';
3401 if ( $this->getUser()->isLoggedIn() ) {
3402 $moduleStyles[] = 'user.groups';
3406 // Per-user custom styles
3407 if ( $wgAllowUserCss ) {
3408 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3409 // We're on a preview of a CSS subpage
3410 // Exclude this page from the user module in case it's in there (bug 26283)
3411 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3412 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3415 // Load the previewed CSS
3416 // If needed, Janus it first. This is user-supplied CSS, so it's
3417 // assumed to be right for the content language directionality.
3418 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3419 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3420 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3422 $otherTags .= Html::inlineStyle( $previewedCSS );
3423 } else {
3424 // Load the user styles normally
3425 $moduleStyles[] = 'user';
3429 // Per-user preference styles
3430 if ( $wgAllowUserCssPrefs ) {
3431 $moduleStyles[] = 'user.cssprefs';
3434 foreach ( $moduleStyles as $name ) {
3435 $module = $resourceLoader->getModule( $name );
3436 if ( !$module ) {
3437 continue;
3439 $group = $module->getGroup();
3440 // Modules in groups named "other" or anything different than "user", "site" or "private"
3441 // will be placed in the "other" group
3442 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3445 // We want site, private and user styles to override dynamically added styles from modules, but we want
3446 // dynamically added styles to override statically added styles from other modules. So the order
3447 // has to be other, dynamic, site, private, user
3448 // Add statically added styles for other modules
3449 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3450 // Add normal styles added through addStyle()/addInlineStyle() here
3451 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3452 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3453 // We use a <meta> tag with a made-up name for this because that's valid HTML
3454 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3456 // Add site, private and user styles
3457 // 'private' at present only contains user.options, so put that before 'user'
3458 // Any future private modules will likely have a similar user-specific character
3459 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3460 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3461 ResourceLoaderModule::TYPE_STYLES
3465 // Add stuff in $otherTags (previewed user CSS if applicable)
3466 $ret .= $otherTags;
3467 return $ret;
3471 * @return Array
3473 public function buildCssLinksArray() {
3474 $links = array();
3476 // Add any extension CSS
3477 foreach ( $this->mExtStyles as $url ) {
3478 $this->addStyle( $url );
3480 $this->mExtStyles = array();
3482 foreach ( $this->styles as $file => $options ) {
3483 $link = $this->styleLink( $file, $options );
3484 if ( $link ) {
3485 $links[$file] = $link;
3488 return $links;
3492 * Generate \<link\> tags for stylesheets
3494 * @param string $style URL to the file
3495 * @param array $options option, can contain 'condition', 'dir', 'media'
3496 * keys
3497 * @return String: HTML fragment
3499 protected function styleLink( $style, $options ) {
3500 if ( isset( $options['dir'] ) ) {
3501 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3502 return '';
3506 if ( isset( $options['media'] ) ) {
3507 $media = self::transformCssMedia( $options['media'] );
3508 if ( is_null( $media ) ) {
3509 return '';
3511 } else {
3512 $media = 'all';
3515 if ( substr( $style, 0, 1 ) == '/' ||
3516 substr( $style, 0, 5 ) == 'http:' ||
3517 substr( $style, 0, 6 ) == 'https:' ) {
3518 $url = $style;
3519 } else {
3520 global $wgStylePath, $wgStyleVersion;
3521 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3524 $link = Html::linkedStyle( $url, $media );
3526 if ( isset( $options['condition'] ) ) {
3527 $condition = htmlspecialchars( $options['condition'] );
3528 $link = "<!--[if $condition]>$link<![endif]-->";
3530 return $link;
3534 * Transform "media" attribute based on request parameters
3536 * @param string $media current value of the "media" attribute
3537 * @return String: modified value of the "media" attribute, or null to skip
3538 * this stylesheet
3540 public static function transformCssMedia( $media ) {
3541 global $wgRequest;
3543 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3544 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3546 // Switch in on-screen display for media testing
3547 $switches = array(
3548 'printable' => 'print',
3549 'handheld' => 'handheld',
3551 foreach ( $switches as $switch => $targetMedia ) {
3552 if ( $wgRequest->getBool( $switch ) ) {
3553 if ( $media == $targetMedia ) {
3554 $media = '';
3555 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3556 // This regex will not attempt to understand a comma-separated media_query_list
3558 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3559 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3561 // If it's a print request, we never want any kind of screen stylesheets
3562 // If it's a handheld request (currently the only other choice with a switch),
3563 // we don't want simple 'screen' but we might want screen queries that
3564 // have a max-width or something, so we'll pass all others on and let the
3565 // client do the query.
3566 if ( $targetMedia == 'print' || $media == 'screen' ) {
3567 return null;
3573 return $media;
3577 * Add a wikitext-formatted message to the output.
3578 * This is equivalent to:
3580 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3582 public function addWikiMsg( /*...*/ ) {
3583 $args = func_get_args();
3584 $name = array_shift( $args );
3585 $this->addWikiMsgArray( $name, $args );
3589 * Add a wikitext-formatted message to the output.
3590 * Like addWikiMsg() except the parameters are taken as an array
3591 * instead of a variable argument list.
3593 * @param $name string
3594 * @param $args array
3596 public function addWikiMsgArray( $name, $args ) {
3597 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3601 * This function takes a number of message/argument specifications, wraps them in
3602 * some overall structure, and then parses the result and adds it to the output.
3604 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3605 * on. The subsequent arguments may either be strings, in which case they are the
3606 * message names, or arrays, in which case the first element is the message name,
3607 * and subsequent elements are the parameters to that message.
3609 * Don't use this for messages that are not in users interface language.
3611 * For example:
3613 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3615 * Is equivalent to:
3617 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3619 * The newline after opening div is needed in some wikitext. See bug 19226.
3621 * @param $wrap string
3623 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3624 $msgSpecs = func_get_args();
3625 array_shift( $msgSpecs );
3626 $msgSpecs = array_values( $msgSpecs );
3627 $s = $wrap;
3628 foreach ( $msgSpecs as $n => $spec ) {
3629 if ( is_array( $spec ) ) {
3630 $args = $spec;
3631 $name = array_shift( $args );
3632 if ( isset( $args['options'] ) ) {
3633 unset( $args['options'] );
3634 wfDeprecated(
3635 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3636 '1.20'
3639 } else {
3640 $args = array();
3641 $name = $spec;
3643 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3645 $this->addWikiText( $s );
3649 * Include jQuery core. Use this to avoid loading it multiple times
3650 * before we get a usable script loader.
3652 * @param array $modules list of jQuery modules which should be loaded
3653 * @return Array: the list of modules which were not loaded.
3654 * @since 1.16
3655 * @deprecated since 1.17
3657 public function includeJQuery( $modules = array() ) {
3658 return array();