Merge "Fix possible error texts in action=options"
[mediawiki.git] / includes / OutputPage.php
blobbf70467cfd79fc9570a79e4c023ee6bfc94765fb
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();
47 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
48 var $mExtStyles = array();
50 /// Should be private - has getter and setter. Contains the HTML title
51 var $mPagetitle = '';
53 /// Contains all of the "<body>" content. Should be private we got set/get accessors and the append() method.
54 var $mBodytext = '';
56 /**
57 * Holds the debug lines that will be output as comments in page source if
58 * $wgDebugComments is enabled. See also $wgShowDebug.
59 * TODO: make a getter method for this
61 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
63 /// Should be private. Stores contents of "<title>" tag
64 var $mHTMLtitle = '';
66 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
67 var $mIsarticle = false;
69 /**
70 * Should be private. Has get/set methods properly documented.
71 * Stores "article flag" toggle.
73 var $mIsArticleRelated = true;
75 /**
76 * Should be private. We have to set isPrintable(). Some pages should
77 * never be printed (ex: redirections).
79 var $mPrintable = false;
81 /**
82 * Should be private. We have set/get/append methods.
84 * Contains the page subtitle. Special pages usually have some links here.
85 * Don't confuse with site subtitle added by skins.
87 private $mSubtitle = array();
89 var $mRedirect = '';
90 var $mStatusCode;
92 /**
93 * mLastModified and mEtag are used for sending cache control.
94 * The whole caching system should probably be moved into its own class.
96 var $mLastModified = '';
98 /**
99 * Should be private. No getter but used in sendCacheControl();
100 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
101 * as a unique identifier for the content. It is later used by the client
102 * to compare its cached version with the server version. Client sends
103 * headers If-Match and If-None-Match containing its locally cached ETAG value.
105 * To get more information, you will have to look at HTTP/1.1 protocol which
106 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
108 var $mETag = false;
110 var $mCategoryLinks = array();
111 var $mCategories = array();
113 /// Should be private. Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
114 var $mLanguageLinks = array();
117 * Should be private. Used for JavaScript (pre resource loader)
118 * We should split js / css.
119 * mScripts content is inserted as is in "<head>" by Skin. This might
120 * contains either a link to a stylesheet or inline css.
122 var $mScripts = '';
125 * Inline CSS styles. Use addInlineStyle() sparsingly
127 var $mInlineStyles = '';
130 var $mLinkColours;
133 * Used by skin template.
134 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 var $mPageLinkTitle = '';
138 /// Array of elements in "<head>". Parser might add its own headers!
139 var $mHeadItems = array();
141 // @todo FIXME: Next variables probably comes from the resource loader
142 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
143 var $mResourceLoader;
144 var $mJsConfigVars = array();
146 /** @todo FIXME: Is this still used ?*/
147 var $mInlineMsg = array();
149 var $mTemplateIds = array();
150 var $mImageTimeKeys = array();
152 var $mRedirectCode = '';
154 var $mFeedLinksAppendQuery = null;
156 # What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
157 # @see ResourceLoaderModule::$origin
158 # ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
159 protected $mAllowedModules = array(
160 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
164 * @EasterEgg I just love the name for this self documenting variable.
165 * @todo document
167 var $mDoNothing = false;
169 // Parser related.
170 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
173 * lazy initialised, use parserOptions()
174 * @var ParserOptions
176 protected $mParserOptions = null;
179 * Handles the atom / rss links.
180 * We probably only support atom in 2011.
181 * Looks like a private variable.
182 * @see $wgAdvertisedFeedTypes
184 var $mFeedLinks = array();
186 // Gwicke work on squid caching? Roughly from 2003.
187 var $mEnableClientCache = true;
190 * Flag if output should only contain the body of the article.
191 * Should be private.
193 var $mArticleBodyOnly = false;
195 var $mNewSectionLink = false;
196 var $mHideNewSectionLink = false;
199 * Comes from the parser. This was probably made to load CSS/JS only
200 * if we had "<gallery>". Used directly in CategoryPage.php
201 * Looks like resource loader can replace this.
203 var $mNoGallery = false;
205 // should be private.
206 var $mPageTitleActionText = '';
207 var $mParseWarnings = array();
209 // Cache stuff. Looks like mEnableClientCache
210 var $mSquidMaxage = 0;
212 // @todo document
213 var $mPreventClickjacking = true;
215 /// should be private. To include the variable {{REVISIONID}}
216 var $mRevisionId = null;
217 private $mRevisionTimestamp = null;
219 var $mFileVersion = null;
222 * An array of stylesheet filenames (relative from skins path), with options
223 * for CSS media, IE conditions, and RTL/LTR direction.
224 * For internal use; add settings in the skin via $this->addStyle()
226 * Style again! This seems like a code duplication since we already have
227 * mStyles. This is what makes OpenSource amazing.
229 var $styles = array();
232 * Whether jQuery is already handled.
234 protected $mJQueryDone = false;
236 private $mIndexPolicy = 'index';
237 private $mFollowPolicy = 'follow';
238 private $mVaryHeader = array(
239 'Accept-Encoding' => array( 'list-contains=gzip' ),
243 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
244 * of the redirect.
246 * @var Title
248 private $mRedirectedFrom = null;
251 * Constructor for OutputPage. This should not be called directly.
252 * Instead a new RequestContext should be created and it will implicitly create
253 * a OutputPage tied to that context.
255 function __construct( IContextSource $context = null ) {
256 if ( $context === null ) {
257 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
258 wfDeprecated( __METHOD__ );
259 } else {
260 $this->setContext( $context );
265 * Redirect to $url rather than displaying the normal page
267 * @param $url String: URL
268 * @param $responsecode String: HTTP status code
270 public function redirect( $url, $responsecode = '302' ) {
271 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
272 $this->mRedirect = str_replace( "\n", '', $url );
273 $this->mRedirectCode = $responsecode;
277 * Get the URL to redirect to, or an empty string if not redirect URL set
279 * @return String
281 public function getRedirect() {
282 return $this->mRedirect;
286 * Set the HTTP status code to send with the output.
288 * @param $statusCode Integer
290 public function setStatusCode( $statusCode ) {
291 $this->mStatusCode = $statusCode;
295 * Add a new "<meta>" tag
296 * To add an http-equiv meta tag, precede the name with "http:"
298 * @param $name String tag name
299 * @param $val String tag value
301 function addMeta( $name, $val ) {
302 array_push( $this->mMetatags, array( $name, $val ) );
306 * Add a keyword or a list of keywords in the page header
308 * @param $text String or array of strings
310 function addKeyword( $text ) {
311 if( is_array( $text ) ) {
312 $this->mKeywords = array_merge( $this->mKeywords, $text );
313 } else {
314 array_push( $this->mKeywords, $text );
319 * Add a new \<link\> tag to the page header
321 * @param $linkarr Array: associative array of attributes.
323 function addLink( $linkarr ) {
324 array_push( $this->mLinktags, $linkarr );
328 * Add a new \<link\> with "rel" attribute set to "meta"
330 * @param $linkarr Array: associative array mapping attribute names to their
331 * values, both keys and values will be escaped, and the
332 * "rel" attribute will be automatically added
334 function addMetadataLink( $linkarr ) {
335 $linkarr['rel'] = $this->getMetadataAttribute();
336 $this->addLink( $linkarr );
340 * Get the value of the "rel" attribute for metadata links
342 * @return String
344 public function getMetadataAttribute() {
345 # note: buggy CC software only reads first "meta" link
346 static $haveMeta = false;
347 if ( $haveMeta ) {
348 return 'alternate meta';
349 } else {
350 $haveMeta = true;
351 return 'meta';
356 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
358 * @param $script String: raw HTML
360 function addScript( $script ) {
361 $this->mScripts .= $script . "\n";
365 * Register and add a stylesheet from an extension directory.
367 * @param $url String path to sheet. Provide either a full url (beginning
368 * with 'http', etc) or a relative path from the document root
369 * (beginning with '/'). Otherwise it behaves identically to
370 * addStyle() and draws from the /skins folder.
372 public function addExtensionStyle( $url ) {
373 array_push( $this->mExtStyles, $url );
377 * Get all styles added by extensions
379 * @return Array
381 function getExtStyle() {
382 return $this->mExtStyles;
386 * Add a JavaScript file out of skins/common, or a given relative path.
388 * @param $file String: filename in skins/common or complete on-server path
389 * (/foo/bar.js)
390 * @param $version String: style version of the file. Defaults to $wgStyleVersion
392 public function addScriptFile( $file, $version = null ) {
393 global $wgStylePath, $wgStyleVersion;
394 // See if $file parameter is an absolute URL or begins with a slash
395 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
396 $path = $file;
397 } else {
398 $path = "{$wgStylePath}/common/{$file}";
400 if ( is_null( $version ) )
401 $version = $wgStyleVersion;
402 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
406 * Add a self-contained script tag with the given contents
408 * @param $script String: JavaScript text, no "<script>" tags
410 public function addInlineScript( $script ) {
411 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
415 * Get all registered JS and CSS tags for the header.
417 * @return String
419 function getScript() {
420 return $this->mScripts . $this->getHeadItems();
424 * Filter an array of modules to remove insufficiently trustworthy members, and modules
425 * which are no longer registered (eg a page is cached before an extension is disabled)
426 * @param $modules Array
427 * @param $position String if not null, only return modules with this position
428 * @param $type string
429 * @return Array
431 protected function filterModules( $modules, $position = null, $type = ResourceLoaderModule::TYPE_COMBINED ){
432 $resourceLoader = $this->getResourceLoader();
433 $filteredModules = array();
434 foreach( $modules as $val ){
435 $module = $resourceLoader->getModule( $val );
436 if( $module instanceof ResourceLoaderModule
437 && $module->getOrigin() <= $this->getAllowedModules( $type )
438 && ( is_null( $position ) || $module->getPosition() == $position ) )
440 $filteredModules[] = $val;
443 return $filteredModules;
447 * Get the list of modules to include on this page
449 * @param $filter Bool whether to filter out insufficiently trustworthy modules
450 * @param $position String if not null, only return modules with this position
451 * @param $param string
452 * @return Array of module names
454 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
455 $modules = array_values( array_unique( $this->$param ) );
456 return $filter
457 ? $this->filterModules( $modules, $position )
458 : $modules;
462 * Add one or more modules recognized by the resource loader. Modules added
463 * through this function will be loaded by the resource loader when the
464 * page loads.
466 * @param $modules Mixed: module name (string) or array of module names
468 public function addModules( $modules ) {
469 $this->mModules = array_merge( $this->mModules, (array)$modules );
473 * Get the list of module JS to include on this page
475 * @param $filter
476 * @param $position
478 * @return array of module names
480 public function getModuleScripts( $filter = false, $position = null ) {
481 return $this->getModules( $filter, $position, 'mModuleScripts' );
485 * Add only JS of one or more modules recognized by the resource loader. Module
486 * scripts added through this function will be loaded by the resource loader when
487 * the page loads.
489 * @param $modules Mixed: module name (string) or array of module names
491 public function addModuleScripts( $modules ) {
492 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
496 * Get the list of module CSS to include on this page
498 * @param $filter
499 * @param $position
501 * @return Array of module names
503 public function getModuleStyles( $filter = false, $position = null ) {
504 return $this->getModules( $filter, $position, 'mModuleStyles' );
508 * Add only CSS of one or more modules recognized by the resource loader. Module
509 * styles 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 addModuleStyles( $modules ) {
515 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
519 * Get the list of module messages to include on this page
521 * @param $filter
522 * @param $position
524 * @return Array of module names
526 public function getModuleMessages( $filter = false, $position = null ) {
527 return $this->getModules( $filter, $position, 'mModuleMessages' );
531 * Add only messages of one or more modules recognized by the resource loader.
532 * Module messages added through this function will be loaded by the resource
533 * loader when the page loads.
535 * @param $modules Mixed: module name (string) or array of module names
537 public function addModuleMessages( $modules ) {
538 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
542 * Get an array of head items
544 * @return Array
546 function getHeadItemsArray() {
547 return $this->mHeadItems;
551 * Get all header items in a string
553 * @return String
555 function getHeadItems() {
556 $s = '';
557 foreach ( $this->mHeadItems as $item ) {
558 $s .= $item;
560 return $s;
564 * Add or replace an header item to the output
566 * @param $name String: item name
567 * @param $value String: raw HTML
569 public function addHeadItem( $name, $value ) {
570 $this->mHeadItems[$name] = $value;
574 * Check if the header item $name is already set
576 * @param $name String: item name
577 * @return Boolean
579 public function hasHeadItem( $name ) {
580 return isset( $this->mHeadItems[$name] );
584 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
586 * @param $tag String: value of "ETag" header
588 function setETag( $tag ) {
589 $this->mETag = $tag;
593 * Set whether the output should only contain the body of the article,
594 * without any skin, sidebar, etc.
595 * Used e.g. when calling with "action=render".
597 * @param $only Boolean: whether to output only the body of the article
599 public function setArticleBodyOnly( $only ) {
600 $this->mArticleBodyOnly = $only;
604 * Return whether the output will contain only the body of the article
606 * @return Boolean
608 public function getArticleBodyOnly() {
609 return $this->mArticleBodyOnly;
613 * checkLastModified tells the client to use the client-cached page if
614 * possible. If sucessful, the OutputPage is disabled so that
615 * any future call to OutputPage->output() have no effect.
617 * Side effect: sets mLastModified for Last-Modified header
619 * @param $timestamp string
621 * @return Boolean: true iff cache-ok headers was sent.
623 public function checkLastModified( $timestamp ) {
624 global $wgCachePages, $wgCacheEpoch;
626 if ( !$timestamp || $timestamp == '19700101000000' ) {
627 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
628 return false;
630 if( !$wgCachePages ) {
631 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
632 return false;
634 if( $this->getUser()->getOption( 'nocache' ) ) {
635 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
636 return false;
639 $timestamp = wfTimestamp( TS_MW, $timestamp );
640 $modifiedTimes = array(
641 'page' => $timestamp,
642 'user' => $this->getUser()->getTouched(),
643 'epoch' => $wgCacheEpoch
645 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
647 $maxModified = max( $modifiedTimes );
648 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
650 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
651 if ( $clientHeader === false ) {
652 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
653 return false;
656 # IE sends sizes after the date like this:
657 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
658 # this breaks strtotime().
659 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
661 wfSuppressWarnings(); // E_STRICT system time bitching
662 $clientHeaderTime = strtotime( $clientHeader );
663 wfRestoreWarnings();
664 if ( !$clientHeaderTime ) {
665 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
666 return false;
668 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
670 # Make debug info
671 $info = '';
672 foreach ( $modifiedTimes as $name => $value ) {
673 if ( $info !== '' ) {
674 $info .= ', ';
676 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
679 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
680 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
681 wfDebug( __METHOD__ . ": effective Last-Modified: " .
682 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
683 if( $clientHeaderTime < $maxModified ) {
684 wfDebug( __METHOD__ . ": STALE, $info\n", false );
685 return false;
688 # Not modified
689 # Give a 304 response code and disable body output
690 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
691 ini_set( 'zlib.output_compression', 0 );
692 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
693 $this->sendCacheControl();
694 $this->disable();
696 // Don't output a compressed blob when using ob_gzhandler;
697 // it's technically against HTTP spec and seems to confuse
698 // Firefox when the response gets split over two packets.
699 wfClearOutputBuffers();
701 return true;
705 * Override the last modified timestamp
707 * @param $timestamp String: new timestamp, in a format readable by
708 * wfTimestamp()
710 public function setLastModified( $timestamp ) {
711 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
715 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
717 * @param $policy String: the literal string to output as the contents of
718 * the meta tag. Will be parsed according to the spec and output in
719 * standardized form.
720 * @return null
722 public function setRobotPolicy( $policy ) {
723 $policy = Article::formatRobotPolicy( $policy );
725 if( isset( $policy['index'] ) ) {
726 $this->setIndexPolicy( $policy['index'] );
728 if( isset( $policy['follow'] ) ) {
729 $this->setFollowPolicy( $policy['follow'] );
734 * Set the index policy for the page, but leave the follow policy un-
735 * touched.
737 * @param $policy string Either 'index' or 'noindex'.
738 * @return null
740 public function setIndexPolicy( $policy ) {
741 $policy = trim( $policy );
742 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
743 $this->mIndexPolicy = $policy;
748 * Set the follow policy for the page, but leave the index policy un-
749 * touched.
751 * @param $policy String: either 'follow' or 'nofollow'.
752 * @return null
754 public function setFollowPolicy( $policy ) {
755 $policy = trim( $policy );
756 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
757 $this->mFollowPolicy = $policy;
762 * Set the new value of the "action text", this will be added to the
763 * "HTML title", separated from it with " - ".
765 * @param $text String: new value of the "action text"
767 public function setPageTitleActionText( $text ) {
768 $this->mPageTitleActionText = $text;
772 * Get the value of the "action text"
774 * @return String
776 public function getPageTitleActionText() {
777 if ( isset( $this->mPageTitleActionText ) ) {
778 return $this->mPageTitleActionText;
783 * "HTML title" means the contents of "<title>".
784 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
786 * @param $name string
788 public function setHTMLTitle( $name ) {
789 if ( $name instanceof Message ) {
790 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
791 } else {
792 $this->mHTMLtitle = $name;
797 * Return the "HTML title", i.e. the content of the "<title>" tag.
799 * @return String
801 public function getHTMLTitle() {
802 return $this->mHTMLtitle;
806 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
808 * @param $t Title
810 public function setRedirectedFrom( $t ) {
811 $this->mRedirectedFrom = $t;
815 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
816 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
817 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
818 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
820 * @param $name string|Message
822 public function setPageTitle( $name ) {
823 if ( $name instanceof Message ) {
824 $name = $name->setContext( $this->getContext() )->text();
827 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
828 # but leave "<i>foobar</i>" alone
829 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
830 $this->mPagetitle = $nameWithTags;
832 # change "<i>foo&amp;bar</i>" to "foo&bar"
833 $this->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) ) );
837 * Return the "page title", i.e. the content of the \<h1\> tag.
839 * @return String
841 public function getPageTitle() {
842 return $this->mPagetitle;
846 * Set the Title object to use
848 * @param $t Title object
850 public function setTitle( Title $t ) {
851 $this->getContext()->setTitle( $t );
856 * Replace the subtile with $str
858 * @param $str String|Message: new value of the subtitle
860 public function setSubtitle( $str ) {
861 $this->clearSubtitle();
862 $this->addSubtitle( $str );
866 * Add $str to the subtitle
868 * @deprecated in 1.19; use addSubtitle() instead
869 * @param $str String|Message to add to the subtitle
871 public function appendSubtitle( $str ) {
872 $this->addSubtitle( $str );
876 * Add $str to the subtitle
878 * @param $str String|Message to add to the subtitle
880 public function addSubtitle( $str ) {
881 if ( $str instanceof Message ) {
882 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
883 } else {
884 $this->mSubtitle[] = $str;
889 * Add a subtitle containing a backlink to a page
891 * @param $title Title to link to
893 public function addBacklinkSubtitle( Title $title ) {
894 $query = array();
895 if ( $title->isRedirect() ) {
896 $query['redirect'] = 'no';
898 $this->addSubtitle( $this->msg( 'backlinksubtitle' )->rawParams( Linker::link( $title, null, array(), $query ) ) );
902 * Clear the subtitles
904 public function clearSubtitle() {
905 $this->mSubtitle = array();
909 * Get the subtitle
911 * @return String
913 public function getSubtitle() {
914 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
918 * Set the page as printable, i.e. it'll be displayed with with all
919 * print styles included
921 public function setPrintable() {
922 $this->mPrintable = true;
926 * Return whether the page is "printable"
928 * @return Boolean
930 public function isPrintable() {
931 return $this->mPrintable;
935 * Disable output completely, i.e. calling output() will have no effect
937 public function disable() {
938 $this->mDoNothing = true;
942 * Return whether the output will be completely disabled
944 * @return Boolean
946 public function isDisabled() {
947 return $this->mDoNothing;
951 * Show an "add new section" link?
953 * @return Boolean
955 public function showNewSectionLink() {
956 return $this->mNewSectionLink;
960 * Forcibly hide the new section link?
962 * @return Boolean
964 public function forceHideNewSectionLink() {
965 return $this->mHideNewSectionLink;
969 * Add or remove feed links in the page header
970 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
971 * for the new version
972 * @see addFeedLink()
974 * @param $show Boolean: true: add default feeds, false: remove all feeds
976 public function setSyndicated( $show = true ) {
977 if ( $show ) {
978 $this->setFeedAppendQuery( false );
979 } else {
980 $this->mFeedLinks = array();
985 * Add default feeds to the page header
986 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
987 * for the new version
988 * @see addFeedLink()
990 * @param $val String: query to append to feed links or false to output
991 * default links
993 public function setFeedAppendQuery( $val ) {
994 global $wgAdvertisedFeedTypes;
996 $this->mFeedLinks = array();
998 foreach ( $wgAdvertisedFeedTypes as $type ) {
999 $query = "feed=$type";
1000 if ( is_string( $val ) ) {
1001 $query .= '&' . $val;
1003 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1008 * Add a feed link to the page header
1010 * @param $format String: feed type, should be a key of $wgFeedClasses
1011 * @param $href String: URL
1013 public function addFeedLink( $format, $href ) {
1014 global $wgAdvertisedFeedTypes;
1016 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
1017 $this->mFeedLinks[$format] = $href;
1022 * Should we output feed links for this page?
1023 * @return Boolean
1025 public function isSyndicated() {
1026 return count( $this->mFeedLinks ) > 0;
1030 * Return URLs for each supported syndication format for this page.
1031 * @return array associating format keys with URLs
1033 public function getSyndicationLinks() {
1034 return $this->mFeedLinks;
1038 * Will currently always return null
1040 * @return null
1042 public function getFeedAppendQuery() {
1043 return $this->mFeedLinksAppendQuery;
1047 * Set whether the displayed content is related to the source of the
1048 * corresponding article on the wiki
1049 * Setting true will cause the change "article related" toggle to true
1051 * @param $v Boolean
1053 public function setArticleFlag( $v ) {
1054 $this->mIsarticle = $v;
1055 if ( $v ) {
1056 $this->mIsArticleRelated = $v;
1061 * Return whether the content displayed page is related to the source of
1062 * the corresponding article on the wiki
1064 * @return Boolean
1066 public function isArticle() {
1067 return $this->mIsarticle;
1071 * Set whether this page is related an article on the wiki
1072 * Setting false will cause the change of "article flag" toggle to false
1074 * @param $v Boolean
1076 public function setArticleRelated( $v ) {
1077 $this->mIsArticleRelated = $v;
1078 if ( !$v ) {
1079 $this->mIsarticle = false;
1084 * Return whether this page is related an article on the wiki
1086 * @return Boolean
1088 public function isArticleRelated() {
1089 return $this->mIsArticleRelated;
1093 * Add new language links
1095 * @param $newLinkArray array Associative array mapping language code to the page
1096 * name
1098 public function addLanguageLinks( $newLinkArray ) {
1099 $this->mLanguageLinks += $newLinkArray;
1103 * Reset the language links and add new language links
1105 * @param $newLinkArray array Associative array mapping language code to the page
1106 * name
1108 public function setLanguageLinks( $newLinkArray ) {
1109 $this->mLanguageLinks = $newLinkArray;
1113 * Get the list of language links
1115 * @return Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1117 public function getLanguageLinks() {
1118 return $this->mLanguageLinks;
1122 * Add an array of categories, with names in the keys
1124 * @param $categories Array mapping category name => sort key
1126 public function addCategoryLinks( $categories ) {
1127 global $wgContLang;
1129 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1130 return;
1133 # Add the links to a LinkBatch
1134 $arr = array( NS_CATEGORY => $categories );
1135 $lb = new LinkBatch;
1136 $lb->setArray( $arr );
1138 # Fetch existence plus the hiddencat property
1139 $dbr = wfGetDB( DB_SLAVE );
1140 $res = $dbr->select( array( 'page', 'page_props' ),
1141 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
1142 $lb->constructSet( 'page', $dbr ),
1143 __METHOD__,
1144 array(),
1145 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
1148 # Add the results to the link cache
1149 $lb->addResultToCache( LinkCache::singleton(), $res );
1151 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1152 $categories = array_combine(
1153 array_keys( $categories ),
1154 array_fill( 0, count( $categories ), 'normal' )
1157 # Mark hidden categories
1158 foreach ( $res as $row ) {
1159 if ( isset( $row->pp_value ) ) {
1160 $categories[$row->page_title] = 'hidden';
1164 # Add the remaining categories to the skin
1165 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1166 foreach ( $categories as $category => $type ) {
1167 $origcategory = $category;
1168 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1169 $wgContLang->findVariantLink( $category, $title, true );
1170 if ( $category != $origcategory ) {
1171 if ( array_key_exists( $category, $categories ) ) {
1172 continue;
1175 $text = $wgContLang->convertHtml( $title->getText() );
1176 $this->mCategories[] = $title->getText();
1177 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1183 * Reset the category links (but not the category list) and add $categories
1185 * @param $categories Array mapping category name => sort key
1187 public function setCategoryLinks( $categories ) {
1188 $this->mCategoryLinks = array();
1189 $this->addCategoryLinks( $categories );
1193 * Get the list of category links, in a 2-D array with the following format:
1194 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1195 * hidden categories) and $link a HTML fragment with a link to the category
1196 * page
1198 * @return Array
1200 public function getCategoryLinks() {
1201 return $this->mCategoryLinks;
1205 * Get the list of category names this page belongs to
1207 * @return Array of strings
1209 public function getCategories() {
1210 return $this->mCategories;
1214 * Do not allow scripts which can be modified by wiki users to load on this page;
1215 * only allow scripts bundled with, or generated by, the software.
1217 public function disallowUserJs() {
1218 $this->reduceAllowedModules(
1219 ResourceLoaderModule::TYPE_SCRIPTS,
1220 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1225 * Return whether user JavaScript is allowed for this page
1226 * @deprecated since 1.18 Load modules with ResourceLoader, and origin and
1227 * trustworthiness is identified and enforced automagically.
1228 * Will be removed in 1.20.
1229 * @return Boolean
1231 public function isUserJsAllowed() {
1232 wfDeprecated( __METHOD__, '1.18' );
1233 return $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS ) >= ResourceLoaderModule::ORIGIN_USER_INDIVIDUAL;
1237 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1238 * @see ResourceLoaderModule::$origin
1239 * @param $type String ResourceLoaderModule TYPE_ constant
1240 * @return Int ResourceLoaderModule ORIGIN_ class constant
1242 public function getAllowedModules( $type ){
1243 if( $type == ResourceLoaderModule::TYPE_COMBINED ){
1244 return min( array_values( $this->mAllowedModules ) );
1245 } else {
1246 return isset( $this->mAllowedModules[$type] )
1247 ? $this->mAllowedModules[$type]
1248 : ResourceLoaderModule::ORIGIN_ALL;
1253 * Set the highest level of CSS/JS untrustworthiness allowed
1254 * @param $type String ResourceLoaderModule TYPE_ constant
1255 * @param $level Int ResourceLoaderModule class constant
1257 public function setAllowedModules( $type, $level ){
1258 $this->mAllowedModules[$type] = $level;
1262 * As for setAllowedModules(), but don't inadvertantly make the page more accessible
1263 * @param $type String
1264 * @param $level Int ResourceLoaderModule class constant
1266 public function reduceAllowedModules( $type, $level ){
1267 $this->mAllowedModules[$type] = min( $this->getAllowedModules($type), $level );
1271 * Prepend $text to the body HTML
1273 * @param $text String: HTML
1275 public function prependHTML( $text ) {
1276 $this->mBodytext = $text . $this->mBodytext;
1280 * Append $text to the body HTML
1282 * @param $text String: HTML
1284 public function addHTML( $text ) {
1285 $this->mBodytext .= $text;
1289 * Shortcut for adding an Html::element via addHTML.
1291 * @since 1.19
1293 * @param $element string
1294 * @param $attribs array
1295 * @param $contents string
1297 public function addElement( $element, $attribs = array(), $contents = '' ) {
1298 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1302 * Clear the body HTML
1304 public function clearHTML() {
1305 $this->mBodytext = '';
1309 * Get the body HTML
1311 * @return String: HTML
1313 public function getHTML() {
1314 return $this->mBodytext;
1318 * Add $text to the debug output
1320 * @param $text String: debug text
1322 public function debug( $text ) {
1323 $this->mDebugtext .= $text;
1327 * Get/set the ParserOptions object to use for wikitext parsing
1329 * @param $options ParserOptions|null either the ParserOption to use or null to only get the
1330 * current ParserOption object
1331 * @return ParserOptions object
1333 public function parserOptions( $options = null ) {
1334 if ( !$this->mParserOptions ) {
1335 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1336 $this->mParserOptions->setEditSection( false );
1338 return wfSetVar( $this->mParserOptions, $options );
1342 * Set the revision ID which will be seen by the wiki text parser
1343 * for things such as embedded {{REVISIONID}} variable use.
1345 * @param $revid Mixed: an positive integer, or null
1346 * @return Mixed: previous value
1348 public function setRevisionId( $revid ) {
1349 $val = is_null( $revid ) ? null : intval( $revid );
1350 return wfSetVar( $this->mRevisionId, $val );
1354 * Get the displayed revision ID
1356 * @return Integer
1358 public function getRevisionId() {
1359 return $this->mRevisionId;
1363 * Set the timestamp of the revision which will be displayed. This is used
1364 * to avoid a extra DB call in Skin::lastModified().
1366 * @param $timestamp Mixed: string, or null
1367 * @return Mixed: previous value
1369 public function setRevisionTimestamp( $timestamp) {
1370 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1374 * Get the timestamp of displayed revision.
1375 * This will be null if not filled by setRevisionTimestamp().
1377 * @return String or null
1379 public function getRevisionTimestamp() {
1380 return $this->mRevisionTimestamp;
1384 * Set the displayed file version
1386 * @param $file File|bool
1387 * @return Mixed: previous value
1389 public function setFileVersion( $file ) {
1390 $val = null;
1391 if ( $file instanceof File && $file->exists() ) {
1392 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1394 return wfSetVar( $this->mFileVersion, $val, true );
1398 * Get the displayed file version
1400 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1402 public function getFileVersion() {
1403 return $this->mFileVersion;
1407 * Get the templates used on this page
1409 * @return Array (namespace => dbKey => revId)
1410 * @since 1.18
1412 public function getTemplateIds() {
1413 return $this->mTemplateIds;
1417 * Get the files used on this page
1419 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1420 * @since 1.18
1422 public function getFileSearchOptions() {
1423 return $this->mImageTimeKeys;
1427 * Convert wikitext to HTML and add it to the buffer
1428 * Default assumes that the current page title will be used.
1430 * @param $text String
1431 * @param $linestart Boolean: is this the start of a line?
1432 * @param $interface Boolean: is this text in the user interface language?
1434 public function addWikiText( $text, $linestart = true, $interface = true ) {
1435 $title = $this->getTitle(); // Work arround E_STRICT
1436 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1440 * Add wikitext with a custom Title object
1442 * @param $text String: wikitext
1443 * @param $title Title object
1444 * @param $linestart Boolean: is this the start of a line?
1446 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1447 $this->addWikiTextTitle( $text, $title, $linestart );
1451 * Add wikitext with a custom Title object and tidy enabled.
1453 * @param $text String: wikitext
1454 * @param $title Title object
1455 * @param $linestart Boolean: is this the start of a line?
1457 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1458 $this->addWikiTextTitle( $text, $title, $linestart, true );
1462 * Add wikitext with tidy enabled
1464 * @param $text String: wikitext
1465 * @param $linestart Boolean: is this the start of a line?
1467 public function addWikiTextTidy( $text, $linestart = true ) {
1468 $title = $this->getTitle();
1469 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1473 * Add wikitext with a custom Title object
1475 * @param $text String: wikitext
1476 * @param $title Title object
1477 * @param $linestart Boolean: is this the start of a line?
1478 * @param $tidy Boolean: whether to use tidy
1479 * @param $interface Boolean: whether it is an interface message
1480 * (for example disables conversion)
1482 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1483 global $wgParser;
1485 wfProfileIn( __METHOD__ );
1487 $popts = $this->parserOptions();
1488 $oldTidy = $popts->setTidy( $tidy );
1489 $popts->setInterfaceMessage( (bool) $interface );
1491 $parserOutput = $wgParser->parse(
1492 $text, $title, $popts,
1493 $linestart, true, $this->mRevisionId
1496 $popts->setTidy( $oldTidy );
1498 $this->addParserOutput( $parserOutput );
1500 wfProfileOut( __METHOD__ );
1504 * Add a ParserOutput object, but without Html
1506 * @param $parserOutput ParserOutput object
1508 public function addParserOutputNoText( &$parserOutput ) {
1509 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1510 $this->addCategoryLinks( $parserOutput->getCategories() );
1511 $this->mNewSectionLink = $parserOutput->getNewSection();
1512 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1514 $this->mParseWarnings = $parserOutput->getWarnings();
1515 if ( !$parserOutput->isCacheable() ) {
1516 $this->enableClientCache( false );
1518 $this->mNoGallery = $parserOutput->getNoGallery();
1519 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1520 $this->addModules( $parserOutput->getModules() );
1521 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1522 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1523 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1525 // Template versioning...
1526 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1527 if ( isset( $this->mTemplateIds[$ns] ) ) {
1528 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1529 } else {
1530 $this->mTemplateIds[$ns] = $dbks;
1533 // File versioning...
1534 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1535 $this->mImageTimeKeys[$dbk] = $data;
1538 // Hooks registered in the object
1539 global $wgParserOutputHooks;
1540 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1541 list( $hookName, $data ) = $hookInfo;
1542 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1543 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1547 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1551 * Add a ParserOutput object
1553 * @param $parserOutput ParserOutput
1555 function addParserOutput( &$parserOutput ) {
1556 $this->addParserOutputNoText( $parserOutput );
1557 $text = $parserOutput->getText();
1558 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1559 $this->addHTML( $text );
1564 * Add the output of a QuickTemplate to the output buffer
1566 * @param $template QuickTemplate
1568 public function addTemplate( &$template ) {
1569 ob_start();
1570 $template->execute();
1571 $this->addHTML( ob_get_contents() );
1572 ob_end_clean();
1576 * Parse wikitext and return the HTML.
1578 * @param $text String
1579 * @param $linestart Boolean: is this the start of a line?
1580 * @param $interface Boolean: use interface language ($wgLang instead of
1581 * $wgContLang) while parsing language sensitive magic
1582 * words like GRAMMAR and PLURAL. This also disables
1583 * LanguageConverter.
1584 * @param $language Language object: target language object, will override
1585 * $interface
1586 * @return String: HTML
1588 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1589 global $wgParser;
1591 if( is_null( $this->getTitle() ) ) {
1592 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1595 $popts = $this->parserOptions();
1596 if ( $interface ) {
1597 $popts->setInterfaceMessage( true );
1599 if ( $language !== null ) {
1600 $oldLang = $popts->setTargetLanguage( $language );
1603 $parserOutput = $wgParser->parse(
1604 $text, $this->getTitle(), $popts,
1605 $linestart, true, $this->mRevisionId
1608 if ( $interface ) {
1609 $popts->setInterfaceMessage( false );
1611 if ( $language !== null ) {
1612 $popts->setTargetLanguage( $oldLang );
1615 return $parserOutput->getText();
1619 * Parse wikitext, strip paragraphs, and return the HTML.
1621 * @param $text String
1622 * @param $linestart Boolean: is this the start of a line?
1623 * @param $interface Boolean: use interface language ($wgLang instead of
1624 * $wgContLang) while parsing language sensitive magic
1625 * words like GRAMMAR and PLURAL
1626 * @return String: HTML
1628 public function parseInline( $text, $linestart = true, $interface = false ) {
1629 $parsed = $this->parse( $text, $linestart, $interface );
1631 $m = array();
1632 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1633 $parsed = $m[1];
1636 return $parsed;
1640 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1642 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1644 public function setSquidMaxage( $maxage ) {
1645 $this->mSquidMaxage = $maxage;
1649 * Use enableClientCache(false) to force it to send nocache headers
1651 * @param $state bool
1653 * @return bool
1655 public function enableClientCache( $state ) {
1656 return wfSetVar( $this->mEnableClientCache, $state );
1660 * Get the list of cookies that will influence on the cache
1662 * @return Array
1664 function getCacheVaryCookies() {
1665 global $wgCookiePrefix, $wgCacheVaryCookies;
1666 static $cookies;
1667 if ( $cookies === null ) {
1668 $cookies = array_merge(
1669 array(
1670 "{$wgCookiePrefix}Token",
1671 "{$wgCookiePrefix}LoggedOut",
1672 session_name()
1674 $wgCacheVaryCookies
1676 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1678 return $cookies;
1682 * Check if the request has a cache-varying cookie header
1683 * If it does, it's very important that we don't allow public caching
1685 * @return Boolean
1687 function haveCacheVaryCookies() {
1688 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1689 if ( $cookieHeader === false ) {
1690 return false;
1692 $cvCookies = $this->getCacheVaryCookies();
1693 foreach ( $cvCookies as $cookieName ) {
1694 # Check for a simple string match, like the way squid does it
1695 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1696 wfDebug( __METHOD__ . ": found $cookieName\n" );
1697 return true;
1700 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1701 return false;
1705 * Add an HTTP header that will influence on the cache
1707 * @param $header String: header name
1708 * @param $option Array|null
1709 * @todo FIXME: Document the $option parameter; it appears to be for
1710 * X-Vary-Options but what format is acceptable?
1712 public function addVaryHeader( $header, $option = null ) {
1713 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1714 $this->mVaryHeader[$header] = (array)$option;
1715 } elseif( is_array( $option ) ) {
1716 if( is_array( $this->mVaryHeader[$header] ) ) {
1717 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1718 } else {
1719 $this->mVaryHeader[$header] = $option;
1722 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1726 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1727 * such as Accept-Encoding or Cookie
1729 * @return String
1731 public function getVaryHeader() {
1732 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
1736 * Get a complete X-Vary-Options header
1738 * @return String
1740 public function getXVO() {
1741 $cvCookies = $this->getCacheVaryCookies();
1743 $cookiesOption = array();
1744 foreach ( $cvCookies as $cookieName ) {
1745 $cookiesOption[] = 'string-contains=' . $cookieName;
1747 $this->addVaryHeader( 'Cookie', $cookiesOption );
1749 $headers = array();
1750 foreach( $this->mVaryHeader as $header => $option ) {
1751 $newheader = $header;
1752 if ( is_array( $option ) && count( $option ) > 0 ) {
1753 $newheader .= ';' . implode( ';', $option );
1755 $headers[] = $newheader;
1757 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1759 return $xvo;
1763 * bug 21672: Add Accept-Language to Vary and XVO headers
1764 * if there's no 'variant' parameter existed in GET.
1766 * For example:
1767 * /w/index.php?title=Main_page should always be served; but
1768 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1770 function addAcceptLanguage() {
1771 $lang = $this->getTitle()->getPageLanguage();
1772 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1773 $variants = $lang->getVariants();
1774 $aloption = array();
1775 foreach ( $variants as $variant ) {
1776 if( $variant === $lang->getCode() ) {
1777 continue;
1778 } else {
1779 $aloption[] = 'string-contains=' . $variant;
1781 // IE and some other browsers use another form of language code
1782 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1783 // We should handle these too.
1784 $ievariant = explode( '-', $variant );
1785 if ( count( $ievariant ) == 2 ) {
1786 $ievariant[1] = strtoupper( $ievariant[1] );
1787 $ievariant = implode( '-', $ievariant );
1788 $aloption[] = 'string-contains=' . $ievariant;
1792 $this->addVaryHeader( 'Accept-Language', $aloption );
1797 * Set a flag which will cause an X-Frame-Options header appropriate for
1798 * edit pages to be sent. The header value is controlled by
1799 * $wgEditPageFrameOptions.
1801 * This is the default for special pages. If you display a CSRF-protected
1802 * form on an ordinary view page, then you need to call this function.
1804 * @param $enable bool
1806 public function preventClickjacking( $enable = true ) {
1807 $this->mPreventClickjacking = $enable;
1811 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1812 * This can be called from pages which do not contain any CSRF-protected
1813 * HTML form.
1815 public function allowClickjacking() {
1816 $this->mPreventClickjacking = false;
1820 * Get the X-Frame-Options header value (without the name part), or false
1821 * if there isn't one. This is used by Skin to determine whether to enable
1822 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1824 * @return string
1826 public function getFrameOptions() {
1827 global $wgBreakFrames, $wgEditPageFrameOptions;
1828 if ( $wgBreakFrames ) {
1829 return 'DENY';
1830 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1831 return $wgEditPageFrameOptions;
1833 return false;
1837 * Send cache control HTTP headers
1839 public function sendCacheControl() {
1840 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1842 $response = $this->getRequest()->response();
1843 if ( $wgUseETag && $this->mETag ) {
1844 $response->header( "ETag: $this->mETag" );
1847 $this->addVaryHeader( 'Cookie' );
1848 $this->addAcceptLanguage();
1850 # don't serve compressed data to clients who can't handle it
1851 # maintain different caches for logged-in users and non-logged in ones
1852 $response->header( $this->getVaryHeader() );
1854 if ( $wgUseXVO ) {
1855 # Add an X-Vary-Options header for Squid with Wikimedia patches
1856 $response->header( $this->getXVO() );
1859 if( $this->mEnableClientCache ) {
1861 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1862 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1865 if ( $wgUseESI ) {
1866 # We'll purge the proxy cache explicitly, but require end user agents
1867 # to revalidate against the proxy on each visit.
1868 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1869 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1870 # start with a shorter timeout for initial testing
1871 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1872 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1873 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1874 } else {
1875 # We'll purge the proxy cache for anons explicitly, but require end user agents
1876 # to revalidate against the proxy on each visit.
1877 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1878 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1879 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1880 # start with a shorter timeout for initial testing
1881 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1882 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1884 } else {
1885 # We do want clients to cache if they can, but they *must* check for updates
1886 # on revisiting the page.
1887 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1888 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1889 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1891 if($this->mLastModified) {
1892 $response->header( "Last-Modified: {$this->mLastModified}" );
1894 } else {
1895 wfDebug( __METHOD__ . ": no caching **\n", false );
1897 # In general, the absence of a last modified header should be enough to prevent
1898 # the client from using its cache. We send a few other things just to make sure.
1899 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1900 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1901 $response->header( 'Pragma: no-cache' );
1906 * Get the message associed with the HTTP response code $code
1908 * @param $code Integer: status code
1909 * @return String or null: message or null if $code is not in the list of
1910 * messages
1912 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1914 public static function getStatusMessage( $code ) {
1915 wfDeprecated( __METHOD__ );
1916 return HttpStatus::getMessage( $code );
1920 * Finally, all the text has been munged and accumulated into
1921 * the object, let's actually output it:
1923 public function output() {
1924 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1926 if( $this->mDoNothing ) {
1927 return;
1930 wfProfileIn( __METHOD__ );
1932 $response = $this->getRequest()->response();
1934 if ( $this->mRedirect != '' ) {
1935 # Standards require redirect URLs to be absolute
1936 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1938 $redirect = $this->mRedirect;
1939 $code = $this->mRedirectCode;
1941 if( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
1942 if( $code == '301' || $code == '303' ) {
1943 if( !$wgDebugRedirects ) {
1944 $message = HttpStatus::getMessage( $code );
1945 $response->header( "HTTP/1.1 $code $message" );
1947 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1949 if ( $wgVaryOnXFP ) {
1950 $this->addVaryHeader( 'X-Forwarded-Proto' );
1952 $this->sendCacheControl();
1954 $response->header( "Content-Type: text/html; charset=utf-8" );
1955 if( $wgDebugRedirects ) {
1956 $url = htmlspecialchars( $redirect );
1957 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1958 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1959 print "</body>\n</html>\n";
1960 } else {
1961 $response->header( 'Location: ' . $redirect );
1965 wfProfileOut( __METHOD__ );
1966 return;
1967 } elseif ( $this->mStatusCode ) {
1968 $message = HttpStatus::getMessage( $this->mStatusCode );
1969 if ( $message ) {
1970 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1974 # Buffer output; final headers may depend on later processing
1975 ob_start();
1977 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1978 $response->header( 'Content-language: ' . $wgLanguageCode );
1980 // Prevent framing, if requested
1981 $frameOptions = $this->getFrameOptions();
1982 if ( $frameOptions ) {
1983 $response->header( "X-Frame-Options: $frameOptions" );
1986 if ( $this->mArticleBodyOnly ) {
1987 $this->out( $this->mBodytext );
1988 } else {
1989 $this->addDefaultModules();
1991 $sk = $this->getSkin();
1993 // Hook that allows last minute changes to the output page, e.g.
1994 // adding of CSS or Javascript by extensions.
1995 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1997 wfProfileIn( 'Output-skin' );
1998 $sk->outputPage();
1999 wfProfileOut( 'Output-skin' );
2002 $this->sendCacheControl();
2003 ob_end_flush();
2004 wfProfileOut( __METHOD__ );
2008 * Actually output something with print().
2010 * @param $ins String: the string to output
2012 public function out( $ins ) {
2013 print $ins;
2017 * Produce a "user is blocked" page.
2018 * @deprecated since 1.18
2020 function blockedPage() {
2021 throw new UserBlockedError( $this->getUser()->mBlock );
2025 * Prepare this object to display an error page; disable caching and
2026 * indexing, clear the current text and redirect, set the page's title
2027 * and optionally an custom HTML title (content of the "<title>" tag).
2029 * @param $pageTitle String|Message will be passed directly to setPageTitle()
2030 * @param $htmlTitle String|Message will be passed directly to setHTMLTitle();
2031 * optional, if not passed the "<title>" attribute will be
2032 * based on $pageTitle
2034 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2035 if ( $this->getTitle() ) {
2036 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
2039 $this->setPageTitle( $pageTitle );
2040 if ( $htmlTitle !== false ) {
2041 $this->setHTMLTitle( $htmlTitle );
2043 $this->setRobotPolicy( 'noindex,nofollow' );
2044 $this->setArticleRelated( false );
2045 $this->enableClientCache( false );
2046 $this->mRedirect = '';
2047 $this->clearSubtitle();
2048 $this->clearHTML();
2052 * Output a standard error page
2054 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2055 * showErrorPage( 'titlemsg', $messageObject );
2057 * @param $title String: message key for page title
2058 * @param $msg Mixed: message key (string) for page text, or a Message object
2059 * @param $params Array: message parameters; ignored if $msg is a Message object
2061 public function showErrorPage( $title, $msg, $params = array() ) {
2062 $this->prepareErrorPage( $this->msg( $title ), $this->msg( 'errorpagetitle' ) );
2064 if ( $msg instanceof Message ){
2065 $this->addHTML( $msg->parse() );
2066 } else {
2067 $this->addWikiMsgArray( $msg, $params );
2070 $this->returnToMain();
2074 * Output a standard permission error page
2076 * @param $errors Array: error message keys
2077 * @param $action String: action that was denied or null if unknown
2079 public function showPermissionsErrorPage( $errors, $action = null ) {
2080 global $wgGroupPermissions;
2082 // For some action (read, edit, create and upload), display a "login to do this action"
2083 // error if all of the following conditions are met:
2084 // 1. the user is not logged in
2085 // 2. the only error is insufficient permissions (i.e. no block or something else)
2086 // 3. the error can be avoided simply by logging in
2087 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2088 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2089 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2090 && ( ( isset( $wgGroupPermissions['user'][$action] ) && $wgGroupPermissions['user'][$action] )
2091 || ( isset( $wgGroupPermissions['autoconfirmed'][$action] ) && $wgGroupPermissions['autoconfirmed'][$action] ) )
2093 $displayReturnto = null;
2095 # Due to bug 32276, if a user does not have read permissions,
2096 # $this->getTitle() will just give Special:Badtitle, which is
2097 # not especially useful as a returnto parameter. Use the title
2098 # from the request instead, if there was one.
2099 $request = $this->getRequest();
2100 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2101 if ( $action == 'edit' ) {
2102 $msg = 'whitelistedittext';
2103 $displayReturnto = $returnto;
2104 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2105 $msg = 'nocreatetext';
2106 } elseif ( $action == 'upload' ) {
2107 $msg = 'uploadnologintext';
2108 } else { # Read
2109 $msg = 'loginreqpagetext';
2110 $displayReturnto = Title::newMainPage();
2113 $query = array();
2115 if ( $returnto ) {
2116 $query['returnto'] = $returnto->getPrefixedText();
2118 if ( !$request->wasPosted() ) {
2119 $returntoquery = $request->getValues();
2120 unset( $returntoquery['title'] );
2121 unset( $returntoquery['returnto'] );
2122 unset( $returntoquery['returntoquery'] );
2123 $query['returntoquery'] = wfArrayToCGI( $returntoquery );
2126 $loginLink = Linker::linkKnown(
2127 SpecialPage::getTitleFor( 'Userlogin' ),
2128 $this->msg( 'loginreqlink' )->escaped(),
2129 array(),
2130 $query
2133 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2134 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2136 # Don't return to a page the user can't read otherwise
2137 # we'll end up in a pointless loop
2138 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2139 $this->returnToMain( null, $displayReturnto );
2141 } else {
2142 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2143 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2148 * Display an error page indicating that a given version of MediaWiki is
2149 * required to use it
2151 * @param $version Mixed: the version of MediaWiki needed to use the page
2153 public function versionRequired( $version ) {
2154 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2156 $this->addWikiMsg( 'versionrequiredtext', $version );
2157 $this->returnToMain();
2161 * Display an error page noting that a given permission bit is required.
2162 * @deprecated since 1.18, just throw the exception directly
2163 * @param $permission String: key required
2165 public function permissionRequired( $permission ) {
2166 throw new PermissionsError( $permission );
2170 * Produce the stock "please login to use the wiki" page
2172 * @deprecated in 1.19; throw the exception directly
2174 public function loginToUse() {
2175 throw new PermissionsError( 'read' );
2179 * Format a list of error messages
2181 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2182 * @param $action String: action that was denied or null if unknown
2183 * @return String: the wikitext error-messages, formatted into a list.
2185 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2186 if ( $action == null ) {
2187 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2188 } else {
2189 $action_desc = $this->msg( "action-$action" )->plain();
2190 $text = $this->msg(
2191 'permissionserrorstext-withaction',
2192 count( $errors ),
2193 $action_desc
2194 )->plain() . "\n\n";
2197 if ( count( $errors ) > 1 ) {
2198 $text .= '<ul class="permissions-errors">' . "\n";
2200 foreach( $errors as $error ) {
2201 $text .= '<li>';
2202 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2203 $text .= "</li>\n";
2205 $text .= '</ul>';
2206 } else {
2207 $text .= "<div class=\"permissions-errors\">\n" .
2208 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2209 "\n</div>";
2212 return $text;
2216 * Display a page stating that the Wiki is in read-only mode,
2217 * and optionally show the source of the page that the user
2218 * was trying to edit. Should only be called (for this
2219 * purpose) after wfReadOnly() has returned true.
2221 * For historical reasons, this function is _also_ used to
2222 * show the error message when a user tries to edit a page
2223 * they are not allowed to edit. (Unless it's because they're
2224 * blocked, then we show blockedPage() instead.) In this
2225 * case, the second parameter should be set to true and a list
2226 * of reasons supplied as the third parameter.
2228 * @todo Needs to be split into multiple functions.
2230 * @param $source String: source code to show (or null).
2231 * @param $protected Boolean: is this a permissions error?
2232 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2233 * @param $action String: action that was denied or null if unknown
2235 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2236 $this->setRobotPolicy( 'noindex,nofollow' );
2237 $this->setArticleRelated( false );
2239 // If no reason is given, just supply a default "I can't let you do
2240 // that, Dave" message. Should only occur if called by legacy code.
2241 if ( $protected && empty( $reasons ) ) {
2242 $reasons[] = array( 'badaccess-group0' );
2245 if ( !empty( $reasons ) ) {
2246 // Permissions error
2247 if( $source ) {
2248 $this->setPageTitle( $this->msg( 'viewsource-title', $this->getTitle()->getPrefixedText() ) );
2249 $this->addBacklinkSubtitle( $this->getTitle() );
2250 } else {
2251 $this->setPageTitle( $this->msg( 'badaccess' ) );
2253 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2254 } else {
2255 // Wiki is read only
2256 throw new ReadOnlyError;
2259 // Show source, if supplied
2260 if( is_string( $source ) ) {
2261 $this->addWikiMsg( 'viewsourcetext' );
2263 $pageLang = $this->getTitle()->getPageLanguage();
2264 $params = array(
2265 'id' => 'wpTextbox1',
2266 'name' => 'wpTextbox1',
2267 'cols' => $this->getUser()->getOption( 'cols' ),
2268 'rows' => $this->getUser()->getOption( 'rows' ),
2269 'readonly' => 'readonly',
2270 'lang' => $pageLang->getHtmlCode(),
2271 'dir' => $pageLang->getDir(),
2273 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2275 // Show templates used by this article
2276 $templates = Linker::formatTemplates( $this->getTitle()->getTemplateLinksFrom() );
2277 $this->addHTML( "<div class='templatesUsed'>
2278 $templates
2279 </div>
2280 " );
2283 # If the title doesn't exist, it's fairly pointless to print a return
2284 # link to it. After all, you just tried editing it and couldn't, so
2285 # what's there to do there?
2286 if( $this->getTitle()->exists() ) {
2287 $this->returnToMain( null, $this->getTitle() );
2292 * Turn off regular page output and return an error reponse
2293 * for when rate limiting has triggered.
2295 public function rateLimited() {
2296 throw new ThrottledError;
2300 * Show a warning about slave lag
2302 * If the lag is higher than $wgSlaveLagCritical seconds,
2303 * then the warning is a bit more obvious. If the lag is
2304 * lower than $wgSlaveLagWarning, then no warning is shown.
2306 * @param $lag Integer: slave lag
2308 public function showLagWarning( $lag ) {
2309 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2310 if( $lag >= $wgSlaveLagWarning ) {
2311 $message = $lag < $wgSlaveLagCritical
2312 ? 'lag-warn-normal'
2313 : 'lag-warn-high';
2314 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2315 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2319 public function showFatalError( $message ) {
2320 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2322 $this->addHTML( $message );
2325 public function showUnexpectedValueError( $name, $val ) {
2326 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2329 public function showFileCopyError( $old, $new ) {
2330 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2333 public function showFileRenameError( $old, $new ) {
2334 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2337 public function showFileDeleteError( $name ) {
2338 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2341 public function showFileNotFoundError( $name ) {
2342 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2346 * Add a "return to" link pointing to a specified title
2348 * @param $title Title to link
2349 * @param $query String query string
2350 * @param $text String text of the link (input is not escaped)
2352 public function addReturnTo( $title, $query = array(), $text = null ) {
2353 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2354 $link = $this->msg( 'returnto' )->rawParams(
2355 Linker::link( $title, $text, array(), $query ) )->escaped();
2356 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2360 * Add a "return to" link pointing to a specified title,
2361 * or the title indicated in the request, or else the main page
2363 * @param $unused
2364 * @param $returnto Title or String to return to
2365 * @param $returntoquery String: query string for the return to link
2367 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2368 if ( $returnto == null ) {
2369 $returnto = $this->getRequest()->getText( 'returnto' );
2372 if ( $returntoquery == null ) {
2373 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2376 if ( $returnto === '' ) {
2377 $returnto = Title::newMainPage();
2380 if ( is_object( $returnto ) ) {
2381 $titleObj = $returnto;
2382 } else {
2383 $titleObj = Title::newFromText( $returnto );
2385 if ( !is_object( $titleObj ) ) {
2386 $titleObj = Title::newMainPage();
2389 $this->addReturnTo( $titleObj, $returntoquery );
2393 * @param $sk Skin The given Skin
2394 * @param $includeStyle Boolean: unused
2395 * @return String: The doctype, opening "<html>", and head element.
2397 public function headElement( Skin $sk, $includeStyle = true ) {
2398 global $wgContLang;
2400 $userdir = $this->getLanguage()->getDir();
2401 $sitedir = $wgContLang->getDir();
2403 if ( $sk->commonPrintStylesheet() ) {
2404 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2407 $ret = Html::htmlHeader( array( 'lang' => $this->getLanguage()->getHtmlCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2409 if ( $this->getHTMLTitle() == '' ) {
2410 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() ) );
2413 $openHead = Html::openElement( 'head' );
2414 if ( $openHead ) {
2415 # Don't bother with the newline if $head == ''
2416 $ret .= "$openHead\n";
2419 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2421 $ret .= implode( "\n", array(
2422 $this->getHeadLinks( null, true ),
2423 $this->buildCssLinks(),
2424 $this->getHeadScripts(),
2425 $this->getHeadItems()
2426 ) );
2428 $closeHead = Html::closeElement( 'head' );
2429 if ( $closeHead ) {
2430 $ret .= "$closeHead\n";
2433 $bodyAttrs = array();
2435 # Classes for LTR/RTL directionality support
2436 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2438 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2439 # A <body> class is probably not the best way to do this . . .
2440 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2442 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2443 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2444 $bodyAttrs['class'] .= ' action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2446 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2447 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2449 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2451 return $ret;
2455 * Add the default ResourceLoader modules to this object
2457 private function addDefaultModules() {
2458 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil, $wgUseAjax,
2459 $wgAjaxWatch, $wgEnableMWSuggest;
2461 // Add base resources
2462 $this->addModules( array(
2463 'mediawiki.user',
2464 'mediawiki.page.startup',
2465 'mediawiki.page.ready',
2466 ) );
2467 if ( $wgIncludeLegacyJavaScript ){
2468 $this->addModules( 'mediawiki.legacy.wikibits' );
2471 if ( $wgPreloadJavaScriptMwUtil ) {
2472 $this->addModules( 'mediawiki.util' );
2475 MWDebug::addModules( $this );
2477 // Add various resources if required
2478 if ( $wgUseAjax ) {
2479 $this->addModules( 'mediawiki.legacy.ajax' );
2481 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2483 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2484 $this->addModules( 'mediawiki.page.watch.ajax' );
2487 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2488 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2492 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2493 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2496 # Crazy edit-on-double-click stuff
2497 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2498 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2503 * Get a ResourceLoader object associated with this OutputPage
2505 * @return ResourceLoader
2507 public function getResourceLoader() {
2508 if ( is_null( $this->mResourceLoader ) ) {
2509 $this->mResourceLoader = new ResourceLoader();
2511 return $this->mResourceLoader;
2515 * TODO: Document
2516 * @param $modules Array/string with the module name(s)
2517 * @param $only String ResourceLoaderModule TYPE_ class constant
2518 * @param $useESI boolean
2519 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2520 * @param $loadCall boolean If true, output an (asynchronous) mw.loader.load() call rather than a "<script src='...'>" tag
2521 * @return string html "<script>" and "<style>" tags
2523 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array(), $loadCall = false ) {
2524 global $wgResourceLoaderUseESI;
2526 $modules = (array) $modules;
2528 if ( !count( $modules ) ) {
2529 return '';
2532 if ( count( $modules ) > 1 ) {
2533 // Remove duplicate module requests
2534 $modules = array_unique( $modules );
2535 // Sort module names so requests are more uniform
2536 sort( $modules );
2538 if ( ResourceLoader::inDebugMode() ) {
2539 // Recursively call us for every item
2540 $links = '';
2541 foreach ( $modules as $name ) {
2542 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2544 return $links;
2548 // Create keyed-by-group list of module objects from modules list
2549 $groups = array();
2550 $resourceLoader = $this->getResourceLoader();
2551 foreach ( $modules as $name ) {
2552 $module = $resourceLoader->getModule( $name );
2553 # Check that we're allowed to include this module on this page
2554 if ( !$module
2555 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2556 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2557 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2558 && $only == ResourceLoaderModule::TYPE_STYLES )
2561 continue;
2564 $group = $module->getGroup();
2565 if ( !isset( $groups[$group] ) ) {
2566 $groups[$group] = array();
2568 $groups[$group][$name] = $module;
2571 $links = '';
2572 foreach ( $groups as $group => $grpModules ) {
2573 // Special handling for user-specific groups
2574 $user = null;
2575 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2576 $user = $this->getUser()->getName();
2579 // Create a fake request based on the one we are about to make so modules return
2580 // correct timestamp and emptiness data
2581 $query = ResourceLoader::makeLoaderQuery(
2582 array(), // modules; not determined yet
2583 $this->getLanguage()->getCode(),
2584 $this->getSkin()->getSkinName(),
2585 $user,
2586 null, // version; not determined yet
2587 ResourceLoader::inDebugMode(),
2588 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2589 $this->isPrintable(),
2590 $this->getRequest()->getBool( 'handheld' ),
2591 $extraQuery
2593 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2594 // Extract modules that know they're empty
2595 $emptyModules = array ();
2596 foreach ( $grpModules as $key => $module ) {
2597 if ( $module->isKnownEmpty( $context ) ) {
2598 $emptyModules[$key] = 'ready';
2599 unset( $grpModules[$key] );
2602 // Inline empty modules: since they're empty, just mark them as 'ready'
2603 if ( count( $emptyModules ) > 0 && $only !== ResourceLoaderModule::TYPE_STYLES ) {
2604 // If we're only getting the styles, we don't need to do anything for empty modules.
2605 $links .= Html::inlineScript(
2607 ResourceLoader::makeLoaderConditionalScript(
2609 ResourceLoader::makeLoaderStateScript( $emptyModules )
2613 ) . "\n";
2616 // If there are no modules left, skip this group
2617 if ( count( $grpModules ) === 0 ) {
2618 continue;
2621 // Inline private modules. These can't be loaded through load.php for security
2622 // reasons, see bug 34907. Note that these modules should be loaded from
2623 // getHeadScripts() before the first loader call. Otherwise other modules can't
2624 // properly use them as dependencies (bug 30914)
2625 if ( $group === 'private' ) {
2626 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2627 $links .= Html::inlineStyle(
2628 $resourceLoader->makeModuleResponse( $context, $grpModules )
2630 } else {
2631 $links .= Html::inlineScript(
2632 ResourceLoader::makeLoaderConditionalScript(
2633 $resourceLoader->makeModuleResponse( $context, $grpModules )
2637 $links .= "\n";
2638 continue;
2640 // Special handling for the user group; because users might change their stuff
2641 // on-wiki like user pages, or user preferences; we need to find the highest
2642 // timestamp of these user-changable modules so we can ensure cache misses on change
2643 // This should NOT be done for the site group (bug 27564) because anons get that too
2644 // and we shouldn't be putting timestamps in Squid-cached HTML
2645 $version = null;
2646 if ( $group === 'user' ) {
2647 // Get the maximum timestamp
2648 $timestamp = 1;
2649 foreach ( $grpModules as $module ) {
2650 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2652 // Add a version parameter so cache will break when things change
2653 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2656 $url = ResourceLoader::makeLoaderURL(
2657 array_keys( $grpModules ),
2658 $this->getLanguage()->getCode(),
2659 $this->getSkin()->getSkinName(),
2660 $user,
2661 $version,
2662 ResourceLoader::inDebugMode(),
2663 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2664 $this->isPrintable(),
2665 $this->getRequest()->getBool( 'handheld' ),
2666 $extraQuery
2668 if ( $useESI && $wgResourceLoaderUseESI ) {
2669 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2670 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2671 $link = Html::inlineStyle( $esi );
2672 } else {
2673 $link = Html::inlineScript( $esi );
2675 } else {
2676 // Automatically select style/script elements
2677 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2678 $link = Html::linkedStyle( $url );
2679 } else if ( $loadCall ) {
2680 $link = Html::inlineScript(
2681 ResourceLoader::makeLoaderConditionalScript(
2682 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2685 } else {
2686 $link = Html::linkedScript( $url );
2690 if( $group == 'noscript' ){
2691 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2692 } else {
2693 $links .= $link . "\n";
2696 return $links;
2700 * JS stuff to put in the "<head>". This is the startup module, config
2701 * vars and modules marked with position 'top'
2703 * @return String: HTML fragment
2705 function getHeadScripts() {
2706 global $wgResourceLoaderExperimentalAsyncLoading;
2708 // Startup - this will immediately load jquery and mediawiki modules
2709 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2711 // Load config before anything else
2712 $scripts .= Html::inlineScript(
2713 ResourceLoader::makeLoaderConditionalScript(
2714 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2718 // Load embeddable private modules before any loader links
2719 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2720 // in mw.loader.implement() calls and deferred until mw.user is available
2721 $embedScripts = array( 'user.options', 'user.tokens' );
2722 $scripts .= $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2724 // Script and Messages "only" requests marked for top inclusion
2725 // Messages should go first
2726 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2727 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2729 // Modules requests - let the client calculate dependencies and batch requests as it likes
2730 // Only load modules that have marked themselves for loading at the top
2731 $modules = $this->getModules( true, 'top' );
2732 if ( $modules ) {
2733 $scripts .= Html::inlineScript(
2734 ResourceLoader::makeLoaderConditionalScript(
2735 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2740 if ( $wgResourceLoaderExperimentalAsyncLoading ) {
2741 $scripts .= $this->getScriptsForBottomQueue( true );
2744 return $scripts;
2748 * JS stuff to put at the 'bottom', which can either be the bottom of the "<body>"
2749 * or the bottom of the "<head>" depending on $wgResourceLoaderExperimentalAsyncLoading:
2750 * modules marked with position 'bottom', legacy scripts ($this->mScripts),
2751 * user preferences, site JS and user JS
2753 * @param $inHead boolean If true, this HTML goes into the "<head>", if false it goes into the "<body>"
2754 * @return string
2756 function getScriptsForBottomQueue( $inHead ) {
2757 global $wgUseSiteJs, $wgAllowUserJs;
2759 // Script and Messages "only" requests marked for bottom inclusion
2760 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2761 // Messages should go first
2762 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2763 ResourceLoaderModule::TYPE_MESSAGES, /* $useESI = */ false, /* $extraQuery = */ array(),
2764 /* $loadCall = */ $inHead
2766 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2767 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
2768 /* $loadCall = */ $inHead
2771 // Modules requests - let the client calculate dependencies and batch requests as it likes
2772 // Only load modules that have marked themselves for loading at the bottom
2773 $modules = $this->getModules( true, 'bottom' );
2774 if ( $modules ) {
2775 $scripts .= Html::inlineScript(
2776 ResourceLoader::makeLoaderConditionalScript(
2777 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2782 // Legacy Scripts
2783 $scripts .= "\n" . $this->mScripts;
2785 $defaultModules = array();
2787 // Add site JS if enabled
2788 if ( $wgUseSiteJs ) {
2789 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
2790 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2792 $defaultModules['site'] = 'loading';
2793 } else {
2794 // The wiki is configured to not allow a site module.
2795 $defaultModules['site'] = 'missing';
2798 // Add user JS if enabled
2799 if ( $wgAllowUserJs ) {
2800 if ( $this->getUser()->isLoggedIn() ) {
2801 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2802 # XXX: additional security check/prompt?
2803 // We're on a preview of a JS subpage
2804 // Exclude this page from the user module in case it's in there (bug 26283)
2805 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2806 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
2808 // Load the previewed JS
2809 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2810 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
2811 // asynchronously and may arrive *after* the inline script here. So the previewed code
2812 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
2813 } else {
2814 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
2815 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
2816 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2819 $defaultModules['user'] = 'loading';
2820 } else {
2821 // Non-logged-in users have no user module. Treat it as empty and 'ready' to avoid
2822 // blocking default gadgets that might depend on it. Although arguably default-enabled
2823 // gadgets should not depend on the user module, it's harmless and less error-prone to
2824 // handle this case.
2825 $defaultModules['user'] = 'ready';
2827 } else {
2828 // User JS disabled
2829 $defaultModules['user'] = 'missing';
2832 // Group JS is only enabled if site JS is enabled.
2833 if ( $wgUseSiteJs ) {
2834 if ( $this->getUser()->isLoggedIn() ) {
2835 $scripts .= $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
2836 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2838 $defaultModules['user.groups'] = 'loading';
2839 } else {
2840 // Non-logged-in users have no user.groups module. Treat it as empty and 'ready' to
2841 // avoid blocking gadgets that might depend upon the module.
2842 $defaultModules['user.groups'] = 'ready';
2844 } else {
2845 // Site (and group JS) disabled
2846 $defaultModules['user.groups'] = 'missing';
2849 $loaderInit = '';
2850 if ( $inHead ) {
2851 // We generate loader calls anyway, so no need to fix the client-side loader's state to 'loading'.
2852 foreach ( $defaultModules as $m => $state ) {
2853 if ( $state == 'loading' ) {
2854 unset( $defaultModules[$m] );
2858 if ( count( $defaultModules ) > 0 ) {
2859 $loaderInit = Html::inlineScript(
2860 ResourceLoader::makeLoaderConditionalScript(
2861 ResourceLoader::makeLoaderStateScript( $defaultModules )
2863 ) . "\n";
2865 return $loaderInit . $scripts;
2869 * JS stuff to put at the bottom of the "<body>"
2870 * @return string
2872 function getBottomScripts() {
2873 global $wgResourceLoaderExperimentalAsyncLoading;
2874 if ( !$wgResourceLoaderExperimentalAsyncLoading ) {
2875 return $this->getScriptsForBottomQueue( false );
2876 } else {
2877 return '';
2882 * Add one or more variables to be set in mw.config in JavaScript.
2884 * @param $keys {String|Array} Key or array of key/value pairs.
2885 * @param $value {Mixed} [optional] Value of the configuration variable.
2887 public function addJsConfigVars( $keys, $value = null ) {
2888 if ( is_array( $keys ) ) {
2889 foreach ( $keys as $key => $value ) {
2890 $this->mJsConfigVars[$key] = $value;
2892 return;
2895 $this->mJsConfigVars[$keys] = $value;
2900 * Get an array containing the variables to be set in mw.config in JavaScript.
2902 * DO NOT CALL THIS FROM OUTSIDE OF THIS CLASS OR Skin::makeGlobalVariablesScript().
2903 * This is only public until that function is removed. You have been warned.
2905 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2906 * - in other words, page-independent/site-wide variables (without state).
2907 * You will only be adding bloat to the html page and causing page caches to
2908 * have to be purged on configuration changes.
2909 * @return array
2911 public function getJSVars() {
2912 global $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2914 $latestRevID = 0;
2915 $pageID = 0;
2916 $canonicalName = false; # bug 21115
2918 $title = $this->getTitle();
2919 $ns = $title->getNamespace();
2920 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2922 // Get the relevant title so that AJAX features can use the correct page name
2923 // when making API requests from certain special pages (bug 34972).
2924 $relevantTitle = $this->getSkin()->getRelevantTitle();
2926 if ( $ns == NS_SPECIAL ) {
2927 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2928 } elseif ( $this->canUseWikiPage() ) {
2929 $wikiPage = $this->getWikiPage();
2930 $latestRevID = $wikiPage->getLatest();
2931 $pageID = $wikiPage->getId();
2934 $lang = $title->getPageLanguage();
2936 // Pre-process information
2937 $separatorTransTable = $lang->separatorTransformTable();
2938 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
2939 $compactSeparatorTransTable = array(
2940 implode( "\t", array_keys( $separatorTransTable ) ),
2941 implode( "\t", $separatorTransTable ),
2943 $digitTransTable = $lang->digitTransformTable();
2944 $digitTransTable = $digitTransTable ? $digitTransTable : array();
2945 $compactDigitTransTable = array(
2946 implode( "\t", array_keys( $digitTransTable ) ),
2947 implode( "\t", $digitTransTable ),
2950 $vars = array(
2951 'wgCanonicalNamespace' => $nsname,
2952 'wgCanonicalSpecialPageName' => $canonicalName,
2953 'wgNamespaceNumber' => $title->getNamespace(),
2954 'wgPageName' => $title->getPrefixedDBKey(),
2955 'wgTitle' => $title->getText(),
2956 'wgCurRevisionId' => $latestRevID,
2957 'wgArticleId' => $pageID,
2958 'wgIsArticle' => $this->isArticle(),
2959 'wgAction' => Action::getActionName( $this->getContext() ),
2960 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2961 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2962 'wgCategories' => $this->getCategories(),
2963 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2964 'wgPageContentLanguage' => $lang->getCode(),
2965 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
2966 'wgDigitTransformTable' => $compactDigitTransTable,
2967 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
2968 'wgMonthNames' => $lang->getMonthNamesArray(),
2969 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
2970 'wgRelevantPageName' => $relevantTitle->getPrefixedDBKey(),
2972 if ( $wgContLang->hasVariants() ) {
2973 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2975 foreach ( $title->getRestrictionTypes() as $type ) {
2976 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2978 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2979 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $this->getUser() );
2981 if ( $title->isMainPage() ) {
2982 $vars['wgIsMainPage'] = true;
2984 if ( $this->mRedirectedFrom ) {
2985 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBKey();
2988 // Allow extensions to add their custom variables to the mw.config map.
2989 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2990 // page-dependant but site-wide (without state).
2991 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2992 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
2994 // Merge in variables from addJsConfigVars last
2995 return array_merge( $vars, $this->mJsConfigVars );
2999 * To make it harder for someone to slip a user a fake
3000 * user-JavaScript or user-CSS preview, a random token
3001 * is associated with the login session. If it's not
3002 * passed back with the preview request, we won't render
3003 * the code.
3005 * @return bool
3007 public function userCanPreview() {
3008 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3009 || !$this->getRequest()->wasPosted()
3010 || !$this->getUser()->matchEditToken(
3011 $this->getRequest()->getVal( 'wpEditToken' ) )
3013 return false;
3015 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3016 return false;
3019 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3023 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3025 * @return array in format "link name or number => 'link html'".
3027 public function getHeadLinksArray( $addContentType = false ) {
3028 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
3029 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
3030 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
3031 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
3032 $wgRightsPage, $wgRightsUrl;
3034 $tags = array();
3036 if ( $addContentType ) {
3037 if ( $wgHtml5 ) {
3038 # More succinct than <meta http-equiv=Content-Type>, has the
3039 # same effect
3040 $tags['meta-charset'] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
3041 } else {
3042 $tags['meta-content-type'] = Html::element( 'meta', array(
3043 'http-equiv' => 'Content-Type',
3044 'content' => "$wgMimeType; charset=UTF-8"
3045 ) );
3046 $tags['meta-content-style-type'] = Html::element( 'meta', array( // bug 15835
3047 'http-equiv' => 'Content-Style-Type',
3048 'content' => 'text/css'
3049 ) );
3053 $tags['meta-generator'] = Html::element( 'meta', array(
3054 'name' => 'generator',
3055 'content' => "MediaWiki $wgVersion",
3056 ) );
3058 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3059 if( $p !== 'index,follow' ) {
3060 // http://www.robotstxt.org/wc/meta-user.html
3061 // Only show if it's different from the default robots policy
3062 $tags['meta-robots'] = Html::element( 'meta', array(
3063 'name' => 'robots',
3064 'content' => $p,
3065 ) );
3068 if ( count( $this->mKeywords ) > 0 ) {
3069 $strip = array(
3070 "/<.*?" . ">/" => '',
3071 "/_/" => ' '
3073 $tags['meta-keywords'] = Html::element( 'meta', array(
3074 'name' => 'keywords',
3075 'content' => preg_replace(
3076 array_keys( $strip ),
3077 array_values( $strip ),
3078 implode( ',', $this->mKeywords )
3080 ) );
3083 foreach ( $this->mMetatags as $tag ) {
3084 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3085 $a = 'http-equiv';
3086 $tag[0] = substr( $tag[0], 5 );
3087 } else {
3088 $a = 'name';
3090 $tagName = "meta-{$tag[0]}";
3091 if ( isset( $tags[$tagName] ) ) {
3092 $tagName .= $tag[1];
3094 $tags[$tagName] = Html::element( 'meta',
3095 array(
3096 $a => $tag[0],
3097 'content' => $tag[1]
3102 foreach ( $this->mLinktags as $tag ) {
3103 $tags[] = Html::element( 'link', $tag );
3106 # Universal edit button
3107 if ( $wgUniversalEditButton && $this->isArticleRelated() ) {
3108 $user = $this->getUser();
3109 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3110 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3111 // Original UniversalEditButton
3112 $msg = $this->msg( 'edit' )->text();
3113 $tags['universal-edit-button'] = Html::element( 'link', array(
3114 'rel' => 'alternate',
3115 'type' => 'application/x-wiki',
3116 'title' => $msg,
3117 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3118 ) );
3119 // Alternate edit link
3120 $tags['alternative-edit'] = Html::element( 'link', array(
3121 'rel' => 'edit',
3122 'title' => $msg,
3123 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
3124 ) );
3128 # Generally the order of the favicon and apple-touch-icon links
3129 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3130 # uses whichever one appears later in the HTML source. Make sure
3131 # apple-touch-icon is specified first to avoid this.
3132 if ( $wgAppleTouchIcon !== false ) {
3133 $tags['apple-touch-icon'] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
3136 if ( $wgFavicon !== false ) {
3137 $tags['favicon'] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
3140 # OpenSearch description link
3141 $tags['opensearch'] = Html::element( 'link', array(
3142 'rel' => 'search',
3143 'type' => 'application/opensearchdescription+xml',
3144 'href' => wfScript( 'opensearch_desc' ),
3145 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3146 ) );
3148 if ( $wgEnableAPI ) {
3149 # Real Simple Discovery link, provides auto-discovery information
3150 # for the MediaWiki API (and potentially additional custom API
3151 # support such as WordPress or Twitter-compatible APIs for a
3152 # blogging extension, etc)
3153 $tags['rsd'] = Html::element( 'link', array(
3154 'rel' => 'EditURI',
3155 'type' => 'application/rsd+xml',
3156 // Output a protocol-relative URL here if $wgServer is protocol-relative
3157 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3158 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
3159 ) );
3163 # Language variants
3164 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks ) {
3165 $lang = $this->getTitle()->getPageLanguage();
3166 if ( $lang->hasVariants() ) {
3168 $urlvar = $lang->getURLVariant();
3170 if ( !$urlvar ) {
3171 $variants = $lang->getVariants();
3172 foreach ( $variants as $_v ) {
3173 $tags["variant-$_v"] = Html::element( 'link', array(
3174 'rel' => 'alternate',
3175 'hreflang' => $_v,
3176 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3179 } else {
3180 $tags['canonical'] = Html::element( 'link', array(
3181 'rel' => 'canonical',
3182 'href' => $this->getTitle()->getCanonicalUrl()
3183 ) );
3188 # Copyright
3189 $copyright = '';
3190 if ( $wgRightsPage ) {
3191 $copy = Title::newFromText( $wgRightsPage );
3193 if ( $copy ) {
3194 $copyright = $copy->getLocalURL();
3198 if ( !$copyright && $wgRightsUrl ) {
3199 $copyright = $wgRightsUrl;
3202 if ( $copyright ) {
3203 $tags['copyright'] = Html::element( 'link', array(
3204 'rel' => 'copyright',
3205 'href' => $copyright )
3209 # Feeds
3210 if ( $wgFeed ) {
3211 foreach( $this->getSyndicationLinks() as $format => $link ) {
3212 # Use the page name for the title. In principle, this could
3213 # lead to issues with having the same name for different feeds
3214 # corresponding to the same page, but we can't avoid that at
3215 # this low a level.
3217 $tags[] = $this->feedLink(
3218 $format,
3219 $link,
3220 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3221 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3225 # Recent changes feed should appear on every page (except recentchanges,
3226 # that would be redundant). Put it after the per-page feed to avoid
3227 # changing existing behavior. It's still available, probably via a
3228 # menu in your browser. Some sites might have a different feed they'd
3229 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3230 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3231 # If so, use it instead.
3232 if ( $wgOverrideSiteFeed ) {
3233 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
3234 // Note, this->feedLink escapes the url.
3235 $tags[] = $this->feedLink(
3236 $type,
3237 $feedUrl,
3238 $this->msg( "site-{$type}-feed", $wgSitename )->text()
3241 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3242 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3243 foreach ( $wgAdvertisedFeedTypes as $format ) {
3244 $tags[] = $this->feedLink(
3245 $format,
3246 $rctitle->getLocalURL( "feed={$format}" ),
3247 $this->msg( "site-{$format}-feed", $wgSitename )->text() # For grep: 'site-rss-feed', 'site-atom-feed'.
3252 return $tags;
3256 * @param $unused
3257 * @param $addContentType bool: Whether "<meta>" specifying content type should be returned
3259 * @return string HTML tag links to be put in the header.
3261 public function getHeadLinks( $unused = null, $addContentType = false ) {
3262 return implode( "\n", $this->getHeadLinksArray( $addContentType ) );
3266 * Generate a "<link rel/>" for a feed.
3268 * @param $type String: feed type
3269 * @param $url String: URL to the feed
3270 * @param $text String: value of the "title" attribute
3271 * @return String: HTML fragment
3273 private function feedLink( $type, $url, $text ) {
3274 return Html::element( 'link', array(
3275 'rel' => 'alternate',
3276 'type' => "application/$type+xml",
3277 'title' => $text,
3278 'href' => $url )
3283 * Add a local or specified stylesheet, with the given media options.
3284 * Meant primarily for internal use...
3286 * @param $style String: URL to the file
3287 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
3288 * @param $condition String: for IE conditional comments, specifying an IE version
3289 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
3291 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3292 $options = array();
3293 // Even though we expect the media type to be lowercase, but here we
3294 // force it to lowercase to be safe.
3295 if( $media ) {
3296 $options['media'] = $media;
3298 if( $condition ) {
3299 $options['condition'] = $condition;
3301 if( $dir ) {
3302 $options['dir'] = $dir;
3304 $this->styles[$style] = $options;
3308 * Adds inline CSS styles
3309 * @param $style_css Mixed: inline CSS
3310 * @param $flip String: Set to 'flip' to flip the CSS if needed
3312 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3313 if( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3314 # If wanted, and the interface is right-to-left, flip the CSS
3315 $style_css = CSSJanus::transform( $style_css, true, false );
3317 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3321 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3322 * These will be applied to various media & IE conditionals.
3324 * @return string
3326 public function buildCssLinks() {
3327 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs,
3328 $wgLang, $wgContLang;
3330 $this->getSkin()->setupSkinUserCss( $this );
3332 // Add ResourceLoader styles
3333 // Split the styles into four groups
3334 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3335 $otherTags = ''; // Tags to append after the normal <link> tags
3336 $resourceLoader = $this->getResourceLoader();
3338 $moduleStyles = $this->getModuleStyles();
3340 // Per-site custom styles
3341 if ( $wgUseSiteCss ) {
3342 $moduleStyles[] = 'site';
3343 $moduleStyles[] = 'noscript';
3344 if( $this->getUser()->isLoggedIn() ){
3345 $moduleStyles[] = 'user.groups';
3349 // Per-user custom styles
3350 if ( $wgAllowUserCss ) {
3351 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3352 // We're on a preview of a CSS subpage
3353 // Exclude this page from the user module in case it's in there (bug 26283)
3354 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3355 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3358 // Load the previewed CSS
3359 // If needed, Janus it first. This is user-supplied CSS, so it's
3360 // assumed to be right for the content language directionality.
3361 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3362 if ( $wgLang->getDir() !== $wgContLang->getDir() ) {
3363 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3365 $otherTags .= Html::inlineStyle( $previewedCSS );
3366 } else {
3367 // Load the user styles normally
3368 $moduleStyles[] = 'user';
3372 // Per-user preference styles
3373 if ( $wgAllowUserCssPrefs ) {
3374 $moduleStyles[] = 'user.cssprefs';
3377 foreach ( $moduleStyles as $name ) {
3378 $module = $resourceLoader->getModule( $name );
3379 if ( !$module ) {
3380 continue;
3382 $group = $module->getGroup();
3383 // Modules in groups named "other" or anything different than "user", "site" or "private"
3384 // will be placed in the "other" group
3385 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3388 // We want site, private and user styles to override dynamically added styles from modules, but we want
3389 // dynamically added styles to override statically added styles from other modules. So the order
3390 // has to be other, dynamic, site, private, user
3391 // Add statically added styles for other modules
3392 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3393 // Add normal styles added through addStyle()/addInlineStyle() here
3394 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3395 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3396 // We use a <meta> tag with a made-up name for this because that's valid HTML
3397 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3399 // Add site, private and user styles
3400 // 'private' at present only contains user.options, so put that before 'user'
3401 // Any future private modules will likely have a similar user-specific character
3402 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3403 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3404 ResourceLoaderModule::TYPE_STYLES
3408 // Add stuff in $otherTags (previewed user CSS if applicable)
3409 $ret .= $otherTags;
3410 return $ret;
3414 * @return Array
3416 public function buildCssLinksArray() {
3417 $links = array();
3419 // Add any extension CSS
3420 foreach ( $this->mExtStyles as $url ) {
3421 $this->addStyle( $url );
3423 $this->mExtStyles = array();
3425 foreach( $this->styles as $file => $options ) {
3426 $link = $this->styleLink( $file, $options );
3427 if( $link ) {
3428 $links[$file] = $link;
3431 return $links;
3435 * Generate \<link\> tags for stylesheets
3437 * @param $style String: URL to the file
3438 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3439 * keys
3440 * @return String: HTML fragment
3442 protected function styleLink( $style, $options ) {
3443 if( isset( $options['dir'] ) ) {
3444 if( $this->getLanguage()->getDir() != $options['dir'] ) {
3445 return '';
3449 if( isset( $options['media'] ) ) {
3450 $media = self::transformCssMedia( $options['media'] );
3451 if( is_null( $media ) ) {
3452 return '';
3454 } else {
3455 $media = 'all';
3458 if( substr( $style, 0, 1 ) == '/' ||
3459 substr( $style, 0, 5 ) == 'http:' ||
3460 substr( $style, 0, 6 ) == 'https:' ) {
3461 $url = $style;
3462 } else {
3463 global $wgStylePath, $wgStyleVersion;
3464 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3467 $link = Html::linkedStyle( $url, $media );
3469 if( isset( $options['condition'] ) ) {
3470 $condition = htmlspecialchars( $options['condition'] );
3471 $link = "<!--[if $condition]>$link<![endif]-->";
3473 return $link;
3477 * Transform "media" attribute based on request parameters
3479 * @param $media String: current value of the "media" attribute
3480 * @return String: modified value of the "media" attribute
3482 public static function transformCssMedia( $media ) {
3483 global $wgRequest, $wgHandheldForIPhone;
3485 // Switch in on-screen display for media testing
3486 $switches = array(
3487 'printable' => 'print',
3488 'handheld' => 'handheld',
3490 foreach( $switches as $switch => $targetMedia ) {
3491 if( $wgRequest->getBool( $switch ) ) {
3492 if( $media == $targetMedia ) {
3493 $media = '';
3494 } elseif( $media == 'screen' ) {
3495 return null;
3500 // Expand longer media queries as iPhone doesn't grok 'handheld'
3501 if( $wgHandheldForIPhone ) {
3502 $mediaAliases = array(
3503 'screen' => 'screen and (min-device-width: 481px)',
3504 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3507 if( isset( $mediaAliases[$media] ) ) {
3508 $media = $mediaAliases[$media];
3512 return $media;
3516 * Add a wikitext-formatted message to the output.
3517 * This is equivalent to:
3519 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3521 public function addWikiMsg( /*...*/ ) {
3522 $args = func_get_args();
3523 $name = array_shift( $args );
3524 $this->addWikiMsgArray( $name, $args );
3528 * Add a wikitext-formatted message to the output.
3529 * Like addWikiMsg() except the parameters are taken as an array
3530 * instead of a variable argument list.
3532 * @param $name string
3533 * @param $args array
3535 public function addWikiMsgArray( $name, $args ) {
3536 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3540 * This function takes a number of message/argument specifications, wraps them in
3541 * some overall structure, and then parses the result and adds it to the output.
3543 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3544 * on. The subsequent arguments may either be strings, in which case they are the
3545 * message names, or arrays, in which case the first element is the message name,
3546 * and subsequent elements are the parameters to that message.
3548 * The special named parameter 'options' in a message specification array is passed
3549 * through to the $options parameter of wfMsgExt().
3551 * Don't use this for messages that are not in users interface language.
3553 * For example:
3555 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3557 * Is equivalent to:
3559 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3561 * The newline after opening div is needed in some wikitext. See bug 19226.
3563 * @param $wrap string
3565 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3566 $msgSpecs = func_get_args();
3567 array_shift( $msgSpecs );
3568 $msgSpecs = array_values( $msgSpecs );
3569 $s = $wrap;
3570 foreach ( $msgSpecs as $n => $spec ) {
3571 $options = array();
3572 if ( is_array( $spec ) ) {
3573 $args = $spec;
3574 $name = array_shift( $args );
3575 if ( isset( $args['options'] ) ) {
3576 $options = $args['options'];
3577 unset( $args['options'] );
3579 } else {
3580 $args = array();
3581 $name = $spec;
3583 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3585 $this->addWikiText( $s );
3589 * Include jQuery core. Use this to avoid loading it multiple times
3590 * before we get a usable script loader.
3592 * @param $modules Array: list of jQuery modules which should be loaded
3593 * @return Array: the list of modules which were not loaded.
3594 * @since 1.16
3595 * @deprecated since 1.17
3597 public function includeJQuery( $modules = array() ) {
3598 return array();