Merge "Add ss_active_users in SiteStats::isSane"
[mediawiki.git] / includes / OutputPage.php
blobb63e658ddddd8da9e1d1e6f0a5d18683aaced755
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 /// "<meta keywords='stuff'>" most of the time the first 10 links to an article
43 var $mKeywords = array();
45 var $mLinktags = array();
46 var $mCanonicalUrl = false;
48 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
49 var $mExtStyles = array();
51 /// Should be private - has getter and setter. Contains the HTML title
52 var $mPagetitle = '';
54 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
55 var $mBodytext = '';
57 /**
58 * Holds the debug lines that will be output as comments in page source if
59 * $wgDebugComments is enabled. See also $wgShowDebug.
60 * @deprecated since 1.20; use MWDebug class instead.
62 public $mDebugtext = '';
64 /// Should be private. Stores contents of "<title>" tag
65 var $mHTMLtitle = '';
67 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
68 var $mIsarticle = false;
70 /**
71 * Should be private. Has get/set methods properly documented.
72 * Stores "article flag" toggle.
74 var $mIsArticleRelated = true;
76 /**
77 * Should be private. We have to set isPrintable(). Some pages should
78 * never be printed (ex: redirections).
80 var $mPrintable = false;
82 /**
83 * Should be private. We have set/get/append methods.
85 * Contains the page subtitle. Special pages usually have some links here.
86 * Don't confuse with site subtitle added by skins.
88 private $mSubtitle = array();
90 var $mRedirect = '';
91 var $mStatusCode;
93 /**
94 * mLastModified and mEtag are used for sending cache control.
95 * The whole caching system should probably be moved into its own class.
97 var $mLastModified = '';
99 /**
100 * Should be private. No getter but used in sendCacheControl();
101 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
102 * as a unique identifier for the content. It is later used by the client
103 * to compare its cached version with the server version. Client sends
104 * headers If-Match and If-None-Match containing its locally cached ETAG value.
106 * To get more information, you will have to look at HTTP/1.1 protocol which
107 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
109 var $mETag = false;
111 var $mCategoryLinks = array();
112 var $mCategories = array();
114 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
115 var $mLanguageLinks = array();
118 * Should be private. Used for JavaScript (pre resource loader)
119 * We should split js / css.
120 * mScripts content is inserted as is in "<head>" by Skin. This might
121 * contains either a link to a stylesheet or inline css.
123 var $mScripts = '';
126 * Inline CSS styles. Use addInlineStyle() sparingly
128 var $mInlineStyles = '';
131 var $mLinkColours;
134 * Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
137 var $mPageLinkTitle = '';
139 /// Array of elements in "<head>". Parser might add its own headers!
140 var $mHeadItems = array();
142 // @todo FIXME: Next variables probably comes from the resource loader
143 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
144 var $mResourceLoader;
145 var $mJsConfigVars = array();
147 /** @todo FIXME: Is this still used ?*/
148 var $mInlineMsg = array();
150 var $mTemplateIds = array();
151 var $mImageTimeKeys = array();
153 var $mRedirectCode = '';
155 var $mFeedLinksAppendQuery = null;
157 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
158 # @see ResourceLoaderModule::$origin
159 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
160 protected $mAllowedModules = array(
161 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
165 * @EasterEgg I just love the name for this self documenting variable.
166 * @todo document
168 var $mDoNothing = false;
170 // Parser related.
171 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
174 * lazy initialised, use parserOptions()
175 * @var ParserOptions
177 protected $mParserOptions = null;
180 * Handles the atom / rss links.
181 * We probably only support atom in 2011.
182 * Looks like a private variable.
183 * @see $wgAdvertisedFeedTypes
185 var $mFeedLinks = array();
187 // Gwicke work on squid caching? Roughly from 2003.
188 var $mEnableClientCache = true;
191 * Flag if output should only contain the body of the article.
192 * Should be private.
194 var $mArticleBodyOnly = false;
196 var $mNewSectionLink = false;
197 var $mHideNewSectionLink = false;
200 * Comes from the parser. This was probably made to load CSS/JS only
201 * if we had "<gallery>". Used directly in CategoryPage.php
202 * Looks like resource loader can replace this.
204 var $mNoGallery = false;
206 // should be private.
207 var $mPageTitleActionText = '';
208 var $mParseWarnings = array();
210 // Cache stuff. Looks like mEnableClientCache
211 var $mSquidMaxage = 0;
213 // @todo document
214 var $mPreventClickjacking = true;
216 /// should be private. To include the variable {{REVISIONID}}
217 var $mRevisionId = null;
218 private $mRevisionTimestamp = null;
220 var $mFileVersion = null;
223 * An array of stylesheet filenames (relative from skins path), with options
224 * for CSS media, IE conditions, and RTL/LTR direction.
225 * For internal use; add settings in the skin via $this->addStyle()
227 * Style again! This seems like a code duplication since we already have
228 * mStyles. This is what makes OpenSource amazing.
230 var $styles = array();
233 * Whether jQuery is already handled.
235 protected $mJQueryDone = false;
237 private $mIndexPolicy = 'index';
238 private $mFollowPolicy = 'follow';
239 private $mVaryHeader = array(
240 'Accept-Encoding' => array( 'list-contains=gzip' ),
244 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
245 * of the redirect.
247 * @var Title
249 private $mRedirectedFrom = null;
252 * Additional key => value data
254 private $mProperties = array();
257 * @var string|null: ResourceLoader target for load.php links. If null, will be omitted
259 private $mTarget = null;
262 * Constructor for OutputPage. This should not be called directly.
263 * Instead a new RequestContext should be created and it will implicitly create
264 * a OutputPage tied to that context.
266 function __construct( IContextSource $context = null ) {
267 if ( $context === null ) {
268 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
269 wfDeprecated( __METHOD__, '1.18' );
270 } else {
271 $this->setContext( $context );
276 * Redirect to $url rather than displaying the normal page
278 * @param string $url URL
279 * @param string $responsecode HTTP status code
281 public function redirect( $url, $responsecode = '302' ) {
282 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
283 $this->mRedirect = str_replace( "\n", '', $url );
284 $this->mRedirectCode = $responsecode;
288 * Get the URL to redirect to, or an empty string if not redirect URL set
290 * @return String
292 public function getRedirect() {
293 return $this->mRedirect;
297 * Set the HTTP status code to send with the output.
299 * @param $statusCode Integer
301 public function setStatusCode( $statusCode ) {
302 $this->mStatusCode = $statusCode;
306 * Add a new "<meta>" tag
307 * To add an http-equiv meta tag, precede the name with "http:"
309 * @param string $name tag name
310 * @param string $val tag value
312 function addMeta( $name, $val ) {
313 array_push( $this->mMetatags, array( $name, $val ) );
317 * Add a keyword or a list of keywords in the page header
319 * @param string $text or array of strings
321 function addKeyword( $text ) {
322 if ( is_array( $text ) ) {
323 $this->mKeywords = array_merge( $this->mKeywords, $text );
324 } else {
325 array_push( $this->mKeywords, $text );
330 * Add a new \<link\> tag to the page header.
332 * Note: use setCanonicalUrl() for rel=canonical.
334 * @param array $linkarr associative array of attributes.
336 function addLink( $linkarr ) {
337 array_push( $this->mLinktags, $linkarr );
341 * Add a new \<link\> with "rel" attribute set to "meta"
343 * @param array $linkarr associative array mapping attribute names to their
344 * values, both keys and values will be escaped, and the
345 * "rel" attribute will be automatically added
347 function addMetadataLink( $linkarr ) {
348 $linkarr['rel'] = $this->getMetadataAttribute();
349 $this->addLink( $linkarr );
353 * Set the URL to be used for the <link rel=canonical>. This should be used
354 * in preference to addLink(), to avoid duplicate link tags.
356 function setCanonicalUrl( $url ) {
357 $this->mCanonicalUrl = $url;
361 * Get the value of the "rel" attribute for metadata links
363 * @return String
365 public function getMetadataAttribute() {
366 # note: buggy CC software only reads first "meta" link
367 static $haveMeta = false;
368 if ( $haveMeta ) {
369 return 'alternate meta';
370 } else {
371 $haveMeta = true;
372 return 'meta';
377 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
379 * @param string $script raw HTML
381 function addScript( $script ) {
382 $this->mScripts .= $script . "\n";
386 * Register and add a stylesheet from an extension directory.
388 * @param string $url path to sheet. Provide either a full url (beginning
389 * with 'http', etc) or a relative path from the document root
390 * (beginning with '/'). Otherwise it behaves identically to
391 * addStyle() and draws from the /skins folder.
393 public function addExtensionStyle( $url ) {
394 array_push( $this->mExtStyles, $url );
398 * Get all styles added by extensions
400 * @return Array
402 function getExtStyle() {
403 return $this->mExtStyles;
407 * Add a JavaScript file out of skins/common, or a given relative path.
409 * @param string $file filename in skins/common or complete on-server path
410 * (/foo/bar.js)
411 * @param string $version style version of the file. Defaults to $wgStyleVersion
413 public function addScriptFile( $file, $version = null ) {
414 global $wgStylePath, $wgStyleVersion;
415 // See if $file parameter is an absolute URL or begins with a slash
416 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
417 $path = $file;
418 } else {
419 $path = "{$wgStylePath}/common/{$file}";
421 if ( is_null( $version ) ) {
422 $version = $wgStyleVersion;
424 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
428 * Add a self-contained script tag with the given contents
430 * @param string $script JavaScript text, no "<script>" tags
432 public function addInlineScript( $script ) {
433 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
437 * Get all registered JS and CSS tags for the header.
439 * @return String
441 function getScript() {
442 return $this->mScripts . $this->getHeadItems();
446 * Filter an array of modules to remove insufficiently trustworthy members, and modules
447 * which are no longer registered (eg a page is cached before an extension is disabled)
448 * @param $modules Array
449 * @param string $position if not null, only return modules with this position
450 * @param $type string
451 * @return Array
453 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ) {
454 $resourceLoader = $this->getResourceLoader();
455 $filteredModules = array();
456 foreach ( $modules as $val ) {
457 $module = $resourceLoader->getModule( $val );
458 if ( $module instanceof ResourceLoaderModule
459 && $module->getOrigin() <= $this->getAllowedModules( $type )
460 && ( is_null( $position ) || $module->getPosition() == $position )
461 && ( !$this->mTarget || in_array( $this->mTarget, $module->getTargets() ) ) )
463 $filteredModules[] = $val;
466 return $filteredModules;
470 * Get the list of modules to include on this page
472 * @param bool $filter whether to filter out insufficiently trustworthy modules
473 * @param string $position if not null, only return modules with this position
474 * @param $param string
475 * @return Array of module names
477 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
478 $modules = array_values( array_unique( $this->$param ) );
479 return $filter
480 ? $this->filterModules( $modules, $position )
481 : $modules;
485 * Add one or more modules recognized by the resource loader. Modules added
486 * through this function will be loaded by the resource loader when the
487 * page loads.
489 * @param $modules Mixed: module name (string) or array of module names
491 public function addModules( $modules ) {
492 $this->mModules = array_merge( $this->mModules, (array)$modules );
496 * Get the list of module JS to include on this page
498 * @param $filter
499 * @param $position
501 * @return array of module names
503 public function getModuleScripts( $filter = false, $position = null ) {
504 return $this->getModules( $filter, $position, 'mModuleScripts' );
508 * Add only JS of one or more modules recognized by the resource loader. Module
509 * scripts added through this function will be loaded by the resource loader when
510 * the page loads.
512 * @param $modules Mixed: module name (string) or array of module names
514 public function addModuleScripts( $modules ) {
515 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
519 * Get the list of module CSS to include on this page
521 * @param $filter
522 * @param $position
524 * @return Array of module names
526 public function getModuleStyles( $filter = false, $position = null ) {
527 return $this->getModules( $filter, $position, 'mModuleStyles' );
531 * Add only CSS of one or more modules recognized by the resource loader.
533 * Module styles added through this function will be added using standard link CSS
534 * tags, rather than as a combined Javascript and CSS package. Thus, they will
535 * load when JavaScript is disabled (unless CSS also happens to be disabled).
537 * @param $modules Mixed: module name (string) or array of module names
539 public function addModuleStyles( $modules ) {
540 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
544 * Get the list of module messages to include on this page
546 * @param $filter
547 * @param $position
549 * @return Array of module names
551 public function getModuleMessages( $filter = false, $position = null ) {
552 return $this->getModules( $filter, $position, 'mModuleMessages' );
556 * Add only messages of one or more modules recognized by the resource loader.
557 * Module messages added through this function will be loaded by the resource
558 * loader when the page loads.
560 * @param $modules Mixed: module name (string) or array of module names
562 public function addModuleMessages( $modules ) {
563 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
567 * @return null|string: ResourceLoader target
569 public function getTarget() {
570 return $this->mTarget;
574 * Sets ResourceLoader target for load.php links. If null, will be omitted
576 * @param $target string|null
578 public function setTarget( $target ) {
579 $this->mTarget = $target;
583 * Get an array of head items
585 * @return Array
587 function getHeadItemsArray() {
588 return $this->mHeadItems;
592 * Get all header items in a string
594 * @return String
596 function getHeadItems() {
597 $s = '';
598 foreach ( $this->mHeadItems as $item ) {
599 $s .= $item;
601 return $s;
605 * Add or replace an header item to the output
607 * @param string $name item name
608 * @param string $value raw HTML
610 public function addHeadItem( $name, $value ) {
611 $this->mHeadItems[$name] = $value;
615 * Check if the header item $name is already set
617 * @param string $name item name
618 * @return Boolean
620 public function hasHeadItem( $name ) {
621 return isset( $this->mHeadItems[$name] );
625 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
627 * @param string $tag value of "ETag" header
629 function setETag( $tag ) {
630 $this->mETag = $tag;
634 * Set whether the output should only contain the body of the article,
635 * without any skin, sidebar, etc.
636 * Used e.g. when calling with "action=render".
638 * @param $only Boolean: whether to output only the body of the article
640 public function setArticleBodyOnly( $only ) {
641 $this->mArticleBodyOnly = $only;
645 * Return whether the output will contain only the body of the article
647 * @return Boolean
649 public function getArticleBodyOnly() {
650 return $this->mArticleBodyOnly;
654 * Set an additional output property
655 * @since 1.21
657 * @param string $name
658 * @param mixed $value
660 public function setProperty( $name, $value ) {
661 $this->mProperties[$name] = $value;
665 * Get an additional output property
666 * @since 1.21
668 * @param $name
669 * @return mixed: Property value or null if not found
671 public function getProperty( $name ) {
672 if ( isset( $this->mProperties[$name] ) ) {
673 return $this->mProperties[$name];
674 } else {
675 return null;
680 * checkLastModified tells the client to use the client-cached page if
681 * possible. If successful, the OutputPage is disabled so that
682 * any future call to OutputPage->output() have no effect.
684 * Side effect: sets mLastModified for Last-Modified header
686 * @param $timestamp string
688 * @return Boolean: true iff cache-ok headers was sent.
690 public function checkLastModified( $timestamp ) {
691 global $wgCachePages, $wgCacheEpoch, $wgUseSquid, $wgSquidMaxage;
693 if ( !$timestamp || $timestamp == '19700101000000' ) {
694 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
695 return false;
697 if ( !$wgCachePages ) {
698 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
699 return false;
701 if ( $this->getUser()->getOption( 'nocache' ) ) {
702 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
703 return false;
706 $timestamp = wfTimestamp( TS_MW, $timestamp );
707 $modifiedTimes = array(
708 'page' => $timestamp,
709 'user' => $this->getUser()->getTouched(),
710 'epoch' => $wgCacheEpoch
712 if ( $wgUseSquid ) {
713 // bug 44570: the core page itself may not change, but resources might
714 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $wgSquidMaxage );
716 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
718 $maxModified = max( $modifiedTimes );
719 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
721 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
722 if ( $clientHeader === false ) {
723 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
724 return false;
727 # IE sends sizes after the date like this:
728 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
729 # this breaks strtotime().
730 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
732 wfSuppressWarnings(); // E_STRICT system time bitching
733 $clientHeaderTime = strtotime( $clientHeader );
734 wfRestoreWarnings();
735 if ( !$clientHeaderTime ) {
736 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
737 return false;
739 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
741 # Make debug info
742 $info = '';
743 foreach ( $modifiedTimes as $name => $value ) {
744 if ( $info !== '' ) {
745 $info .= ', ';
747 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
750 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
751 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
752 wfDebug( __METHOD__ . ": effective Last-Modified: " .
753 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
754 if ( $clientHeaderTime < $maxModified ) {
755 wfDebug( __METHOD__ . ": STALE, $info\n", false );
756 return false;
759 # Not modified
760 # Give a 304 response code and disable body output
761 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
762 ini_set( 'zlib.output_compression', 0 );
763 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
764 $this->sendCacheControl();
765 $this->disable();
767 // Don't output a compressed blob when using ob_gzhandler;
768 // it's technically against HTTP spec and seems to confuse
769 // Firefox when the response gets split over two packets.
770 wfClearOutputBuffers();
772 return true;
776 * Override the last modified timestamp
778 * @param string $timestamp new timestamp, in a format readable by
779 * wfTimestamp()
781 public function setLastModified( $timestamp ) {
782 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
786 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
788 * @param string $policy the literal string to output as the contents of
789 * the meta tag. Will be parsed according to the spec and output in
790 * standardized form.
791 * @return null
793 public function setRobotPolicy( $policy ) {
794 $policy = Article::formatRobotPolicy( $policy );
796 if ( isset( $policy['index'] ) ) {
797 $this->setIndexPolicy( $policy['index'] );
799 if ( isset( $policy['follow'] ) ) {
800 $this->setFollowPolicy( $policy['follow'] );
805 * Set the index policy for the page, but leave the follow policy un-
806 * touched.
808 * @param string $policy Either 'index' or 'noindex'.
809 * @return null
811 public function setIndexPolicy( $policy ) {
812 $policy = trim( $policy );
813 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
814 $this->mIndexPolicy = $policy;
819 * Set the follow policy for the page, but leave the index policy un-
820 * touched.
822 * @param string $policy either 'follow' or 'nofollow'.
823 * @return null
825 public function setFollowPolicy( $policy ) {
826 $policy = trim( $policy );
827 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
828 $this->mFollowPolicy = $policy;
833 * Set the new value of the "action text", this will be added to the
834 * "HTML title", separated from it with " - ".
836 * @param string $text new value of the "action text"
838 public function setPageTitleActionText( $text ) {
839 $this->mPageTitleActionText = $text;
843 * Get the value of the "action text"
845 * @return String
847 public function getPageTitleActionText() {
848 if ( isset( $this->mPageTitleActionText ) ) {
849 return $this->mPageTitleActionText;
851 return '';
855 * "HTML title" means the contents of "<title>".
856 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
858 * @param $name string
860 public function setHTMLTitle( $name ) {
861 if ( $name instanceof Message ) {
862 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
863 } else {
864 $this->mHTMLtitle = $name;
869 * Return the "HTML title", i.e. the content of the "<title>" tag.
871 * @return String
873 public function getHTMLTitle() {
874 return $this->mHTMLtitle;
878 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
880 * @param $t Title
882 public function setRedirectedFrom( $t ) {
883 $this->mRedirectedFrom = $t;
887 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
888 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
889 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
890 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
892 * @param $name string|Message
894 public function setPageTitle( $name ) {
895 if ( $name instanceof Message ) {
896 $name = $name->setContext( $this->getContext() )->text();
899 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
900 # but leave "<i>foobar</i>" alone
901 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
902 $this->mPagetitle = $nameWithTags;
904 # change "<i>foo&amp;bar</i>" to "foo&bar"
905 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) ) );
909 * Return the "page title", i.e. the content of the \<h1\> tag.
911 * @return String
913 public function getPageTitle() {
914 return $this->mPagetitle;
918 * Set the Title object to use
920 * @param $t Title object
922 public function setTitle( Title $t ) {
923 $this->getContext()->setTitle( $t );
927 * Replace the subtitle with $str
929 * @param string|Message $str new value of the subtitle. String should be safe HTML.
931 public function setSubtitle( $str ) {
932 $this->clearSubtitle();
933 $this->addSubtitle( $str );
937 * Add $str to the subtitle
939 * @deprecated in 1.19; use addSubtitle() instead
940 * @param string|Message $str to add to the subtitle
942 public function appendSubtitle( $str ) {
943 $this->addSubtitle( $str );
947 * Add $str to the subtitle
949 * @param string|Message $str to add to the subtitle. String should be safe HTML.
951 public function addSubtitle( $str ) {
952 if ( $str instanceof Message ) {
953 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
954 } else {
955 $this->mSubtitle[] = $str;
960 * Add a subtitle containing a backlink to a page
962 * @param $title Title to link to
964 public function addBacklinkSubtitle( Title $title ) {
965 $query = array();
966 if ( $title->isRedirect() ) {
967 $query['redirect'] = 'no';
969 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker::link( $title, null, array(), $query ) ) );
973 * Clear the subtitles
975 public function clearSubtitle() {
976 $this->mSubtitle = array();
980 * Get the subtitle
982 * @return String
984 public function getSubtitle() {
985 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
989 * Set the page as printable, i.e. it'll be displayed with with all
990 * print styles included
992 public function setPrintable() {
993 $this->mPrintable = true;
997 * Return whether the page is "printable"
999 * @return Boolean
1001 public function isPrintable() {
1002 return $this->mPrintable;
1006 * Disable output completely, i.e. calling output() will have no effect
1008 public function disable() {
1009 $this->mDoNothing = true;
1013 * Return whether the output will be completely disabled
1015 * @return Boolean
1017 public function isDisabled() {
1018 return $this->mDoNothing;
1022 * Show an "add new section" link?
1024 * @return Boolean
1026 public function showNewSectionLink() {
1027 return $this->mNewSectionLink;
1031 * Forcibly hide the new section link?
1033 * @return Boolean
1035 public function forceHideNewSectionLink() {
1036 return $this->mHideNewSectionLink;
1040 * Add or remove feed links in the page header
1041 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1042 * for the new version
1043 * @see addFeedLink()
1045 * @param $show Boolean: true: add default feeds, false: remove all feeds
1047 public function setSyndicated( $show = true ) {
1048 if ( $show ) {
1049 $this->setFeedAppendQuery( false );
1050 } else {
1051 $this->mFeedLinks = array();
1056 * Add default feeds to the page header
1057 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1058 * for the new version
1059 * @see addFeedLink()
1061 * @param string $val query to append to feed links or false to output
1062 * default links
1064 public function setFeedAppendQuery( $val ) {
1065 global $wgAdvertisedFeedTypes;
1067 $this->mFeedLinks = array();
1069 foreach ( $wgAdvertisedFeedTypes as $type ) {
1070 $query = "feed=$type";
1071 if ( is_string( $val ) ) {
1072 $query .= '&' . $val;
1074 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1079 * Add a feed link to the page header
1081 * @param string $format feed type, should be a key of $wgFeedClasses
1082 * @param string $href URL
1084 public function addFeedLink( $format, $href ) {
1085 global $wgAdvertisedFeedTypes;
1087 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1088 $this->mFeedLinks[$format] = $href;
1093 * Should we output feed links for this page?
1094 * @return Boolean
1096 public function isSyndicated() {
1097 return count( $this->mFeedLinks ) > 0;
1101 * Return URLs for each supported syndication format for this page.
1102 * @return array associating format keys with URLs
1104 public function getSyndicationLinks() {
1105 return $this->mFeedLinks;
1109 * Will currently always return null
1111 * @return null
1113 public function getFeedAppendQuery() {
1114 return $this->mFeedLinksAppendQuery;
1118 * Set whether the displayed content is related to the source of the
1119 * corresponding article on the wiki
1120 * Setting true will cause the change "article related" toggle to true
1122 * @param $v Boolean
1124 public function setArticleFlag( $v ) {
1125 $this->mIsarticle = $v;
1126 if ( $v ) {
1127 $this->mIsArticleRelated = $v;
1132 * Return whether the content displayed page is related to the source of
1133 * the corresponding article on the wiki
1135 * @return Boolean
1137 public function isArticle() {
1138 return $this->mIsarticle;
1142 * Set whether this page is related an article on the wiki
1143 * Setting false will cause the change of "article flag" toggle to false
1145 * @param $v Boolean
1147 public function setArticleRelated( $v ) {
1148 $this->mIsArticleRelated = $v;
1149 if ( !$v ) {
1150 $this->mIsarticle = false;
1155 * Return whether this page is related an article on the wiki
1157 * @return Boolean
1159 public function isArticleRelated() {
1160 return $this->mIsArticleRelated;
1164 * Add new language links
1166 * @param array $newLinkArray Associative array mapping language code to the page
1167 * name
1169 public function addLanguageLinks( $newLinkArray ) {
1170 $this->mLanguageLinks += $newLinkArray;
1174 * Reset the language links and add new language links
1176 * @param array $newLinkArray Associative array mapping language code to the page
1177 * name
1179 public function setLanguageLinks( $newLinkArray ) {
1180 $this->mLanguageLinks = $newLinkArray;
1184 * Get the list of language links
1186 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1188 public function getLanguageLinks() {
1189 return $this->mLanguageLinks;
1193 * Add an array of categories, with names in the keys
1195 * @param array $categories mapping category name => sort key
1197 public function addCategoryLinks( $categories ) {
1198 global $wgContLang;
1200 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1201 return;
1204 # Add the links to a LinkBatch
1205 $arr = array( NS_CATEGORY => $categories );
1206 $lb = new LinkBatch;
1207 $lb->setArray( $arr );
1209 # Fetch existence plus the hiddencat property
1210 $dbr = wfGetDB( DB_SLAVE );
1211 $res = $dbr->select( array( 'page', 'page_props' ),
1212 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1213 $lb->constructSet( 'page', $dbr ),
1214 __METHOD__,
1215 array(),
1216 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1219 # Add the results to the link cache
1220 $lb->addResultToCache( LinkCache::singleton(), $res );
1222 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1223 $categories = array_combine(
1224 array_keys( $categories ),
1225 array_fill( 0, count( $categories ), 'normal' )
1228 # Mark hidden categories
1229 foreach ( $res as $row ) {
1230 if ( isset( $row->pp_value ) ) {
1231 $categories[$row->page_title] = 'hidden';
1235 # Add the remaining categories to the skin
1236 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1237 foreach ( $categories as $category => $type ) {
1238 $origcategory = $category;
1239 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1240 $wgContLang->findVariantLink( $category, $title, true );
1241 if ( $category != $origcategory ) {
1242 if ( array_key_exists( $category, $categories ) ) {
1243 continue;
1246 $text = $wgContLang->convertHtml( $title->getText() );
1247 $this->mCategories[] = $title->getText();
1248 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1254 * Reset the category links (but not the category list) and add $categories
1256 * @param array $categories mapping category name => sort key
1258 public function setCategoryLinks( $categories ) {
1259 $this->mCategoryLinks = array();
1260 $this->addCategoryLinks( $categories );
1264 * Get the list of category links, in a 2-D array with the following format:
1265 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1266 * hidden categories) and $link a HTML fragment with a link to the category
1267 * page
1269 * @return Array
1271 public function getCategoryLinks() {
1272 return $this->mCategoryLinks;
1276 * Get the list of category names this page belongs to
1278 * @return Array of strings
1280 public function getCategories() {
1281 return $this->mCategories;
1285 * Do not allow scripts which can be modified by wiki users to load on this page;
1286 * only allow scripts bundled with, or generated by, the software.
1288 public function disallowUserJs() {
1289 $this->reduceAllowedModules(
1290 ResourceLoaderModule::TYPE_SCRIPTS,
1291 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1296 * Return whether user JavaScript is allowed for this page
1297 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1298 * trustworthiness is identified and enforced automagically.
1299 * @return Boolean
1301 public function isUserJsAllowed() {
1302 wfDeprecated( __METHOD__, '1.18' );
1303 return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
1307 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1308 * @see ResourceLoaderModule::$origin
1309 * @param string $type ResourceLoaderModule TYPE_ constant
1310 * @return Int ResourceLoaderModule ORIGIN_ class constant
1312 public function getAllowedModules( $type ) {
1313 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1314 return min( array_values( $this->mAllowedModules ) );
1315 } else {
1316 return isset( $this->mAllowedModules[$type] )
1317 ? $this->mAllowedModules[$type]
1318 : ResourceLoaderModule::ORIGIN_ALL;
1323 * Set the highest level of CSS/JS untrustworthiness allowed
1324 * @param $type String ResourceLoaderModule TYPE_ constant
1325 * @param $level Int ResourceLoaderModule class constant
1327 public function setAllowedModules( $type, $level ) {
1328 $this->mAllowedModules[$type] = $level;
1332 * As for setAllowedModules(), but don't inadvertently make the page more accessible
1333 * @param $type String
1334 * @param $level Int ResourceLoaderModule class constant
1336 public function reduceAllowedModules( $type, $level ) {
1337 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1341 * Prepend $text to the body HTML
1343 * @param string $text HTML
1345 public function prependHTML( $text ) {
1346 $this->mBodytext = $text . $this->mBodytext;
1350 * Append $text to the body HTML
1352 * @param string $text HTML
1354 public function addHTML( $text ) {
1355 $this->mBodytext .= $text;
1359 * Shortcut for adding an Html::element via addHTML.
1361 * @since 1.19
1363 * @param $element string
1364 * @param $attribs array
1365 * @param $contents string
1367 public function addElement( $element, $attribs = array(), $contents = '' ) {
1368 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1372 * Clear the body HTML
1374 public function clearHTML() {
1375 $this->mBodytext = '';
1379 * Get the body HTML
1381 * @return String: HTML
1383 public function getHTML() {
1384 return $this->mBodytext;
1388 * Get/set the ParserOptions object to use for wikitext parsing
1390 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1391 * current ParserOption object
1392 * @return ParserOptions object
1394 public function parserOptions( $options = null ) {
1395 if ( !$this->mParserOptions ) {
1396 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1397 $this->mParserOptions->setEditSection( false );
1399 return wfSetVar( $this->mParserOptions, $options );
1403 * Set the revision ID which will be seen by the wiki text parser
1404 * for things such as embedded {{REVISIONID}} variable use.
1406 * @param $revid Mixed: an positive integer, or null
1407 * @return Mixed: previous value
1409 public function setRevisionId( $revid ) {
1410 $val = is_null( $revid ) ? null : intval( $revid );
1411 return wfSetVar( $this->mRevisionId, $val );
1415 * Get the displayed revision ID
1417 * @return Integer
1419 public function getRevisionId() {
1420 return $this->mRevisionId;
1424 * Set the timestamp of the revision which will be displayed. This is used
1425 * to avoid a extra DB call in Skin::lastModified().
1427 * @param $timestamp Mixed: string, or null
1428 * @return Mixed: previous value
1430 public function setRevisionTimestamp( $timestamp ) {
1431 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1435 * Get the timestamp of displayed revision.
1436 * This will be null if not filled by setRevisionTimestamp().
1438 * @return String or null
1440 public function getRevisionTimestamp() {
1441 return $this->mRevisionTimestamp;
1445 * Set the displayed file version
1447 * @param $file File|bool
1448 * @return Mixed: previous value
1450 public function setFileVersion( $file ) {
1451 $val = null;
1452 if ( $file instanceof File && $file->exists() ) {
1453 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1455 return wfSetVar( $this->mFileVersion, $val, true );
1459 * Get the displayed file version
1461 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1463 public function getFileVersion() {
1464 return $this->mFileVersion;
1468 * Get the templates used on this page
1470 * @return Array (namespace => dbKey => revId)
1471 * @since 1.18
1473 public function getTemplateIds() {
1474 return $this->mTemplateIds;
1478 * Get the files used on this page
1480 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1481 * @since 1.18
1483 public function getFileSearchOptions() {
1484 return $this->mImageTimeKeys;
1488 * Convert wikitext to HTML and add it to the buffer
1489 * Default assumes that the current page title will be used.
1491 * @param $text String
1492 * @param $linestart Boolean: is this the start of a line?
1493 * @param $interface Boolean: is this text in the user interface language?
1495 public function addWikiText( $text, $linestart = true, $interface = true ) {
1496 $title = $this->getTitle(); // Work around E_STRICT
1497 if ( !$title ) {
1498 throw new MWException( 'Title is null' );
1500 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1504 * Add wikitext with a custom Title object
1506 * @param string $text wikitext
1507 * @param $title Title object
1508 * @param $linestart Boolean: is this the start of a line?
1510 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1511 $this->addWikiTextTitle( $text, $title, $linestart );
1515 * Add wikitext with a custom Title object and tidy enabled.
1517 * @param string $text wikitext
1518 * @param $title Title object
1519 * @param $linestart Boolean: is this the start of a line?
1521 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1522 $this->addWikiTextTitle( $text, $title, $linestart, true );
1526 * Add wikitext with tidy enabled
1528 * @param string $text wikitext
1529 * @param $linestart Boolean: is this the start of a line?
1531 public function addWikiTextTidy( $text, $linestart = true ) {
1532 $title = $this->getTitle();
1533 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1537 * Add wikitext with a custom Title object
1539 * @param string $text wikitext
1540 * @param $title Title object
1541 * @param $linestart Boolean: is this the start of a line?
1542 * @param $tidy Boolean: whether to use tidy
1543 * @param $interface Boolean: whether it is an interface message
1544 * (for example disables conversion)
1546 public function addWikiTextTitle( $text, Title $title, $linestart, $tidy = false, $interface = false ) {
1547 global $wgParser;
1549 wfProfileIn( __METHOD__ );
1551 $popts = $this->parserOptions();
1552 $oldTidy = $popts->setTidy( $tidy );
1553 $popts->setInterfaceMessage( (bool) $interface );
1555 $parserOutput = $wgParser->parse(
1556 $text, $title, $popts,
1557 $linestart, true, $this->mRevisionId
1560 $popts->setTidy( $oldTidy );
1562 $this->addParserOutput( $parserOutput );
1564 wfProfileOut( __METHOD__ );
1568 * Add a ParserOutput object, but without Html
1570 * @param $parserOutput ParserOutput object
1572 public function addParserOutputNoText( &$parserOutput ) {
1573 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1574 $this->addCategoryLinks( $parserOutput->getCategories() );
1575 $this->mNewSectionLink = $parserOutput->getNewSection();
1576 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1578 $this->mParseWarnings = $parserOutput->getWarnings();
1579 if ( !$parserOutput->isCacheable() ) {
1580 $this->enableClientCache( false );
1582 $this->mNoGallery = $parserOutput->getNoGallery();
1583 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1584 $this->addModules( $parserOutput->getModules() );
1585 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1586 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1587 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1589 // Template versioning...
1590 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1591 if ( isset( $this->mTemplateIds[$ns] ) ) {
1592 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1593 } else {
1594 $this->mTemplateIds[$ns] = $dbks;
1597 // File versioning...
1598 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1599 $this->mImageTimeKeys[$dbk] = $data;
1602 // Hooks registered in the object
1603 global $wgParserOutputHooks;
1604 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1605 list( $hookName, $data ) = $hookInfo;
1606 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1607 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1611 // Link flags are ignored for now, but may in the future be
1612 // used to mark individual language links.
1613 $linkFlags = array();
1614 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1615 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1619 * Add a ParserOutput object
1621 * @param $parserOutput ParserOutput
1623 function addParserOutput( &$parserOutput ) {
1624 $this->addParserOutputNoText( $parserOutput );
1625 $text = $parserOutput->getText();
1626 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1627 $this->addHTML( $text );
1631 * Add the output of a QuickTemplate to the output buffer
1633 * @param $template QuickTemplate
1635 public function addTemplate( &$template ) {
1636 ob_start();
1637 $template->execute();
1638 $this->addHTML( ob_get_contents() );
1639 ob_end_clean();
1643 * Parse wikitext and return the HTML.
1645 * @param $text String
1646 * @param $linestart Boolean: is this the start of a line?
1647 * @param $interface Boolean: use interface language ($wgLang instead of
1648 * $wgContLang) while parsing language sensitive magic
1649 * words like GRAMMAR and PLURAL. This also disables
1650 * LanguageConverter.
1651 * @param $language Language object: target language object, will override
1652 * $interface
1653 * @throws MWException
1654 * @return String: HTML
1656 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1657 global $wgParser;
1659 if ( is_null( $this->getTitle() ) ) {
1660 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1663 $popts = $this->parserOptions();
1664 if ( $interface ) {
1665 $popts->setInterfaceMessage( true );
1667 if ( $language !== null ) {
1668 $oldLang = $popts->setTargetLanguage( $language );
1671 $parserOutput = $wgParser->parse(
1672 $text, $this->getTitle(), $popts,
1673 $linestart, true, $this->mRevisionId
1676 if ( $interface ) {
1677 $popts->setInterfaceMessage( false );
1679 if ( $language !== null ) {
1680 $popts->setTargetLanguage( $oldLang );
1683 return $parserOutput->getText();
1687 * Parse wikitext, strip paragraphs, and return the HTML.
1689 * @param $text String
1690 * @param $linestart Boolean: is this the start of a line?
1691 * @param $interface Boolean: use interface language ($wgLang instead of
1692 * $wgContLang) while parsing language sensitive magic
1693 * words like GRAMMAR and PLURAL
1694 * @return String: HTML
1696 public function parseInline( $text, $linestart = true, $interface = false ) {
1697 $parsed = $this->parse( $text, $linestart, $interface );
1699 $m = array();
1700 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1701 $parsed = $m[1];
1704 return $parsed;
1708 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1710 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1712 public function setSquidMaxage( $maxage ) {
1713 $this->mSquidMaxage = $maxage;
1717 * Use enableClientCache(false) to force it to send nocache headers
1719 * @param $state bool
1721 * @return bool
1723 public function enableClientCache( $state ) {
1724 return wfSetVar( $this->mEnableClientCache, $state );
1728 * Get the list of cookies that will influence on the cache
1730 * @return Array
1732 function getCacheVaryCookies() {
1733 global $wgCookiePrefix, $wgCacheVaryCookies;
1734 static $cookies;
1735 if ( $cookies === null ) {
1736 $cookies = array_merge(
1737 array(
1738 "{$wgCookiePrefix}Token",
1739 "{$wgCookiePrefix}LoggedOut",
1740 session_name()
1742 $wgCacheVaryCookies
1744 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1746 return $cookies;
1750 * Check if the request has a cache-varying cookie header
1751 * If it does, it's very important that we don't allow public caching
1753 * @return Boolean
1755 function haveCacheVaryCookies() {
1756 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1757 if ( $cookieHeader === false ) {
1758 return false;
1760 $cvCookies = $this->getCacheVaryCookies();
1761 foreach ( $cvCookies as $cookieName ) {
1762 # Check for a simple string match, like the way squid does it
1763 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1764 wfDebug( __METHOD__ . ": found $cookieName\n" );
1765 return true;
1768 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1769 return false;
1773 * Add an HTTP header that will influence on the cache
1775 * @param string $header header name
1776 * @param $option Array|null
1777 * @todo FIXME: Document the $option parameter; it appears to be for
1778 * X-Vary-Options but what format is acceptable?
1780 public function addVaryHeader( $header, $option = null ) {
1781 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1782 $this->mVaryHeader[$header] = (array)$option;
1783 } elseif ( is_array( $option ) ) {
1784 if ( is_array( $this->mVaryHeader[$header] ) ) {
1785 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1786 } else {
1787 $this->mVaryHeader[$header] = $option;
1790 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1794 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1795 * such as Accept-Encoding or Cookie
1797 * @return String
1799 public function getVaryHeader() {
1800 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1804 * Get a complete X-Vary-Options header
1806 * @return String
1808 public function getXVO() {
1809 $cvCookies = $this->getCacheVaryCookies();
1811 $cookiesOption = array();
1812 foreach ( $cvCookies as $cookieName ) {
1813 $cookiesOption[] = 'string-contains=' . $cookieName;
1815 $this->addVaryHeader( 'Cookie', $cookiesOption );
1817 $headers = array();
1818 foreach ( $this->mVaryHeader as $header => $option ) {
1819 $newheader = $header;
1820 if ( is_array( $option ) && count( $option ) > 0 ) {
1821 $newheader .= ';' . implode( ';', $option );
1823 $headers[] = $newheader;
1825 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1827 return $xvo;
1831 * bug 21672: Add Accept-Language to Vary and XVO headers
1832 * if there's no 'variant' parameter existed in GET.
1834 * For example:
1835 * /w/index.php?title=Main_page should always be served; but
1836 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1838 function addAcceptLanguage() {
1839 $lang = $this->getTitle()->getPageLanguage();
1840 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1841 $variants = $lang->getVariants();
1842 $aloption = array();
1843 foreach ( $variants as $variant ) {
1844 if ( $variant === $lang->getCode() ) {
1845 continue;
1846 } else {
1847 $aloption[] = 'string-contains=' . $variant;
1849 // IE and some other browsers use BCP 47 standards in
1850 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1851 // We should handle these too.
1852 $variantBCP47 = wfBCP47( $variant );
1853 if ( $variantBCP47 !== $variant ) {
1854 $aloption[] = 'string-contains=' . $variantBCP47;
1858 $this->addVaryHeader( 'Accept-Language', $aloption );
1863 * Set a flag which will cause an X-Frame-Options header appropriate for
1864 * edit pages to be sent. The header value is controlled by
1865 * $wgEditPageFrameOptions.
1867 * This is the default for special pages. If you display a CSRF-protected
1868 * form on an ordinary view page, then you need to call this function.
1870 * @param $enable bool
1872 public function preventClickjacking( $enable = true ) {
1873 $this->mPreventClickjacking = $enable;
1877 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1878 * This can be called from pages which do not contain any CSRF-protected
1879 * HTML form.
1881 public function allowClickjacking() {
1882 $this->mPreventClickjacking = false;
1886 * Get the X-Frame-Options header value (without the name part), or false
1887 * if there isn't one. This is used by Skin to determine whether to enable
1888 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1890 * @return string
1892 public function getFrameOptions() {
1893 global $wgBreakFrames, $wgEditPageFrameOptions;
1894 if ( $wgBreakFrames ) {
1895 return 'DENY';
1896 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1897 return $wgEditPageFrameOptions;
1899 return false;
1903 * Send cache control HTTP headers
1905 public function sendCacheControl() {
1906 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1908 $response = $this->getRequest()->response();
1909 if ( $wgUseETag && $this->mETag ) {
1910 $response->header( "ETag: $this->mETag" );
1913 $this->addVaryHeader( 'Cookie' );
1914 $this->addAcceptLanguage();
1916 # don't serve compressed data to clients who can't handle it
1917 # maintain different caches for logged-in users and non-logged in ones
1918 $response->header( $this->getVaryHeader() );
1920 if ( $wgUseXVO ) {
1921 # Add an X-Vary-Options header for Squid with Wikimedia patches
1922 $response->header( $this->getXVO() );
1925 if ( $this->mEnableClientCache ) {
1926 if (
1927 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1928 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1930 if ( $wgUseESI ) {
1931 # We'll purge the proxy cache explicitly, but require end user agents
1932 # to revalidate against the proxy on each visit.
1933 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1934 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1935 # start with a shorter timeout for initial testing
1936 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1937 $response->header( 'Surrogate-Control: max-age=' . $wgSquidMaxage . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
1938 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1939 } else {
1940 # We'll purge the proxy cache for anons explicitly, but require end user agents
1941 # to revalidate against the proxy on each visit.
1942 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1943 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1944 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1945 # start with a shorter timeout for initial testing
1946 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1947 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0' );
1949 } else {
1950 # We do want clients to cache if they can, but they *must* check for updates
1951 # on revisiting the page.
1952 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1953 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1954 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1956 if ( $this->mLastModified ) {
1957 $response->header( "Last-Modified: {$this->mLastModified}" );
1959 } else {
1960 wfDebug( __METHOD__ . ": no caching **\n", false );
1962 # In general, the absence of a last modified header should be enough to prevent
1963 # the client from using its cache. We send a few other things just to make sure.
1964 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1965 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1966 $response->header( 'Pragma: no-cache' );
1971 * Get the message associated with the HTTP response code $code
1973 * @param $code Integer: status code
1974 * @return String or null: message or null if $code is not in the list of
1975 * messages
1977 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1979 public static function getStatusMessage( $code ) {
1980 wfDeprecated( __METHOD__, '1.18' );
1981 return HttpStatus::getMessage( $code );
1985 * Finally, all the text has been munged and accumulated into
1986 * the object, let's actually output it:
1988 public function output() {
1989 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1991 if ( $this->mDoNothing ) {
1992 return;
1995 wfProfileIn( __METHOD__ );
1997 $response = $this->getRequest()->response();
1999 if ( $this->mRedirect != '' ) {
2000 # Standards require redirect URLs to be absolute
2001 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2003 $redirect = $this->mRedirect;
2004 $code = $this->mRedirectCode;
2006 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2007 if ( $code == '301' || $code == '303' ) {
2008 if ( !$wgDebugRedirects ) {
2009 $message = HttpStatus::getMessage( $code );
2010 $response->header( "HTTP/1.1 $code $message" );
2012 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2014 if ( $wgVaryOnXFP ) {
2015 $this->addVaryHeader( 'X-Forwarded-Proto' );
2017 $this->sendCacheControl();
2019 $response->header( "Content-Type: text/html; charset=utf-8" );
2020 if ( $wgDebugRedirects ) {
2021 $url = htmlspecialchars( $redirect );
2022 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2023 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2024 print "</body>\n</html>\n";
2025 } else {
2026 $response->header( 'Location: ' . $redirect );
2030 wfProfileOut( __METHOD__ );
2031 return;
2032 } elseif ( $this->mStatusCode ) {
2033 $message = HttpStatus::getMessage( $this->mStatusCode );
2034 if ( $message ) {
2035 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2039 # Buffer output; final headers may depend on later processing
2040 ob_start();
2042 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
2043 $response->header( 'Content-language: ' . $wgLanguageCode );
2045 // Prevent framing, if requested
2046 $frameOptions = $this->getFrameOptions();
2047 if ( $frameOptions ) {
2048 $response->header( "X-Frame-Options: $frameOptions" );
2051 if ( $this->mArticleBodyOnly ) {
2052 echo $this->mBodytext;
2053 } else {
2054 $this->addDefaultModules();
2056 $sk = $this->getSkin();
2058 // Hook that allows last minute changes to the output page, e.g.
2059 // adding of CSS or Javascript by extensions.
2060 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2062 wfProfileIn( 'Output-skin' );
2063 $sk->outputPage();
2064 wfProfileOut( 'Output-skin' );
2067 // This hook allows last minute changes to final overall output by modifying output buffer
2068 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2070 $this->sendCacheControl();
2072 ob_end_flush();
2074 wfProfileOut( __METHOD__ );
2078 * Actually output something with print.
2080 * @param string $ins the string to output
2081 * @deprecated since 1.20 Use echo yourself.
2083 public function out( $ins ) {
2084 wfDeprecated( __METHOD__, '1.22' );
2085 print $ins;
2089 * Produce a "user is blocked" page.
2090 * @deprecated since 1.18
2092 function blockedPage() {
2093 throw new UserBlockedError( $this->getUser()->mBlock );
2097 * Prepare this object to display an error page; disable caching and
2098 * indexing, clear the current text and redirect, set the page's title
2099 * and optionally an custom HTML title (content of the "<title>" tag).
2101 * @param string|Message $pageTitle will be passed directly to setPageTitle()
2102 * @param string|Message $htmlTitle will be passed directly to setHTMLTitle();
2103 * optional, if not passed the "<title>" attribute will be
2104 * based on $pageTitle
2106 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2107 $this->setPageTitle( $pageTitle );
2108 if ( $htmlTitle !== false ) {
2109 $this->setHTMLTitle( $htmlTitle );
2111 $this->setRobotPolicy( 'noindex,nofollow' );
2112 $this->setArticleRelated( false );
2113 $this->enableClientCache( false );
2114 $this->mRedirect = '';
2115 $this->clearSubtitle();
2116 $this->clearHTML();
2120 * Output a standard error page
2122 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2123 * showErrorPage( 'titlemsg', $messageObject );
2124 * showErrorPage( $titleMessageObj, $messageObject );
2126 * @param $title Mixed: message key (string) for page title, or a Message object
2127 * @param $msg Mixed: message key (string) for page text, or a Message object
2128 * @param array $params message parameters; ignored if $msg is a Message object
2130 public function showErrorPage( $title, $msg, $params = array() ) {
2131 if ( !$title instanceof Message ) {
2132 $title = $this->msg( $title );
2135 $this->prepareErrorPage( $title );
2137 if ( $msg instanceof Message ) {
2138 $this->addHTML( $msg->parseAsBlock() );
2139 } else {
2140 $this->addWikiMsgArray( $msg, $params );
2143 $this->returnToMain();
2147 * Output a standard permission error page
2149 * @param array $errors error message keys
2150 * @param string $action action that was denied or null if unknown
2152 public function showPermissionsErrorPage( $errors, $action = null ) {
2153 // For some action (read, edit, create and upload), display a "login to do this action"
2154 // error if all of the following conditions are met:
2155 // 1. the user is not logged in
2156 // 2. the only error is insufficient permissions (i.e. no block or something else)
2157 // 3. the error can be avoided simply by logging in
2158 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2159 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2160 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2161 && ( User::groupHasPermission( 'user', $action )
2162 || User::groupHasPermission( 'autoconfirmed', $action ) )
2164 $displayReturnto = null;
2166 # Due to bug 32276, if a user does not have read permissions,
2167 # $this->getTitle() will just give Special:Badtitle, which is
2168 # not especially useful as a returnto parameter. Use the title
2169 # from the request instead, if there was one.
2170 $request = $this->getRequest();
2171 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2172 if ( $action == 'edit' ) {
2173 $msg = 'whitelistedittext';
2174 $displayReturnto = $returnto;
2175 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2176 $msg = 'nocreatetext';
2177 } elseif ( $action == 'upload' ) {
2178 $msg = 'uploadnologintext';
2179 } else { # Read
2180 $msg = 'loginreqpagetext';
2181 $displayReturnto = Title::newMainPage();
2184 $query = array();
2186 if ( $returnto ) {
2187 $query['returnto'] = $returnto->getPrefixedText();
2189 if ( !$request->wasPosted() ) {
2190 $returntoquery = $request->getValues();
2191 unset( $returntoquery['title'] );
2192 unset( $returntoquery['returnto'] );
2193 unset( $returntoquery['returntoquery'] );
2194 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2197 $loginLink = Linker::linkKnown(
2198 SpecialPage::getTitleFor( 'Userlogin' ),
2199 $this->msg( 'loginreqlink' )->escaped(),
2200 array(),
2201 $query
2204 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2205 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2207 # Don't return to a page the user can't read otherwise
2208 # we'll end up in a pointless loop
2209 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2210 $this->returnToMain( null, $displayReturnto );
2212 } else {
2213 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2214 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2219 * Display an error page indicating that a given version of MediaWiki is
2220 * required to use it
2222 * @param $version Mixed: the version of MediaWiki needed to use the page
2224 public function versionRequired( $version ) {
2225 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2227 $this->addWikiMsg( 'versionrequiredtext', $version );
2228 $this->returnToMain();
2232 * Display an error page noting that a given permission bit is required.
2233 * @deprecated since 1.18, just throw the exception directly
2234 * @param string $permission key required
2235 * @throws PermissionsError
2237 public function permissionRequired( $permission ) {
2238 throw new PermissionsError( $permission );
2242 * Produce the stock "please login to use the wiki" page
2244 * @deprecated in 1.19; throw the exception directly
2246 public function loginToUse() {
2247 throw new PermissionsError( 'read' );
2251 * Format a list of error messages
2253 * @param array $errors of arrays returned by Title::getUserPermissionsErrors
2254 * @param string $action action that was denied or null if unknown
2255 * @return String: the wikitext error-messages, formatted into a list.
2257 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2258 if ( $action == null ) {
2259 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2260 } else {
2261 $action_desc = $this->msg( "action-$action" )->plain();
2262 $text = $this->msg(
2263 'permissionserrorstext-withaction',
2264 count( $errors ),
2265 $action_desc
2266 )->plain() . "\n\n";
2269 if ( count( $errors ) > 1 ) {
2270 $text .= '<ul class="permissions-errors">' . "\n";
2272 foreach ( $errors as $error ) {
2273 $text .= '<li>';
2274 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2275 $text .= "</li>\n";
2277 $text .= '</ul>';
2278 } else {
2279 $text .= "<div class=\"permissions-errors\">\n" .
2280 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2281 "\n</div>";
2284 return $text;
2288 * Display a page stating that the Wiki is in read-only mode,
2289 * and optionally show the source of the page that the user
2290 * was trying to edit. Should only be called (for this
2291 * purpose) after wfReadOnly() has returned true.
2293 * For historical reasons, this function is _also_ used to
2294 * show the error message when a user tries to edit a page
2295 * they are not allowed to edit. (Unless it's because they're
2296 * blocked, then we show blockedPage() instead.) In this
2297 * case, the second parameter should be set to true and a list
2298 * of reasons supplied as the third parameter.
2300 * @todo Needs to be split into multiple functions.
2302 * @param $source String: source code to show (or null).
2303 * @param $protected Boolean: is this a permissions error?
2304 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2305 * @param $action String: action that was denied or null if unknown
2306 * @throws ReadOnlyError
2308 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2309 $this->setRobotPolicy( 'noindex,nofollow' );
2310 $this->setArticleRelated( false );
2312 // If no reason is given, just supply a default "I can't let you do
2313 // that, Dave" message. Should only occur if called by legacy code.
2314 if ( $protected && empty( $reasons ) ) {
2315 $reasons[] = array( 'badaccess-group0' );
2318 if ( !empty( $reasons ) ) {
2319 // Permissions error
2320 if ( $source ) {
2321 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2322 $this->addBacklinkSubtitle( $this->getTitle() );
2323 } else {
2324 $this->setPageTitle( $this->msg( 'badaccess' ) );
2326 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2327 } else {
2328 // Wiki is read only
2329 throw new ReadOnlyError;
2332 // Show source, if supplied
2333 if ( is_string( $source ) ) {
2334 $this->addWikiMsg( 'viewsourcetext' );
2336 $pageLang = $this->getTitle()->getPageLanguage();
2337 $params = array(
2338 'id' => 'wpTextbox1',
2339 'name' => 'wpTextbox1',
2340 'cols' => $this->getUser()->getOption( 'cols' ),
2341 'rows' => $this->getUser()->getOption( 'rows' ),
2342 'readonly' => 'readonly',
2343 'lang' => $pageLang->getHtmlCode(),
2344 'dir' => $pageLang->getDir(),
2346 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2348 // Show templates used by this article
2349 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2350 $this->addHTML( "<div class='templatesUsed'>
2351 $templates
2352 </div>
2353 " );
2356 # If the title doesn't exist, it's fairly pointless to print a return
2357 # link to it. After all, you just tried editing it and couldn't, so
2358 # what's there to do there?
2359 if ( $this->getTitle()->exists() ) {
2360 $this->returnToMain( null, $this->getTitle() );
2365 * Turn off regular page output and return an error response
2366 * for when rate limiting has triggered.
2368 public function rateLimited() {
2369 throw new ThrottledError;
2373 * Show a warning about slave lag
2375 * If the lag is higher than $wgSlaveLagCritical seconds,
2376 * then the warning is a bit more obvious. If the lag is
2377 * lower than $wgSlaveLagWarning, then no warning is shown.
2379 * @param $lag Integer: slave lag
2381 public function showLagWarning( $lag ) {
2382 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2383 if ( $lag >= $wgSlaveLagWarning ) {
2384 $message = $lag < $wgSlaveLagCritical
2385 ? 'lag-warn-normal'
2386 : 'lag-warn-high';
2387 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2388 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2392 public function showFatalError( $message ) {
2393 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2395 $this->addHTML( $message );
2398 public function showUnexpectedValueError( $name, $val ) {
2399 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2402 public function showFileCopyError( $old, $new ) {
2403 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2406 public function showFileRenameError( $old, $new ) {
2407 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2410 public function showFileDeleteError( $name ) {
2411 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2414 public function showFileNotFoundError( $name ) {
2415 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2419 * Add a "return to" link pointing to a specified title
2421 * @param $title Title to link
2422 * @param array $query query string parameters
2423 * @param string $text text of the link (input is not escaped)
2424 * @param $options Options array to pass to Linker
2426 public function addReturnTo( $title, $query = array(), $text = null, $options = array() ) {
2427 if ( in_array( 'http', $options ) ) {
2428 $proto = PROTO_HTTP;
2429 } elseif ( in_array( 'https', $options ) ) {
2430 $proto = PROTO_HTTPS;
2431 } else {
2432 $proto = PROTO_RELATIVE;
2435 $link = $this->msg( 'returnto' )->rawParams(
2436 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2437 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2441 * Add a "return to" link pointing to a specified title,
2442 * or the title indicated in the request, or else the main page
2444 * @param $unused
2445 * @param $returnto Title or String to return to
2446 * @param string $returntoquery query string for the return to link
2448 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2449 if ( $returnto == null ) {
2450 $returnto = $this->getRequest()->getText( 'returnto' );
2453 if ( $returntoquery == null ) {
2454 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2457 if ( $returnto === '' ) {
2458 $returnto = Title::newMainPage();
2461 if ( is_object( $returnto ) ) {
2462 $titleObj = $returnto;
2463 } else {
2464 $titleObj = Title::newFromText( $returnto );
2466 if ( !is_object( $titleObj ) ) {
2467 $titleObj = Title::newMainPage();
2470 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2474 * @param $sk Skin The given Skin
2475 * @param $includeStyle Boolean: unused
2476 * @return String: The doctype, opening "<html>", and head element.
2478 public function headElement( Skin $sk, $includeStyle = true ) {
2479 global $wgContLang, $wgMimeType;
2481 $userdir = $this->getLanguage()->getDir();
2482 $sitedir = $wgContLang->getDir();
2484 if ( $sk->commonPrintStylesheet() ) {
2485 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2488 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2490 if ( $this->getHTMLTitle() == '' ) {
2491 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2494 $openHead = Html::openElement( 'head' );
2495 if ( $openHead ) {
2496 # Don't bother with the newline if $head == ''
2497 $ret .= "$openHead\n";
2500 if ( !Html::isXmlMimeType( $wgMimeType ) ) {
2501 // Add <meta charset="UTF-8">
2502 // This should be before <title> since it defines the charset used by
2503 // text including the text inside <title>.
2504 // The spec recommends defining XHTML5's charset using the XML declaration
2505 // instead of meta.
2506 // Our XML declaration is output by Html::htmlHeader.
2507 // http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#attr-meta-http-equiv-content-type
2508 // http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#charset
2509 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
2512 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2514 $ret .= implode( "\n", array(
2515 $this->getHeadLinks(),
2516 $this->buildCssLinks(),
2517 $this->getHeadScripts(),
2518 $this->getHeadItems()
2519 ) );
2521 $closeHead = Html::closeElement( 'head' );
2522 if ( $closeHead ) {
2523 $ret .= "$closeHead\n";
2526 $bodyClasses = array();
2527 $bodyClasses[] = 'mediawiki';
2529 # Classes for LTR/RTL directionality support
2530 $bodyClasses[] = $userdir;
2531 $bodyClasses[] = "sitedir-$sitedir";
2533 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2534 # A <body> class is probably not the best way to do this . . .
2535 $bodyClasses[] = 'capitalize-all-nouns';
2538 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2539 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2540 $bodyClasses[] = 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2542 $bodyAttrs = array();
2543 // While the implode() is not strictly needed, it's used for backwards compatibility
2544 // (this used to be built as a string and hooks likely still expect that).
2545 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2547 // Allow skins and extensions to add body attributes they need
2548 $sk->addToBodyAttributes( $this, $bodyAttrs );
2549 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2551 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2553 return $ret;
2557 * Add the default ResourceLoader modules to this object
2559 private function addDefaultModules() {
2560 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2561 $wgAjaxWatch, $wgResponsiveImages;
2563 // Add base resources
2564 $this->addModules( array(
2565 'mediawiki.user',
2566 'mediawiki.page.startup',
2567 'mediawiki.page.ready',
2568 ) );
2569 if ( $wgIncludeLegacyJavaScript ) {
2570 $this->addModules( 'mediawiki.legacy.wikibits' );
2573 if ( $wgPreloadJavaScriptMwUtil ) {
2574 $this->addModules( 'mediawiki.util' );
2577 MWDebug::addModules( $this );
2579 // Add various resources if required
2580 if ( $wgUseAjax ) {
2581 $this->addModules( 'mediawiki.legacy.ajax' );
2583 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2585 if ( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2586 $this->addModules( 'mediawiki.page.watch.ajax' );
2589 if ( !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2590 $this->addModules( 'mediawiki.searchSuggest' );
2594 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2595 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2598 # Crazy edit-on-double-click stuff
2599 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2600 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2603 // Support for high-density display images
2604 if ( $wgResponsiveImages ) {
2605 $this->addModules( 'mediawiki.hidpi' );
2610 * Get a ResourceLoader object associated with this OutputPage
2612 * @return ResourceLoader
2614 public function getResourceLoader() {
2615 if ( is_null( $this->mResourceLoader ) ) {
2616 $this->mResourceLoader = new ResourceLoader();
2618 return $this->mResourceLoader;
2622 * TODO: Document
2623 * @param $modules Array/string with the module name(s)
2624 * @param string $only ResourceLoaderModule TYPE_ class constant
2625 * @param $useESI boolean
2626 * @param array $extraQuery with extra query parameters to add to each request. array( param => value )
2627 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2628 * @return string html "<script>" and "<style>" tags
2630 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2631 global $wgResourceLoaderUseESI;
2633 $modules = (array) $modules;
2635 if ( !count( $modules ) ) {
2636 return '';
2639 if ( count( $modules ) > 1 ) {
2640 // Remove duplicate module requests
2641 $modules = array_unique( $modules );
2642 // Sort module names so requests are more uniform
2643 sort( $modules );
2645 if ( ResourceLoader::inDebugMode() ) {
2646 // Recursively call us for every item
2647 $links = '';
2648 foreach ( $modules as $name ) {
2649 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2651 return $links;
2654 if ( !is_null( $this->mTarget ) ) {
2655 $extraQuery['target'] = $this->mTarget;
2658 // Create keyed-by-group list of module objects from modules list
2659 $groups = array();
2660 $resourceLoader = $this->getResourceLoader();
2661 foreach ( $modules as $name ) {
2662 $module = $resourceLoader->getModule( $name );
2663 # Check that we're allowed to include this module on this page
2664 if ( !$module
2665 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2666 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2667 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2668 && $only == ResourceLoaderModule::TYPE_STYLES )
2669 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2671 continue;
2674 $group = $module->getGroup();
2675 if ( !isset( $groups[$group] ) ) {
2676 $groups[$group] = array();
2678 $groups[$group][$name] = $module;
2681 $links = '';
2682 foreach ( $groups as $group => $grpModules ) {
2683 // Special handling for user-specific groups
2684 $user = null;
2685 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2686 $user = $this->getUser()->getName();
2689 // Create a fake request based on the one we are about to make so modules return
2690 // correct timestamp and emptiness data
2691 $query = ResourceLoader::makeLoaderQuery(
2692 array(), // modules; not determined yet
2693 $this->getLanguage()->getCode(),
2694 $this->getSkin()->getSkinName(),
2695 $user,
2696 null, // version; not determined yet
2697 ResourceLoader::inDebugMode(),
2698 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2699 $this->isPrintable(),
2700 $this->getRequest()->getBool( 'handheld' ),
2701 $extraQuery
2703 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2704 // Extract modules that know they're empty
2705 $emptyModules = array();
2706 foreach ( $grpModules as $key => $module ) {
2707 if ( $module->isKnownEmpty( $context ) ) {
2708 $emptyModules[$key] = 'ready';
2709 unset( $grpModules[$key] );
2712 // Inline empty modules: since they're empty, just mark them as 'ready'
2713 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2714 // If we're only getting the styles, we don't need to do anything for empty modules.
2715 $links .= Html::inlineScript(
2716 ResourceLoader::makeLoaderConditionalScript(
2717 ResourceLoader::makeLoaderStateScript( $emptyModules )
2719 ) . "\n";
2722 // If there are no modules left, skip this group
2723 if ( count( $grpModules ) === 0 ) {
2724 continue;
2727 // Inline private modules. These can't be loaded through load.php for security
2728 // reasons, see bug 34907. Note that these modules should be loaded from
2729 // getHeadScripts() before the first loader call. Otherwise other modules can't
2730 // properly use them as dependencies (bug 30914)
2731 if ( $group === 'private' ) {
2732 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2733 $links .= Html::inlineStyle(
2734 $resourceLoader->makeModuleResponse( $context, $grpModules )
2736 } else {
2737 $links .= Html::inlineScript(
2738 ResourceLoader::makeLoaderConditionalScript(
2739 $resourceLoader->makeModuleResponse( $context, $grpModules )
2743 $links .= "\n";
2744 continue;
2746 // Special handling for the user group; because users might change their stuff
2747 // on-wiki like user pages, or user preferences; we need to find the highest
2748 // timestamp of these user-changeable modules so we can ensure cache misses on change
2749 // This should NOT be done for the site group (bug 27564) because anons get that too
2750 // and we shouldn't be putting timestamps in Squid-cached HTML
2751 $version = null;
2752 if ( $group === 'user' ) {
2753 // Get the maximum timestamp
2754 $timestamp = 1;
2755 foreach ( $grpModules as $module ) {
2756 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2758 // Add a version parameter so cache will break when things change
2759 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2762 $url = ResourceLoader::makeLoaderURL(
2763 array_keys( $grpModules ),
2764 $this->getLanguage()->getCode(),
2765 $this->getSkin()->getSkinName(),
2766 $user,
2767 $version,
2768 ResourceLoader::inDebugMode(),
2769 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2770 $this->isPrintable(),
2771 $this->getRequest()->getBool( 'handheld' ),
2772 $extraQuery
2774 if ( $useESI && $wgResourceLoaderUseESI ) {
2775 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2776 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2777 $link = Html::inlineStyle( $esi );
2778 } else {
2779 $link = Html::inlineScript( $esi );
2781 } else {
2782 // Automatically select style/script elements
2783 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2784 $link = Html::linkedStyle( $url );
2785 } elseif ( $loadCall ) {
2786 $link = Html::inlineScript(
2787 ResourceLoader::makeLoaderConditionalScript(
2788 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2791 } else {
2792 $link = Html::linkedScript( $url );
2796 if ( $group == 'noscript' ) {
2797 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2798 } else {
2799 $links .= $link . "\n";
2802 return $links;
2806 * JS stuff to put in the "<head>". This is the startup module, config
2807 * vars and modules marked with position 'top'
2809 * @return String: HTML fragment
2811 function getHeadScripts() {
2812 global $wgResourceLoaderExperimentalAsyncLoading;
2814 // Startup - this will immediately load jquery and mediawiki modules
2815 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2817 // Load config before anything else
2818 $scripts .= Html::inlineScript(
2819 ResourceLoader::makeLoaderConditionalScript(
2820 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2824 // Load embeddable private modules before any loader links
2825 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2826 // in mw.loader.implement() calls and deferred until mw.user is available
2827 $embedScripts = array( 'user.options', 'user.tokens' );
2828 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2830 // Script and Messages "only" requests marked for top inclusion
2831 // Messages should go first
2832 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2833 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2835 // Modules requests - let the client calculate dependencies and batch requests as it likes
2836 // Only load modules that have marked themselves for loading at the top
2837 $modules = $this->getModules( true, 'top' );
2838 if ( $modules ) {
2839 $scripts .= Html::inlineScript(
2840 ResourceLoader::makeLoaderConditionalScript(
2841 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2846 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2847 $scripts .= $this->getScriptsForBottomQueue( true );
2850 return $scripts;
2854 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2855 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2856 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2857 * user preferences, site JS and user JS
2859 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2860 * @return string
2862 function getScriptsForBottomQueue( $inHead ) {
2863 global $wgUseSiteJs, $wgAllowUserJs;
2865 // Script and Messages "only" requests marked for bottom inclusion
2866 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2867 // Messages should go first
2868 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2869 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2870 /* $loadCall = */ $inHead
2872 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2873 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2874 /* $loadCall = */ $inHead
2877 // Modules requests - let the client calculate dependencies and batch requests as it likes
2878 // Only load modules that have marked themselves for loading at the bottom
2879 $modules = $this->getModules( true, 'bottom' );
2880 if ( $modules ) {
2881 $scripts .= Html::inlineScript(
2882 ResourceLoader::makeLoaderConditionalScript(
2883 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2888 // Legacy Scripts
2889 $scripts .= "\n" . $this->mScripts;
2891 $defaultModules = array();
2893 // Add site JS if enabled
2894 if ( $wgUseSiteJs ) {
2895 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2896 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2898 $defaultModules['site'] = 'loading';
2899 } else {
2900 // Site module is empty, save request by marking ready in advance (bug 46857)
2901 $defaultModules['site'] = 'ready';
2904 // Add user JS if enabled
2905 if ( $wgAllowUserJs ) {
2906 if ( $this->getUser()->isLoggedIn() ) {
2907 if ( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2908 # XXX: additional security check/prompt?
2909 // We're on a preview of a JS subpage
2910 // Exclude this page from the user module in case it's in there (bug 26283)
2911 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2912 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2914 // Load the previewed JS
2915 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2916 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2917 // asynchronously and may arrive *after* the inline script here. So the previewed code
2918 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2919 } else {
2920 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2921 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2922 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2925 $defaultModules['user'] = 'loading';
2926 } else {
2927 // Non-logged-in users have an empty user module.
2928 // Save request by marking ready in advance (bug 46857)
2929 $defaultModules['user'] = 'ready';
2931 } else {
2932 // User modules are disabled on this wiki.
2933 // Save request by marking ready in advance (bug 46857)
2934 $defaultModules['user'] = 'ready';
2937 // Group JS is only enabled if site JS is enabled.
2938 if ( $wgUseSiteJs ) {
2939 if ( $this->getUser()->isLoggedIn() ) {
2940 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2941 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2943 $defaultModules['user.groups'] = 'loading';
2944 } else {
2945 // Non-logged-in users have no user.groups module.
2946 // Save request by marking ready in advance (bug 46857)
2947 $defaultModules['user.groups'] = 'ready';
2949 } else {
2950 // Site (and group JS) disabled
2951 $defaultModules['user.groups'] = 'ready';
2954 $loaderInit = '';
2955 if ( $inHead ) {
2956 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2957 foreach ( $defaultModules as $m => $state ) {
2958 if ( $state == 'loading' ) {
2959 unset( $defaultModules[$m] );
2963 if ( count( $defaultModules ) > 0 ) {
2964 $loaderInit = Html::inlineScript(
2965 ResourceLoader::makeLoaderConditionalScript(
2966 ResourceLoader::makeLoaderStateScript( $defaultModules )
2968 ) . "\n";
2970 return $loaderInit . $scripts;
2974 * JS stuff to put at the bottom of the "<body>"
2975 * @return string
2977 function getBottomScripts() {
2978 global $wgResourceLoaderExperimentalAsyncLoading;
2980 // Optimise jQuery ready event cross-browser.
2981 // This also enforces $.isReady to be true at </body> which fixes the
2982 // mw.loader bug in Firefox with using document.write between </body>
2983 // and the DOMContentReady event (bug 47457).
2984 $html = Html::inlineScript( 'window.jQuery && jQuery.ready();' );
2986 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2987 $html .= $this->getScriptsForBottomQueue( false );
2990 return $html;
2994 * Add one or more variables to be set in mw.config in JavaScript.
2996 * @param $keys {String|Array} Key or array of key/value pairs.
2997 * @param $value {Mixed} [optional] Value of the configuration variable.
2999 public function addJsConfigVars( $keys, $value = null ) {
3000 if ( is_array( $keys ) ) {
3001 foreach ( $keys as $key => $value ) {
3002 $this->mJsConfigVars[$key] = $value;
3004 return;
3007 $this->mJsConfigVars[$keys] = $value;
3011 * Get an array containing the variables to be set in mw.config in JavaScript.
3013 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
3014 * This is only public until that function is removed. You have been warned.
3016 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3017 * - in other words, page-independent/site-wide variables (without state).
3018 * You will only be adding bloat to the html page and causing page caches to
3019 * have to be purged on configuration changes.
3020 * @return array
3022 public function getJSVars() {
3023 global $wgContLang;
3025 $latestRevID = 0;
3026 $pageID = 0;
3027 $canonicalName = false; # bug 21115
3029 $title = $this->getTitle();
3030 $ns = $title->getNamespace();
3031 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
3033 // Get the relevant title so that AJAX features can use the correct page name
3034 // when making API requests from certain special pages (bug 34972).
3035 $relevantTitle = $this->getSkin()->getRelevantTitle();
3037 if ( $ns == NS_SPECIAL ) {
3038 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
3039 } elseif ( $this->canUseWikiPage() ) {
3040 $wikiPage = $this->getWikiPage();
3041 $latestRevID = $wikiPage->getLatest();
3042 $pageID = $wikiPage->getId();
3045 $lang = $title->getPageLanguage();
3047 // Pre-process information
3048 $separatorTransTable = $lang->separatorTransformTable();
3049 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3050 $compactSeparatorTransTable = array(
3051 implode( "\t", array_keys( $separatorTransTable ) ),
3052 implode( "\t", $separatorTransTable ),
3054 $digitTransTable = $lang->digitTransformTable();
3055 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3056 $compactDigitTransTable = array(
3057 implode( "\t", array_keys( $digitTransTable ) ),
3058 implode( "\t", $digitTransTable ),
3061 $user = $this->getUser();
3063 $vars = array(
3064 'wgCanonicalNamespace' => $nsname,
3065 'wgCanonicalSpecialPageName' => $canonicalName,
3066 'wgNamespaceNumber' => $title->getNamespace(),
3067 'wgPageName' => $title->getPrefixedDBkey(),
3068 'wgTitle' => $title->getText(),
3069 'wgCurRevisionId' => $latestRevID,
3070 'wgArticleId' => $pageID,
3071 'wgIsArticle' => $this->isArticle(),
3072 'wgAction' => Action::getActionName( $this->getContext() ),
3073 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3074 'wgUserGroups' => $user->getEffectiveGroups(),
3075 'wgCategories' => $this->getCategories(),
3076 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3077 'wgPageContentLanguage' => $lang->getCode(),
3078 'wgPageContentModel' => $title->getContentModel(),
3079 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3080 'wgDigitTransformTable' => $compactDigitTransTable,
3081 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3082 'wgMonthNames' => $lang->getMonthNamesArray(),
3083 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3084 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3086 if ( $user->isLoggedIn() ) {
3087 $vars['wgUserId'] = $user->getId();
3088 $vars['wgUserEditCount'] = $user->getEditCount();
3089 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3090 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3091 // Get the revision ID of the oldest new message on the user's talk
3092 // page. This can be used for constructing new message alerts on
3093 // the client side.
3094 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3096 if ( $wgContLang->hasVariants() ) {
3097 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3099 foreach ( $title->getRestrictionTypes() as $type ) {
3100 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3102 if ( $title->isMainPage() ) {
3103 $vars['wgIsMainPage'] = true;
3105 if ( $this->mRedirectedFrom ) {
3106 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3109 // Allow extensions to add their custom variables to the mw.config map.
3110 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3111 // page-dependant but site-wide (without state).
3112 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3113 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3115 // Merge in variables from addJsConfigVars last
3116 return array_merge( $vars, $this->mJsConfigVars );
3120 * To make it harder for someone to slip a user a fake
3121 * user-JavaScript or user-CSS preview, a random token
3122 * is associated with the login session. If it's not
3123 * passed back with the preview request, we won't render
3124 * the code.
3126 * @return bool
3128 public function userCanPreview() {
3129 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3130 || !$this->getRequest()->wasPosted()
3131 || !$this->getUser()->matchEditToken(
3132 $this->getRequest()->getVal( 'wpEditToken' ) )
3134 return false;
3136 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3137 return false;
3140 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3144 * @return array in format "link name or number => 'link html'".
3146 public function getHeadLinksArray() {
3147 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3148 $wgSitename, $wgVersion,
3149 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3150 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3151 $wgRightsPage, $wgRightsUrl;
3153 $tags = array();
3155 $canonicalUrl = $this->mCanonicalUrl;
3157 $tags['meta-generator'] = Html::element( 'meta', array(
3158 'name' => 'generator',
3159 'content' => "MediaWiki $wgVersion",
3160 ) );
3162 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3163 if ( $p !== 'index,follow' ) {
3164 // http://www.robotstxt.org/wc/meta-user.html
3165 // Only show if it's different from the default robots policy
3166 $tags['meta-robots'] = Html::element( 'meta', array(
3167 'name' => 'robots',
3168 'content' => $p,
3169 ) );
3172 if ( count( $this->mKeywords ) > 0 ) {
3173 $strip = array(
3174 "/<.*?" . ">/" => '',
3175 "/_/" => ' '
3177 $tags['meta-keywords'] = Html::element( 'meta', array(
3178 'name' => 'keywords',
3179 'content' => preg_replace(
3180 array_keys( $strip ),
3181 array_values( $strip ),
3182 implode( ',', $this->mKeywords )
3184 ) );
3187 foreach ( $this->mMetatags as $tag ) {
3188 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3189 $a = 'http-equiv';
3190 $tag[0] = substr( $tag[0], 5 );
3191 } else {
3192 $a = 'name';
3194 $tagName = "meta-{$tag[0]}";
3195 if ( isset( $tags[$tagName] ) ) {
3196 $tagName .= $tag[1];
3198 $tags[$tagName] = Html::element( 'meta',
3199 array(
3200 $a => $tag[0],
3201 'content' => $tag[1]
3206 foreach ( $this->mLinktags as $tag ) {
3207 $tags[] = Html::element( 'link', $tag );
3210 # Universal edit button
3211 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3212 $user = $this->getUser();
3213 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3214 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3215 // Original UniversalEditButton
3216 $msg = $this->msg( 'edit' )->text();
3217 $tags['universal-edit-button'] = Html::element( 'link', array(
3218 'rel' => 'alternate',
3219 'type' => 'application/x-wiki',
3220 'title' => $msg,
3221 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3222 ) );
3223 // Alternate edit link
3224 $tags['alternative-edit'] = Html::element( 'link', array(
3225 'rel' => 'edit',
3226 'title' => $msg,
3227 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3228 ) );
3232 # Generally the order of the favicon and apple-touch-icon links
3233 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3234 # uses whichever one appears later in the HTML source. Make sure
3235 # apple-touch-icon is specified first to avoid this.
3236 if ( $wgAppleTouchIcon !== false ) {
3237 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3240 if ( $wgFavicon !== false ) {
3241 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3244 # OpenSearch description link
3245 $tags['opensearch'] = Html::element( 'link', array(
3246 'rel' => 'search',
3247 'type' => 'application/opensearchdescription+xml',
3248 'href' => wfScript( 'opensearch_desc' ),
3249 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3250 ) );
3252 if ( $wgEnableAPI ) {
3253 # Real Simple Discovery link, provides auto-discovery information
3254 # for the MediaWiki API (and potentially additional custom API
3255 # support such as WordPress or Twitter-compatible APIs for a
3256 # blogging extension, etc)
3257 $tags['rsd'] = Html::element( 'link', array(
3258 'rel' => 'EditURI',
3259 'type' => 'application/rsd+xml',
3260 // Output a protocol-relative URL here if $wgServer is protocol-relative
3261 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3262 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3263 ) );
3266 # Language variants
3267 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3268 $lang = $this->getTitle()->getPageLanguage();
3269 if ( $lang->hasVariants() ) {
3271 $urlvar = $lang->getURLVariant();
3273 if ( !$urlvar ) {
3274 $variants = $lang->getVariants();
3275 foreach ( $variants as $_v ) {
3276 $tags["variant-$_v"] = Html::element( 'link', array(
3277 'rel' => 'alternate',
3278 'hreflang' => $_v,
3279 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3282 } else {
3283 $canonicalUrl = $this->getTitle()->getLocalURL();
3288 # Copyright
3289 $copyright = '';
3290 if ( $wgRightsPage ) {
3291 $copy = Title::newFromText( $wgRightsPage );
3293 if ( $copy ) {
3294 $copyright = $copy->getLocalURL();
3298 if ( !$copyright && $wgRightsUrl ) {
3299 $copyright = $wgRightsUrl;
3302 if ( $copyright ) {
3303 $tags['copyright'] = Html::element( 'link', array(
3304 'rel' => 'copyright',
3305 'href' => $copyright )
3309 # Feeds
3310 if ( $wgFeed ) {
3311 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3312 # Use the page name for the title. In principle, this could
3313 # lead to issues with having the same name for different feeds
3314 # corresponding to the same page, but we can't avoid that at
3315 # this low a level.
3317 $tags[] = $this->feedLink(
3318 $format,
3319 $link,
3320 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3321 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3325 # Recent changes feed should appear on every page (except recentchanges,
3326 # that would be redundant). Put it after the per-page feed to avoid
3327 # changing existing behavior. It's still available, probably via a
3328 # menu in your browser. Some sites might have a different feed they'd
3329 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3330 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3331 # If so, use it instead.
3332 if ( $wgOverrideSiteFeed ) {
3333 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3334 // Note, this->feedLink escapes the url.
3335 $tags[] = $this->feedLink(
3336 $type,
3337 $feedUrl,
3338 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3341 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3342 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3343 foreach ( $wgAdvertisedFeedTypes as $format ) {
3344 $tags[] = $this->feedLink(
3345 $format,
3346 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3347 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3353 # Canonical URL
3354 global $wgEnableCanonicalServerLink;
3355 if ( $wgEnableCanonicalServerLink ) {
3356 if ( $canonicalUrl !== false ) {
3357 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3358 } else {
3359 $reqUrl = $this->getRequest()->getRequestURL();
3360 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3363 if ( $canonicalUrl !== false ) {
3364 $tags[] = Html::element( 'link', array(
3365 'rel' => 'canonical',
3366 'href' => $canonicalUrl
3367 ) );
3370 return $tags;
3374 * @return string HTML tag links to be put in the header.
3376 public function getHeadLinks() {
3377 return implode( "\n", $this->getHeadLinksArray() );
3381 * Generate a "<link rel/>" for a feed.
3383 * @param string $type feed type
3384 * @param string $url URL to the feed
3385 * @param string $text value of the "title" attribute
3386 * @return String: HTML fragment
3388 private function feedLink( $type, $url, $text ) {
3389 return Html::element( 'link', array(
3390 'rel' => 'alternate',
3391 'type' => "application/$type+xml",
3392 'title' => $text,
3393 'href' => $url )
3398 * Add a local or specified stylesheet, with the given media options.
3399 * Meant primarily for internal use...
3401 * @param string $style URL to the file
3402 * @param string $media to specify a media type, 'screen', 'printable', 'handheld' or any.
3403 * @param string $condition for IE conditional comments, specifying an IE version
3404 * @param string $dir set to 'rtl' or 'ltr' for direction-specific sheets
3406 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3407 $options = array();
3408 // Even though we expect the media type to be lowercase, but here we
3409 // force it to lowercase to be safe.
3410 if ( $media ) {
3411 $options['media'] = $media;
3413 if ( $condition ) {
3414 $options['condition'] = $condition;
3416 if ( $dir ) {
3417 $options['dir'] = $dir;
3419 $this->styles[$style] = $options;
3423 * Adds inline CSS styles
3424 * @param $style_css Mixed: inline CSS
3425 * @param string $flip Set to 'flip' to flip the CSS if needed
3427 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3428 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3429 # If wanted, and the interface is right-to-left, flip the CSS
3430 $style_css = CSSJanus::transform( $style_css, true, false );
3432 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3436 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3437 * These will be applied to various media & IE conditionals.
3439 * @return string
3441 public function buildCssLinks() {
3442 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs, $wgContLang;
3444 $this->getSkin()->setupSkinUserCss( $this );
3446 // Add ResourceLoader styles
3447 // Split the styles into four groups
3448 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3449 $otherTags = ''; // Tags to append after the normal <link> tags
3450 $resourceLoader = $this->getResourceLoader();
3452 $moduleStyles = $this->getModuleStyles();
3454 // Per-site custom styles
3455 if ( $wgUseSiteCss ) {
3456 $moduleStyles[] = 'site';
3457 $moduleStyles[] = 'noscript';
3458 if ( $this->getUser()->isLoggedIn() ) {
3459 $moduleStyles[] = 'user.groups';
3463 // Per-user custom styles
3464 if ( $wgAllowUserCss ) {
3465 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3466 // We're on a preview of a CSS subpage
3467 // Exclude this page from the user module in case it's in there (bug 26283)
3468 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3469 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3472 // Load the previewed CSS
3473 // If needed, Janus it first. This is user-supplied CSS, so it's
3474 // assumed to be right for the content language directionality.
3475 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3476 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3477 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3479 $otherTags .= Html::inlineStyle( $previewedCSS );
3480 } else {
3481 // Load the user styles normally
3482 $moduleStyles[] = 'user';
3486 // Per-user preference styles
3487 if ( $wgAllowUserCssPrefs ) {
3488 $moduleStyles[] = 'user.cssprefs';
3491 foreach ( $moduleStyles as $name ) {
3492 $module = $resourceLoader->getModule( $name );
3493 if ( !$module ) {
3494 continue;
3496 $group = $module->getGroup();
3497 // Modules in groups named "other" or anything different than "user", "site" or "private"
3498 // will be placed in the "other" group
3499 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3502 // We want site, private and user styles to override dynamically added styles from modules, but we want
3503 // dynamically added styles to override statically added styles from other modules. So the order
3504 // has to be other, dynamic, site, private, user
3505 // Add statically added styles for other modules
3506 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3507 // Add normal styles added through addStyle()/addInlineStyle() here
3508 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3509 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3510 // We use a <meta> tag with a made-up name for this because that's valid HTML
3511 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3513 // Add site, private and user styles
3514 // 'private' at present only contains user.options, so put that before 'user'
3515 // Any future private modules will likely have a similar user-specific character
3516 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3517 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3518 ResourceLoaderModule::TYPE_STYLES
3522 // Add stuff in $otherTags (previewed user CSS if applicable)
3523 $ret .= $otherTags;
3524 return $ret;
3528 * @return Array
3530 public function buildCssLinksArray() {
3531 $links = array();
3533 // Add any extension CSS
3534 foreach ( $this->mExtStyles as $url ) {
3535 $this->addStyle( $url );
3537 $this->mExtStyles = array();
3539 foreach ( $this->styles as $file => $options ) {
3540 $link = $this->styleLink( $file, $options );
3541 if ( $link ) {
3542 $links[$file] = $link;
3545 return $links;
3549 * Generate \<link\> tags for stylesheets
3551 * @param string $style URL to the file
3552 * @param array $options option, can contain 'condition', 'dir', 'media'
3553 * keys
3554 * @return String: HTML fragment
3556 protected function styleLink( $style, $options ) {
3557 if ( isset( $options['dir'] ) ) {
3558 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3559 return '';
3563 if ( isset( $options['media'] ) ) {
3564 $media = self::transformCssMedia( $options['media'] );
3565 if ( is_null( $media ) ) {
3566 return '';
3568 } else {
3569 $media = 'all';
3572 if ( substr( $style, 0, 1 ) == '/' ||
3573 substr( $style, 0, 5 ) == 'http:' ||
3574 substr( $style, 0, 6 ) == 'https:' ) {
3575 $url = $style;
3576 } else {
3577 global $wgStylePath, $wgStyleVersion;
3578 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3581 $link = Html::linkedStyle( $url, $media );
3583 if ( isset( $options['condition'] ) ) {
3584 $condition = htmlspecialchars( $options['condition'] );
3585 $link = "<!--[if $condition]>$link<![endif]-->";
3587 return $link;
3591 * Transform "media" attribute based on request parameters
3593 * @param string $media current value of the "media" attribute
3594 * @return String: modified value of the "media" attribute, or null to skip
3595 * this stylesheet
3597 public static function transformCssMedia( $media ) {
3598 global $wgRequest, $wgHandheldForIPhone;
3600 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3601 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3603 // Switch in on-screen display for media testing
3604 $switches = array(
3605 'printable' => 'print',
3606 'handheld' => 'handheld',
3608 foreach ( $switches as $switch => $targetMedia ) {
3609 if ( $wgRequest->getBool( $switch ) ) {
3610 if ( $media == $targetMedia ) {
3611 $media = '';
3612 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3613 // This regex will not attempt to understand a comma-separated media_query_list
3615 // Example supported values for $media: 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3616 // Example NOT supported value for $media: '3d-glasses, screen, print and resolution > 90dpi'
3618 // If it's a print request, we never want any kind of screen stylesheets
3619 // If it's a handheld request (currently the only other choice with a switch),
3620 // we don't want simple 'screen' but we might want screen queries that
3621 // have a max-width or something, so we'll pass all others on and let the
3622 // client do the query.
3623 if ( $targetMedia == 'print' || $media == 'screen' ) {
3624 return null;
3630 // Expand longer media queries as iPhone doesn't grok 'handheld'
3631 if ( $wgHandheldForIPhone ) {
3632 $mediaAliases = array(
3633 'screen' => 'screen and (min-device-width: 481px)',
3634 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3637 if ( isset( $mediaAliases[$media] ) ) {
3638 $media = $mediaAliases[$media];
3642 return $media;
3646 * Add a wikitext-formatted message to the output.
3647 * This is equivalent to:
3649 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3651 public function addWikiMsg( /*...*/ ) {
3652 $args = func_get_args();
3653 $name = array_shift( $args );
3654 $this->addWikiMsgArray( $name, $args );
3658 * Add a wikitext-formatted message to the output.
3659 * Like addWikiMsg() except the parameters are taken as an array
3660 * instead of a variable argument list.
3662 * @param $name string
3663 * @param $args array
3665 public function addWikiMsgArray( $name, $args ) {
3666 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3670 * This function takes a number of message/argument specifications, wraps them in
3671 * some overall structure, and then parses the result and adds it to the output.
3673 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3674 * on. The subsequent arguments may either be strings, in which case they are the
3675 * message names, or arrays, in which case the first element is the message name,
3676 * and subsequent elements are the parameters to that message.
3678 * Don't use this for messages that are not in users interface language.
3680 * For example:
3682 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3684 * Is equivalent to:
3686 * $wgOut->addWikiText( "<div class='error'>\n" . wfMessage( 'some-error' )->plain() . "\n</div>" );
3688 * The newline after opening div is needed in some wikitext. See bug 19226.
3690 * @param $wrap string
3692 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3693 $msgSpecs = func_get_args();
3694 array_shift( $msgSpecs );
3695 $msgSpecs = array_values( $msgSpecs );
3696 $s = $wrap;
3697 foreach ( $msgSpecs as $n => $spec ) {
3698 if ( is_array( $spec ) ) {
3699 $args = $spec;
3700 $name = array_shift( $args );
3701 if ( isset( $args['options'] ) ) {
3702 unset( $args['options'] );
3703 wfDeprecated(
3704 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3705 '1.20'
3708 } else {
3709 $args = array();
3710 $name = $spec;
3712 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3714 $this->addWikiText( $s );
3718 * Include jQuery core. Use this to avoid loading it multiple times
3719 * before we get a usable script loader.
3721 * @param array $modules list of jQuery modules which should be loaded
3722 * @return Array: the list of modules which were not loaded.
3723 * @since 1.16
3724 * @deprecated since 1.17
3726 public function includeJQuery( $modules = array() ) {
3727 return array();