2 if ( !defined( 'MEDIAWIKI' ) ) {
7 * This class should be covered by a general architecture document which does
8 * not exist as of january 2011. This is one of the Core class and should
9 * be read at least once by any new developers.
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
14 * Another class (fixme) handle sending the whole page to the client.
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
22 // should be private. Used with addMeta() which add <meta>
23 var $mMetatags = array();
25 // <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
28 var $mLinktags = array();
30 // additional stylesheets. Looks like this is for extensions. Might be replaced by ressource loader.
31 var $mExtStyles = array();
33 // should be private. We got set/get accessors. Set the HTML title
36 // Contains all of the <BODY> content. Should be private we got set/get accessors and the append() method.
40 * Holds the debug lines that will be outputted as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
46 // should be private. Stores contents of <title> tg
49 // should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = true;
53 * should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections.
56 var $mPrintable = false;
59 * Should be private. We have set/get/append methods.
61 * Contains the article subtitle.
63 * Example: 'From Wikipedia, the free encyclopedia'
69 // mLastModified and mEtag are used for sending cache control.
70 // The whole caching system should probably be moved in its own class.
71 var $mLastModified = '';
74 * Should be private. No getter but used in sendCacheControl();
75 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
76 * as a unique identifier for the content. It is later used by the client
77 * to compare its cache version with the server version. Client sends
78 * headers If-Match and If-None-Match containing its local cache ETAG value.
80 * To get more information, you will have to look at HTTP1/1 protocols which
81 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
85 var $mCategoryLinks = array();
86 var $mCategories = array();
88 // Should be private. Associative array mapping language code to the page name
89 var $mLanguageLinks = array();
92 * Should be private. Used for javascript (or VB?)
93 * We should split js / css.
94 * mScripts content is inserted as is in <head> by Skin. This might contains
95 * either a link to a stylesheet or inline css.
98 var $mInlineStyles = ''; // ???
104 * Used by skin template.
105 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
107 var $mPageLinkTitle = '';
109 // Array of <head> elements. Parser might add its own headers!
110 var $mHeadItems = array();
112 // Next variables probably comes from the ressource loader @todo FIXME
113 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
114 var $mResourceLoader;
116 /** @fixme is this still used ?*/
117 var $mInlineMsg = array();
119 var $mTemplateIds = array();
121 // Initialized with a global value. Let us override it.
122 // Should probably get deleted / rewritten ...
126 * This was for the old skins and for users with 640x480 screen.
127 * Please note old sckins are still used and might prove useful for
128 * users having old computers or visually impaired.
130 var $mSuppressQuickbar = false;
133 * @EasterEgg I just love the name for this self documenting variable.
136 var $mDoNothing = false;
139 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
142 * should be private. Has get/set methods properly documented.
143 * Stores "article flag" toggle.
145 var $mIsArticleRelated = true;
147 // lazy initialised, use parserOptions()
148 protected $mParserOptions = null;
151 * Handles the atom / rss links.
152 * We probably only support atom in 2011.
153 * Looks like a private variable.
155 var $mFeedLinks = array();
157 // Gwicke work on squid caching? Roughly from 2003.
158 var $mEnableClientCache = true;
161 * Flag if output should only contain the body of the article.
164 var $mArticleBodyOnly = false;
166 var $mNewSectionLink = false;
167 var $mHideNewSectionLink = false;
170 * Comes from the parser. This was probably made to laod CSS/JS only
171 * if we had <gallery>. Used directly in CategoryPage.php
172 * Looks like resource loader can replace this.
174 var $mNoGallery = false;
176 // should be private.
177 var $mPageTitleActionText = '';
178 var $mParseWarnings = array();
180 // Cache stuff. Looks like mEnableClientCache
181 var $mSquidMaxage = 0;
184 var $mPreventClickjacking = true;
186 // should be private. To include the variable {{REVISIONID}}
187 var $mRevisionId = null;
189 // Stores a Title object.
190 protected $mTitle = null;
193 * An array of stylesheet filenames (relative from skins path), with options
194 * for CSS media, IE conditions, and RTL/LTR direction.
195 * For internal use; add settings in the skin via $this->addStyle()
197 * Style again! This seems like a code duplication since we already have
198 * mStyles. This is what makes OpenSource amazing.
200 var $styles = array();
203 * Whether to load jQuery core.
205 protected $mJQueryDone = false;
207 private $mIndexPolicy = 'index';
208 private $mFollowPolicy = 'follow';
209 private $mVaryHeader = array(
210 'Accept-Encoding' => array( 'list-contains=gzip' ),
216 * Initialise private variables
218 function __construct() {
219 global $wgAllowUserJs;
220 $this->mAllowUserJs
= $wgAllowUserJs;
224 * Redirect to $url rather than displaying the normal page
226 * @param $url String: URL
227 * @param $responsecode String: HTTP status code
229 public function redirect( $url, $responsecode = '302' ) {
230 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
231 $this->mRedirect
= str_replace( "\n", '', $url );
232 $this->mRedirectCode
= $responsecode;
236 * Get the URL to redirect to, or an empty string if not redirect URL set
240 public function getRedirect() {
241 return $this->mRedirect
;
245 * Set the HTTP status code to send with the output.
247 * @param $statusCode Integer
250 public function setStatusCode( $statusCode ) {
251 $this->mStatusCode
= $statusCode;
255 * Add a new <meta> tag
256 * To add an http-equiv meta tag, precede the name with "http:"
258 * @param $name tag name
259 * @param $val tag value
261 function addMeta( $name, $val ) {
262 array_push( $this->mMetatags
, array( $name, $val ) );
266 * Add a keyword or a list of keywords in the page header
268 * @param $text String or array of strings
270 function addKeyword( $text ) {
271 if( is_array( $text ) ) {
272 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
274 array_push( $this->mKeywords
, $text );
279 * Add a new \<link\> tag to the page header
281 * @param $linkarr Array: associative array of attributes.
283 function addLink( $linkarr ) {
284 array_push( $this->mLinktags
, $linkarr );
288 * Add a new \<link\> with "rel" attribute set to "meta"
290 * @param $linkarr Array: associative array mapping attribute names to their
291 * values, both keys and values will be escaped, and the
292 * "rel" attribute will be automatically added
294 function addMetadataLink( $linkarr ) {
295 # note: buggy CC software only reads first "meta" link
296 static $haveMeta = false;
297 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
298 $this->addLink( $linkarr );
303 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
305 * @param $script String: raw HTML
307 function addScript( $script ) {
308 $this->mScripts
.= $script . "\n";
312 * Register and add a stylesheet from an extension directory.
314 * @param $url String path to sheet. Provide either a full url (beginning
315 * with 'http', etc) or a relative path from the document root
316 * (beginning with '/'). Otherwise it behaves identically to
317 * addStyle() and draws from the /skins folder.
319 public function addExtensionStyle( $url ) {
320 array_push( $this->mExtStyles
, $url );
324 * Get all links added by extensions
328 function getExtStyle() {
329 return $this->mExtStyles
;
333 * Add a JavaScript file out of skins/common, or a given relative path.
335 * @param $file String: filename in skins/common or complete on-server path
337 * @param $version String: style version of the file. Defaults to $wgStyleVersion
339 public function addScriptFile( $file, $version = null ) {
340 global $wgStylePath, $wgStyleVersion;
341 // See if $file parameter is an absolute URL or begins with a slash
342 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
345 $path = "{$wgStylePath}/common/{$file}";
347 if ( is_null( $version ) )
348 $version = $wgStyleVersion;
349 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
353 * Add a self-contained script tag with the given contents
355 * @param $script String: JavaScript text, no <script> tags
357 public function addInlineScript( $script ) {
358 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
362 * Get all registered JS and CSS tags for the header.
366 function getScript() {
367 return $this->mScripts
. $this->getHeadItems();
371 * Get the list of modules to include on this page
373 * @return Array of module names
375 public function getModules() {
376 return array_values( array_unique( $this->mModules
) );
380 * Add one or more modules recognized by the resource loader. Modules added
381 * through this function will be loaded by the resource loader when the
384 * @param $modules Mixed: module name (string) or array of module names
386 public function addModules( $modules ) {
387 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
391 * Get the list of module JS to include on this page
392 * @return array of module names
394 public function getModuleScripts() {
395 return array_values( array_unique( $this->mModuleScripts
) );
399 * Add only JS of one or more modules recognized by the resource loader. Module
400 * scripts added through this function will be loaded by the resource loader when
403 * @param $modules Mixed: module name (string) or array of module names
405 public function addModuleScripts( $modules ) {
406 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
410 * Get the list of module CSS to include on this page
412 * @return Array of module names
414 public function getModuleStyles() {
415 return array_values( array_unique( $this->mModuleStyles
) );
419 * Add only CSS of one or more modules recognized by the resource loader. Module
420 * styles added through this function will be loaded by the resource loader when
423 * @param $modules Mixed: module name (string) or array of module names
425 public function addModuleStyles( $modules ) {
426 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
430 * Get the list of module messages to include on this page
432 * @return Array of module names
434 public function getModuleMessages() {
435 return array_values( array_unique( $this->mModuleMessages
) );
439 * Add only messages of one or more modules recognized by the resource loader.
440 * Module messages added through this function will be loaded by the resource
441 * loader when the page loads.
443 * @param $modules Mixed: module name (string) or array of module names
445 public function addModuleMessages( $modules ) {
446 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
450 * Get all header items in a string
454 function getHeadItems() {
456 foreach ( $this->mHeadItems
as $item ) {
463 * Add or replace an header item to the output
465 * @param $name String: item name
466 * @param $value String: raw HTML
468 public function addHeadItem( $name, $value ) {
469 $this->mHeadItems
[$name] = $value;
473 * Check if the header item $name is already set
475 * @param $name String: item name
478 public function hasHeadItem( $name ) {
479 return isset( $this->mHeadItems
[$name] );
483 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
485 * @param $tag String: value of "ETag" header
487 function setETag( $tag ) {
492 * Set whether the output should only contain the body of the article,
493 * without any skin, sidebar, etc.
494 * Used e.g. when calling with "action=render".
496 * @param $only Boolean: whether to output only the body of the article
498 public function setArticleBodyOnly( $only ) {
499 $this->mArticleBodyOnly
= $only;
503 * Return whether the output will contain only the body of the article
507 public function getArticleBodyOnly() {
508 return $this->mArticleBodyOnly
;
512 * checkLastModified tells the client to use the client-cached page if
513 * possible. If sucessful, the OutputPage is disabled so that
514 * any future call to OutputPage->output() have no effect.
516 * Side effect: sets mLastModified for Last-Modified header
518 * @return Boolean: true iff cache-ok headers was sent.
520 public function checkLastModified( $timestamp ) {
521 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
523 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
524 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
527 if( !$wgCachePages ) {
528 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
531 if( $wgUser->getOption( 'nocache' ) ) {
532 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
536 $timestamp = wfTimestamp( TS_MW
, $timestamp );
537 $modifiedTimes = array(
538 'page' => $timestamp,
539 'user' => $wgUser->getTouched(),
540 'epoch' => $wgCacheEpoch
542 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
544 $maxModified = max( $modifiedTimes );
545 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
547 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
548 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
554 foreach ( $modifiedTimes as $name => $value ) {
555 if ( $info !== '' ) {
558 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
561 # IE sends sizes after the date like this:
562 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
563 # this breaks strtotime().
564 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
566 wfSuppressWarnings(); // E_STRICT system time bitching
567 $clientHeaderTime = strtotime( $clientHeader );
569 if ( !$clientHeaderTime ) {
570 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
573 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
575 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
576 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
577 wfDebug( __METHOD__
. ": effective Last-Modified: " .
578 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
579 if( $clientHeaderTime < $maxModified ) {
580 wfDebug( __METHOD__
. ": STALE, $info\n", false );
585 # Give a 304 response code and disable body output
586 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
587 ini_set( 'zlib.output_compression', 0 );
588 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
589 $this->sendCacheControl();
592 // Don't output a compressed blob when using ob_gzhandler;
593 // it's technically against HTTP spec and seems to confuse
594 // Firefox when the response gets split over two packets.
595 wfClearOutputBuffers();
601 * Override the last modified timestamp
603 * @param $timestamp String: new timestamp, in a format readable by
606 public function setLastModified( $timestamp ) {
607 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
611 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
613 * @param $policy String: the literal string to output as the contents of
614 * the meta tag. Will be parsed according to the spec and output in
618 public function setRobotPolicy( $policy ) {
619 $policy = Article
::formatRobotPolicy( $policy );
621 if( isset( $policy['index'] ) ) {
622 $this->setIndexPolicy( $policy['index'] );
624 if( isset( $policy['follow'] ) ) {
625 $this->setFollowPolicy( $policy['follow'] );
630 * Set the index policy for the page, but leave the follow policy un-
633 * @param $policy string Either 'index' or 'noindex'.
636 public function setIndexPolicy( $policy ) {
637 $policy = trim( $policy );
638 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
639 $this->mIndexPolicy
= $policy;
644 * Set the follow policy for the page, but leave the index policy un-
647 * @param $policy String: either 'follow' or 'nofollow'.
650 public function setFollowPolicy( $policy ) {
651 $policy = trim( $policy );
652 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
653 $this->mFollowPolicy
= $policy;
658 * Set the new value of the "action text", this will be added to the
659 * "HTML title", separated from it with " - ".
661 * @param $text String: new value of the "action text"
663 public function setPageTitleActionText( $text ) {
664 $this->mPageTitleActionText
= $text;
668 * Get the value of the "action text"
672 public function getPageTitleActionText() {
673 if ( isset( $this->mPageTitleActionText
) ) {
674 return $this->mPageTitleActionText
;
679 * "HTML title" means the contents of <title>.
680 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
682 public function setHTMLTitle( $name ) {
683 $this->mHTMLtitle
= $name;
687 * Return the "HTML title", i.e. the content of the <title> tag.
691 public function getHTMLTitle() {
692 return $this->mHTMLtitle
;
696 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
697 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
698 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
699 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
701 public function setPageTitle( $name ) {
702 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
703 # but leave "<i>foobar</i>" alone
704 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
705 $this->mPagetitle
= $nameWithTags;
707 # change "<i>foo&bar</i>" to "foo&bar"
708 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
712 * Return the "page title", i.e. the content of the \<h1\> tag.
716 public function getPageTitle() {
717 return $this->mPagetitle
;
721 * Set the Title object to use
723 * @param $t Title object
725 public function setTitle( $t ) {
730 * Get the Title object used in this instance
734 public function getTitle() {
735 if ( $this->mTitle
instanceof Title
) {
736 return $this->mTitle
;
738 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
745 * Replace the subtile with $str
747 * @param $str String: new value of the subtitle
749 public function setSubtitle( $str ) {
750 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
754 * Add $str to the subtitle
756 * @param $str String to add to the subtitle
758 public function appendSubtitle( $str ) {
759 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
767 public function getSubtitle() {
768 return $this->mSubtitle
;
772 * Set the page as printable, i.e. it'll be displayed with with all
773 * print styles included
775 public function setPrintable() {
776 $this->mPrintable
= true;
780 * Return whether the page is "printable"
784 public function isPrintable() {
785 return $this->mPrintable
;
789 * Disable output completely, i.e. calling output() will have no effect
791 public function disable() {
792 $this->mDoNothing
= true;
796 * Return whether the output will be completely disabled
800 public function isDisabled() {
801 return $this->mDoNothing
;
805 * Show an "add new section" link?
809 public function showNewSectionLink() {
810 return $this->mNewSectionLink
;
814 * Forcibly hide the new section link?
818 public function forceHideNewSectionLink() {
819 return $this->mHideNewSectionLink
;
823 * Add or remove feed links in the page header
824 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
825 * for the new version
828 * @param $show Boolean: true: add default feeds, false: remove all feeds
830 public function setSyndicated( $show = true ) {
832 $this->setFeedAppendQuery( false );
834 $this->mFeedLinks
= array();
839 * Add default feeds to the page header
840 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
841 * for the new version
844 * @param $val String: query to append to feed links or false to output
847 public function setFeedAppendQuery( $val ) {
848 global $wgAdvertisedFeedTypes;
850 $this->mFeedLinks
= array();
852 foreach ( $wgAdvertisedFeedTypes as $type ) {
853 $query = "feed=$type";
854 if ( is_string( $val ) ) {
855 $query .= '&' . $val;
857 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
862 * Add a feed link to the page header
864 * @param $format String: feed type, should be a key of $wgFeedClasses
865 * @param $href String: URL
867 public function addFeedLink( $format, $href ) {
868 global $wgAdvertisedFeedTypes;
870 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
871 $this->mFeedLinks
[$format] = $href;
876 * Should we output feed links for this page?
879 public function isSyndicated() {
880 return count( $this->mFeedLinks
) > 0;
884 * Return URLs for each supported syndication format for this page.
885 * @return array associating format keys with URLs
887 public function getSyndicationLinks() {
888 return $this->mFeedLinks
;
892 * Will currently always return null
896 public function getFeedAppendQuery() {
897 return $this->mFeedLinksAppendQuery
;
901 * Set whether the displayed content is related to the source of the
902 * corresponding article on the wiki
903 * Setting true will cause the change "article related" toggle to true
907 public function setArticleFlag( $v ) {
908 $this->mIsarticle
= $v;
910 $this->mIsArticleRelated
= $v;
915 * Return whether the content displayed page is related to the source of
916 * the corresponding article on the wiki
920 public function isArticle() {
921 return $this->mIsarticle
;
925 * Set whether this page is related an article on the wiki
926 * Setting false will cause the change of "article flag" toggle to false
930 public function setArticleRelated( $v ) {
931 $this->mIsArticleRelated
= $v;
933 $this->mIsarticle
= false;
938 * Return whether this page is related an article on the wiki
942 public function isArticleRelated() {
943 return $this->mIsArticleRelated
;
947 * Add new language links
949 * @param $newLinkArray Associative array mapping language code to the page
952 public function addLanguageLinks( $newLinkArray ) {
953 $this->mLanguageLinks +
= $newLinkArray;
957 * Reset the language links and add new language links
959 * @param $newLinkArray Associative array mapping language code to the page
962 public function setLanguageLinks( $newLinkArray ) {
963 $this->mLanguageLinks
= $newLinkArray;
967 * Get the list of language links
969 * @return Associative array mapping language code to the page name
971 public function getLanguageLinks() {
972 return $this->mLanguageLinks
;
976 * Add an array of categories, with names in the keys
978 * @param $categories Associative array mapping category name to its sort key
980 public function addCategoryLinks( $categories ) {
981 global $wgUser, $wgContLang;
983 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
987 # Add the links to a LinkBatch
988 $arr = array( NS_CATEGORY
=> $categories );
990 $lb->setArray( $arr );
992 # Fetch existence plus the hiddencat property
993 $dbr = wfGetDB( DB_SLAVE
);
994 $pageTable = $dbr->tableName( 'page' );
995 $where = $lb->constructSet( 'page', $dbr );
996 $propsTable = $dbr->tableName( 'page_props' );
997 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
998 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
999 $res = $dbr->query( $sql, __METHOD__
);
1001 # Add the results to the link cache
1002 $lb->addResultToCache( LinkCache
::singleton(), $res );
1004 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1005 $categories = array_combine(
1006 array_keys( $categories ),
1007 array_fill( 0, count( $categories ), 'normal' )
1010 # Mark hidden categories
1011 foreach ( $res as $row ) {
1012 if ( isset( $row->pp_value
) ) {
1013 $categories[$row->page_title
] = 'hidden';
1017 # Add the remaining categories to the skin
1018 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1019 $sk = $wgUser->getSkin();
1020 foreach ( $categories as $category => $type ) {
1021 $origcategory = $category;
1022 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1023 $wgContLang->findVariantLink( $category, $title, true );
1024 if ( $category != $origcategory ) {
1025 if ( array_key_exists( $category, $categories ) ) {
1029 $text = $wgContLang->convertHtml( $title->getText() );
1030 $this->mCategories
[] = $title->getText();
1031 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
1037 * Reset the category links (but not the category list) and add $categories
1039 * @param $categories Associative array mapping category name to its sort key
1041 public function setCategoryLinks( $categories ) {
1042 $this->mCategoryLinks
= array();
1043 $this->addCategoryLinks( $categories );
1047 * Get the list of category links, in a 2-D array with the following format:
1048 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1049 * hidden categories) and $link a HTML fragment with a link to the category
1054 public function getCategoryLinks() {
1055 return $this->mCategoryLinks
;
1059 * Get the list of category names this page belongs to
1061 * @return Array of strings
1063 public function getCategories() {
1064 return $this->mCategories
;
1068 * Suppress the quickbar from the output, only for skin supporting
1071 public function suppressQuickbar() {
1072 $this->mSuppressQuickbar
= true;
1076 * Return whether the quickbar should be suppressed from the output
1080 public function isQuickbarSuppressed() {
1081 return $this->mSuppressQuickbar
;
1085 * Remove user JavaScript from scripts to load
1087 public function disallowUserJs() {
1088 $this->mAllowUserJs
= false;
1092 * Return whether user JavaScript is allowed for this page
1096 public function isUserJsAllowed() {
1097 return $this->mAllowUserJs
;
1101 * Prepend $text to the body HTML
1103 * @param $text String: HTML
1105 public function prependHTML( $text ) {
1106 $this->mBodytext
= $text . $this->mBodytext
;
1110 * Append $text to the body HTML
1112 * @param $text String: HTML
1114 public function addHTML( $text ) {
1115 $this->mBodytext
.= $text;
1119 * Clear the body HTML
1121 public function clearHTML() {
1122 $this->mBodytext
= '';
1128 * @return String: HTML
1130 public function getHTML() {
1131 return $this->mBodytext
;
1135 * Add $text to the debug output
1137 * @param $text String: debug text
1139 public function debug( $text ) {
1140 $this->mDebugtext
.= $text;
1144 * Get/set the ParserOptions object to use for wikitext parsing
1146 * @param $options either the ParserOption to use or null to only get the
1147 * current ParserOption object
1148 * @return current ParserOption object
1150 public function parserOptions( $options = null ) {
1151 if ( !$this->mParserOptions
) {
1152 $this->mParserOptions
= new ParserOptions
;
1154 return wfSetVar( $this->mParserOptions
, $options );
1158 * Set the revision ID which will be seen by the wiki text parser
1159 * for things such as embedded {{REVISIONID}} variable use.
1161 * @param $revid Mixed: an positive integer, or null
1162 * @return Mixed: previous value
1164 public function setRevisionId( $revid ) {
1165 $val = is_null( $revid ) ?
null : intval( $revid );
1166 return wfSetVar( $this->mRevisionId
, $val );
1170 * Get the current revision ID
1174 public function getRevisionId() {
1175 return $this->mRevisionId
;
1179 * Convert wikitext to HTML and add it to the buffer
1180 * Default assumes that the current page title will be used.
1182 * @param $text String
1183 * @param $linestart Boolean: is this the start of a line?
1185 public function addWikiText( $text, $linestart = true ) {
1186 $title = $this->getTitle(); // Work arround E_STRICT
1187 $this->addWikiTextTitle( $text, $title, $linestart );
1191 * Add wikitext with a custom Title object
1193 * @param $text String: wikitext
1194 * @param $title Title object
1195 * @param $linestart Boolean: is this the start of a line?
1197 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1198 $this->addWikiTextTitle( $text, $title, $linestart );
1202 * Add wikitext with a custom Title object and
1204 * @param $text String: wikitext
1205 * @param $title Title object
1206 * @param $linestart Boolean: is this the start of a line?
1208 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1209 $this->addWikiTextTitle( $text, $title, $linestart, true );
1213 * Add wikitext with tidy enabled
1215 * @param $text String: wikitext
1216 * @param $linestart Boolean: is this the start of a line?
1218 public function addWikiTextTidy( $text, $linestart = true ) {
1219 $title = $this->getTitle();
1220 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1224 * Add wikitext with a custom Title object
1226 * @param $text String: wikitext
1227 * @param $title Title object
1228 * @param $linestart Boolean: is this the start of a line?
1229 * @param $tidy Boolean: whether to use tidy
1231 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1234 wfProfileIn( __METHOD__
);
1236 wfIncrStats( 'pcache_not_possible' );
1238 $popts = $this->parserOptions();
1239 $oldTidy = $popts->setTidy( $tidy );
1241 $parserOutput = $wgParser->parse(
1242 $text, $title, $popts,
1243 $linestart, true, $this->mRevisionId
1246 $popts->setTidy( $oldTidy );
1248 $this->addParserOutput( $parserOutput );
1250 wfProfileOut( __METHOD__
);
1254 * Add a ParserOutput object, but without Html
1256 * @param $parserOutput ParserOutput object
1258 public function addParserOutputNoText( &$parserOutput ) {
1259 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1260 $this->addCategoryLinks( $parserOutput->getCategories() );
1261 $this->mNewSectionLink
= $parserOutput->getNewSection();
1262 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1264 $this->mParseWarnings
= $parserOutput->getWarnings();
1265 if ( !$parserOutput->isCacheable() ) {
1266 $this->enableClientCache( false );
1268 $this->mNoGallery
= $parserOutput->getNoGallery();
1269 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1270 $this->addModules( $parserOutput->getModules() );
1272 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1273 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1274 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1276 $this->mTemplateIds
[$ns] = $dbks;
1280 // Hooks registered in the object
1281 global $wgParserOutputHooks;
1282 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1283 list( $hookName, $data ) = $hookInfo;
1284 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1285 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1289 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1293 * Add a ParserOutput object
1295 * @param $parserOutput ParserOutput
1297 function addParserOutput( &$parserOutput ) {
1298 $this->addParserOutputNoText( $parserOutput );
1299 $text = $parserOutput->getText();
1300 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1301 $this->addHTML( $text );
1306 * Add the output of a QuickTemplate to the output buffer
1308 * @param $template QuickTemplate
1310 public function addTemplate( &$template ) {
1312 $template->execute();
1313 $this->addHTML( ob_get_contents() );
1318 * Parse wikitext and return the HTML.
1320 * @param $text String
1321 * @param $linestart Boolean: is this the start of a line?
1322 * @param $interface Boolean: use interface language ($wgLang instead of
1323 * $wgContLang) while parsing language sensitive magic
1324 * words like GRAMMAR and PLURAL
1325 * @param $language Language object: target language object, will override
1327 * @return String: HTML
1329 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1330 // Check one for one common cause for parser state resetting
1331 $callers = wfGetAllCallers( 10 );
1332 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1333 throw new MWException( "wfMsg* function with parsing cannot be used " .
1334 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1339 if( is_null( $this->getTitle() ) ) {
1340 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1343 $popts = $this->parserOptions();
1345 $popts->setInterfaceMessage( true );
1347 if ( $language !== null ) {
1348 $oldLang = $popts->setTargetLanguage( $language );
1351 $parserOutput = $wgParser->parse(
1352 $text, $this->getTitle(), $popts,
1353 $linestart, true, $this->mRevisionId
1357 $popts->setInterfaceMessage( false );
1359 if ( $language !== null ) {
1360 $popts->setTargetLanguage( $oldLang );
1363 return $parserOutput->getText();
1367 * Parse wikitext, strip paragraphs, and return the HTML.
1369 * @param $text String
1370 * @param $linestart Boolean: is this the start of a line?
1371 * @param $interface Boolean: use interface language ($wgLang instead of
1372 * $wgContLang) while parsing language sensitive magic
1373 * words like GRAMMAR and PLURAL
1374 * @return String: HTML
1376 public function parseInline( $text, $linestart = true, $interface = false ) {
1377 $parsed = $this->parse( $text, $linestart, $interface );
1380 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1388 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1390 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1392 public function setSquidMaxage( $maxage ) {
1393 $this->mSquidMaxage
= $maxage;
1397 * Use enableClientCache(false) to force it to send nocache headers
1401 public function enableClientCache( $state ) {
1402 return wfSetVar( $this->mEnableClientCache
, $state );
1406 * Get the list of cookies that will influence on the cache
1410 function getCacheVaryCookies() {
1411 global $wgCookiePrefix, $wgCacheVaryCookies;
1413 if ( $cookies === null ) {
1414 $cookies = array_merge(
1416 "{$wgCookiePrefix}Token",
1417 "{$wgCookiePrefix}LoggedOut",
1422 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1428 * Return whether this page is not cacheable because "useskin" or "uselang"
1429 * URL parameters were passed.
1433 function uncacheableBecauseRequestVars() {
1435 return $wgRequest->getText( 'useskin', false ) === false
1436 && $wgRequest->getText( 'uselang', false ) === false;
1440 * Check if the request has a cache-varying cookie header
1441 * If it does, it's very important that we don't allow public caching
1445 function haveCacheVaryCookies() {
1447 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1448 if ( $cookieHeader === false ) {
1451 $cvCookies = $this->getCacheVaryCookies();
1452 foreach ( $cvCookies as $cookieName ) {
1453 # Check for a simple string match, like the way squid does it
1454 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1455 wfDebug( __METHOD__
. ": found $cookieName\n" );
1459 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1464 * Add an HTTP header that will influence on the cache
1466 * @param $header String: header name
1467 * @param $option either an Array or null
1469 public function addVaryHeader( $header, $option = null ) {
1470 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1471 $this->mVaryHeader
[$header] = $option;
1472 } elseif( is_array( $option ) ) {
1473 if( is_array( $this->mVaryHeader
[$header] ) ) {
1474 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1476 $this->mVaryHeader
[$header] = $option;
1479 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1483 * Get a complete X-Vary-Options header
1487 public function getXVO() {
1488 $cvCookies = $this->getCacheVaryCookies();
1490 $cookiesOption = array();
1491 foreach ( $cvCookies as $cookieName ) {
1492 $cookiesOption[] = 'string-contains=' . $cookieName;
1494 $this->addVaryHeader( 'Cookie', $cookiesOption );
1497 foreach( $this->mVaryHeader
as $header => $option ) {
1498 $newheader = $header;
1499 if( is_array( $option ) ) {
1500 $newheader .= ';' . implode( ';', $option );
1502 $headers[] = $newheader;
1504 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1510 * bug 21672: Add Accept-Language to Vary and XVO headers
1511 * if there's no 'variant' parameter existed in GET.
1514 * /w/index.php?title=Main_page should always be served; but
1515 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1517 function addAcceptLanguage() {
1518 global $wgRequest, $wgContLang;
1519 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1520 $variants = $wgContLang->getVariants();
1521 $aloption = array();
1522 foreach ( $variants as $variant ) {
1523 if( $variant === $wgContLang->getCode() ) {
1526 $aloption[] = 'string-contains=' . $variant;
1528 // IE and some other browsers use another form of language code
1529 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1530 // We should handle these too.
1531 $ievariant = explode( '-', $variant );
1532 if ( count( $ievariant ) == 2 ) {
1533 $ievariant[1] = strtoupper( $ievariant[1] );
1534 $ievariant = implode( '-', $ievariant );
1535 $aloption[] = 'string-contains=' . $ievariant;
1539 $this->addVaryHeader( 'Accept-Language', $aloption );
1544 * Set a flag which will cause an X-Frame-Options header appropriate for
1545 * edit pages to be sent. The header value is controlled by
1546 * $wgEditPageFrameOptions.
1548 * This is the default for special pages. If you display a CSRF-protected
1549 * form on an ordinary view page, then you need to call this function.
1551 public function preventClickjacking( $enable = true ) {
1552 $this->mPreventClickjacking
= $enable;
1556 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1557 * This can be called from pages which do not contain any CSRF-protected
1560 public function allowClickjacking() {
1561 $this->mPreventClickjacking
= false;
1565 * Get the X-Frame-Options header value (without the name part), or false
1566 * if there isn't one. This is used by Skin to determine whether to enable
1567 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1569 public function getFrameOptions() {
1570 global $wgBreakFrames, $wgEditPageFrameOptions;
1571 if ( $wgBreakFrames ) {
1573 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1574 return $wgEditPageFrameOptions;
1579 * Send cache control HTTP headers
1581 public function sendCacheControl() {
1582 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1584 $response = $wgRequest->response();
1585 if ( $wgUseETag && $this->mETag
) {
1586 $response->header( "ETag: $this->mETag" );
1589 $this->addAcceptLanguage();
1591 # don't serve compressed data to clients who can't handle it
1592 # maintain different caches for logged-in users and non-logged in ones
1593 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1596 # Add an X-Vary-Options header for Squid with Wikimedia patches
1597 $response->header( $this->getXVO() );
1600 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1602 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1603 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1607 # We'll purge the proxy cache explicitly, but require end user agents
1608 # to revalidate against the proxy on each visit.
1609 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1610 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1611 # start with a shorter timeout for initial testing
1612 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1613 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1614 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1616 # We'll purge the proxy cache for anons explicitly, but require end user agents
1617 # to revalidate against the proxy on each visit.
1618 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1619 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1620 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1621 # start with a shorter timeout for initial testing
1622 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1623 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1626 # We do want clients to cache if they can, but they *must* check for updates
1627 # on revisiting the page.
1628 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1629 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1630 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1632 if($this->mLastModified
) {
1633 $response->header( "Last-Modified: {$this->mLastModified}" );
1636 wfDebug( __METHOD__
. ": no caching **\n", false );
1638 # In general, the absence of a last modified header should be enough to prevent
1639 # the client from using its cache. We send a few other things just to make sure.
1640 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1641 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1642 $response->header( 'Pragma: no-cache' );
1647 * Get the message associed with the HTTP response code $code
1649 * @param $code Integer: status code
1650 * @return String or null: message or null if $code is not in the list of
1653 public static function getStatusMessage( $code ) {
1654 static $statusMessage = array(
1656 101 => 'Switching Protocols',
1657 102 => 'Processing',
1661 203 => 'Non-Authoritative Information',
1662 204 => 'No Content',
1663 205 => 'Reset Content',
1664 206 => 'Partial Content',
1665 207 => 'Multi-Status',
1666 300 => 'Multiple Choices',
1667 301 => 'Moved Permanently',
1670 304 => 'Not Modified',
1672 307 => 'Temporary Redirect',
1673 400 => 'Bad Request',
1674 401 => 'Unauthorized',
1675 402 => 'Payment Required',
1678 405 => 'Method Not Allowed',
1679 406 => 'Not Acceptable',
1680 407 => 'Proxy Authentication Required',
1681 408 => 'Request Timeout',
1684 411 => 'Length Required',
1685 412 => 'Precondition Failed',
1686 413 => 'Request Entity Too Large',
1687 414 => 'Request-URI Too Large',
1688 415 => 'Unsupported Media Type',
1689 416 => 'Request Range Not Satisfiable',
1690 417 => 'Expectation Failed',
1691 422 => 'Unprocessable Entity',
1693 424 => 'Failed Dependency',
1694 500 => 'Internal Server Error',
1695 501 => 'Not Implemented',
1696 502 => 'Bad Gateway',
1697 503 => 'Service Unavailable',
1698 504 => 'Gateway Timeout',
1699 505 => 'HTTP Version Not Supported',
1700 507 => 'Insufficient Storage'
1702 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1706 * Finally, all the text has been munged and accumulated into
1707 * the object, let's actually output it:
1709 public function output() {
1710 global $wgUser, $wgOutputEncoding, $wgRequest;
1711 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1712 global $wgUseAjax, $wgAjaxWatch;
1713 global $wgEnableMWSuggest, $wgUniversalEditButton;
1715 if( $this->mDoNothing
) {
1718 wfProfileIn( __METHOD__
);
1719 if ( $this->mRedirect
!= '' ) {
1720 # Standards require redirect URLs to be absolute
1721 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1722 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1723 if( !$wgDebugRedirects ) {
1724 $message = self
::getStatusMessage( $this->mRedirectCode
);
1725 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1727 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1729 $this->sendCacheControl();
1731 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1732 if( $wgDebugRedirects ) {
1733 $url = htmlspecialchars( $this->mRedirect
);
1734 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1735 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1736 print "</body>\n</html>\n";
1738 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1740 wfProfileOut( __METHOD__
);
1742 } elseif ( $this->mStatusCode
) {
1743 $message = self
::getStatusMessage( $this->mStatusCode
);
1745 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1749 $sk = $wgUser->getSkin();
1751 // Add base resources
1752 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1754 // Add various resources if required
1756 $this->addModules( 'mediawiki.legacy.ajax' );
1758 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1760 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1761 $this->addModules( 'mediawiki.action.watch.ajax' );
1764 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1765 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1769 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1770 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1773 if( $wgUniversalEditButton ) {
1774 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1775 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1776 // Original UniversalEditButton
1777 $msg = wfMsg( 'edit' );
1778 $this->addLink( array(
1779 'rel' => 'alternate',
1780 'type' => 'application/x-wiki',
1782 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1784 // Alternate edit link
1785 $this->addLink( array(
1788 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1794 # Buffer output; final headers may depend on later processing
1797 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1798 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1800 // Prevent framing, if requested
1801 $frameOptions = $this->getFrameOptions();
1802 if ( $frameOptions ) {
1803 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1806 if ( $this->mArticleBodyOnly
) {
1807 $this->out( $this->mBodytext
);
1809 // Hook that allows last minute changes to the output page, e.g.
1810 // adding of CSS or Javascript by extensions.
1811 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1813 wfProfileIn( 'Output-skin' );
1814 $sk->outputPage( $this );
1815 wfProfileOut( 'Output-skin' );
1818 $this->sendCacheControl();
1820 wfProfileOut( __METHOD__
);
1824 * Actually output something with print(). Performs an iconv to the
1825 * output encoding, if needed.
1827 * @param $ins String: the string to output
1829 public function out( $ins ) {
1830 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1831 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1834 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1835 if ( false === $outs ) {
1843 * Produce a "user is blocked" page.
1845 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1848 function blockedPage( $return = true ) {
1849 global $wgUser, $wgContLang, $wgLang;
1851 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1852 $this->setRobotPolicy( 'noindex,nofollow' );
1853 $this->setArticleRelated( false );
1855 $name = User
::whoIs( $wgUser->blockedBy() );
1856 $reason = $wgUser->blockedFor();
1857 if( $reason == '' ) {
1858 $reason = wfMsg( 'blockednoreason' );
1860 $blockTimestamp = $wgLang->timeanddate(
1861 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1865 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1867 $blockid = $wgUser->mBlock
->mId
;
1869 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1870 if ( $blockExpiry == 'infinity' ) {
1871 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1872 // Search for localization in 'ipboptions'
1873 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1874 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1875 if ( strpos( $option, ':' ) === false ) {
1878 list( $show, $value ) = explode( ':', $option );
1879 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1880 $blockExpiry = $show;
1885 $blockExpiry = $wgLang->timeanddate(
1886 wfTimestamp( TS_MW
, $blockExpiry ),
1891 if ( $wgUser->mBlock
->mAuto
) {
1892 $msg = 'autoblockedtext';
1894 $msg = 'blockedtext';
1897 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1898 * This could be a username, an IP range, or a single IP. */
1899 $intended = $wgUser->mBlock
->mAddress
;
1902 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1903 $intended, $blockTimestamp
1906 # Don't auto-return to special pages
1908 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1909 $this->returnToMain( null, $return );
1914 * Output a standard error page
1916 * @param $title String: message key for page title
1917 * @param $msg String: message key for page text
1918 * @param $params Array: message parameters
1920 public function showErrorPage( $title, $msg, $params = array() ) {
1921 if ( $this->getTitle() ) {
1922 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1924 $this->setPageTitle( wfMsg( $title ) );
1925 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1926 $this->setRobotPolicy( 'noindex,nofollow' );
1927 $this->setArticleRelated( false );
1928 $this->enableClientCache( false );
1929 $this->mRedirect
= '';
1930 $this->mBodytext
= '';
1932 $this->addWikiMsgArray( $msg, $params );
1934 $this->returnToMain();
1938 * Output a standard permission error page
1940 * @param $errors Array: error message keys
1941 * @param $action String: action that was denied or null if unknown
1943 public function showPermissionsErrorPage( $errors, $action = null ) {
1944 $this->mDebugtext
.= 'Original title: ' .
1945 $this->getTitle()->getPrefixedText() . "\n";
1946 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1947 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1948 $this->setRobotPolicy( 'noindex,nofollow' );
1949 $this->setArticleRelated( false );
1950 $this->enableClientCache( false );
1951 $this->mRedirect
= '';
1952 $this->mBodytext
= '';
1953 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1957 * Display an error page indicating that a given version of MediaWiki is
1958 * required to use it
1960 * @param $version Mixed: the version of MediaWiki needed to use the page
1962 public function versionRequired( $version ) {
1963 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1964 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1965 $this->setRobotPolicy( 'noindex,nofollow' );
1966 $this->setArticleRelated( false );
1967 $this->mBodytext
= '';
1969 $this->addWikiMsg( 'versionrequiredtext', $version );
1970 $this->returnToMain();
1974 * Display an error page noting that a given permission bit is required.
1976 * @param $permission String: key required
1978 public function permissionRequired( $permission ) {
1981 $this->setPageTitle( wfMsg( 'badaccess' ) );
1982 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1983 $this->setRobotPolicy( 'noindex,nofollow' );
1984 $this->setArticleRelated( false );
1985 $this->mBodytext
= '';
1987 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1988 User
::getGroupsWithPermission( $permission ) );
1992 $wgLang->commaList( $groups ),
1996 $this->addWikiMsg( 'badaccess-group0' );
1998 $this->returnToMain();
2002 * Produce the stock "please login to use the wiki" page
2004 public function loginToUse() {
2007 if( $wgUser->isLoggedIn() ) {
2008 $this->permissionRequired( 'read' );
2012 $skin = $wgUser->getSkin();
2014 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2015 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2016 $this->setRobotPolicy( 'noindex,nofollow' );
2017 $this->setArticleRelated( false );
2019 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2020 $loginLink = $skin->link(
2022 wfMsgHtml( 'loginreqlink' ),
2024 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2025 array( 'known', 'noclasses' )
2027 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
2028 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2030 # Don't return to the main page if the user can't read it
2031 # otherwise we'll end up in a pointless loop
2032 $mainPage = Title
::newMainPage();
2033 if( $mainPage->userCanRead() ) {
2034 $this->returnToMain( null, $mainPage );
2039 * Format a list of error messages
2041 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
2042 * @param $action String: action that was denied or null if unknown
2043 * @return String: the wikitext error-messages, formatted into a list.
2045 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2046 if ( $action == null ) {
2047 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2049 $action_desc = wfMsgNoTrans( "action-$action" );
2050 $text = wfMsgNoTrans(
2051 'permissionserrorstext-withaction',
2057 if ( count( $errors ) > 1 ) {
2058 $text .= '<ul class="permissions-errors">' . "\n";
2060 foreach( $errors as $error ) {
2062 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2067 $text .= "<div class=\"permissions-errors\">\n" .
2068 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2076 * Display a page stating that the Wiki is in read-only mode,
2077 * and optionally show the source of the page that the user
2078 * was trying to edit. Should only be called (for this
2079 * purpose) after wfReadOnly() has returned true.
2081 * For historical reasons, this function is _also_ used to
2082 * show the error message when a user tries to edit a page
2083 * they are not allowed to edit. (Unless it's because they're
2084 * blocked, then we show blockedPage() instead.) In this
2085 * case, the second parameter should be set to true and a list
2086 * of reasons supplied as the third parameter.
2088 * @todo Needs to be split into multiple functions.
2090 * @param $source String: source code to show (or null).
2091 * @param $protected Boolean: is this a permissions error?
2092 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2093 * @param $action String: action that was denied or null if unknown
2095 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2097 $skin = $wgUser->getSkin();
2099 $this->setRobotPolicy( 'noindex,nofollow' );
2100 $this->setArticleRelated( false );
2102 // If no reason is given, just supply a default "I can't let you do
2103 // that, Dave" message. Should only occur if called by legacy code.
2104 if ( $protected && empty( $reasons ) ) {
2105 $reasons[] = array( 'badaccess-group0' );
2108 if ( !empty( $reasons ) ) {
2109 // Permissions error
2111 $this->setPageTitle( wfMsg( 'viewsource' ) );
2113 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2116 $this->setPageTitle( wfMsg( 'badaccess' ) );
2118 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2120 // Wiki is read only
2121 $this->setPageTitle( wfMsg( 'readonly' ) );
2122 $reason = wfReadOnlyReason();
2123 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2126 // Show source, if supplied
2127 if( is_string( $source ) ) {
2128 $this->addWikiMsg( 'viewsourcetext' );
2131 'id' => 'wpTextbox1',
2132 'name' => 'wpTextbox1',
2133 'cols' => $wgUser->getOption( 'cols' ),
2134 'rows' => $wgUser->getOption( 'rows' ),
2135 'readonly' => 'readonly'
2137 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2139 // Show templates used by this article
2140 $skin = $wgUser->getSkin();
2141 $article = new Article( $this->getTitle() );
2142 $this->addHTML( "<div class='templatesUsed'>
2143 {$skin->formatTemplates( $article->getUsedTemplates() )}
2148 # If the title doesn't exist, it's fairly pointless to print a return
2149 # link to it. After all, you just tried editing it and couldn't, so
2150 # what's there to do there?
2151 if( $this->getTitle()->exists() ) {
2152 $this->returnToMain( null, $this->getTitle() );
2157 * Adds JS-based password security checker
2158 * @param $passwordId String ID of input box containing password
2159 * @param $retypeId String ID of input box containing retyped password
2162 public function addPasswordSecurity( $passwordId, $retypeId ) {
2164 'password' => '#' . $passwordId,
2165 'retype' => '#' . $retypeId,
2166 'messages' => array(),
2168 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2169 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2171 $data['messages'][$message] = wfMsg( $message );
2173 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2174 $this->addModules( 'mediawiki.legacy.password' );
2177 public function showFatalError( $message ) {
2178 $this->setPageTitle( wfMsg( 'internalerror' ) );
2179 $this->setRobotPolicy( 'noindex,nofollow' );
2180 $this->setArticleRelated( false );
2181 $this->enableClientCache( false );
2182 $this->mRedirect
= '';
2183 $this->mBodytext
= $message;
2186 public function showUnexpectedValueError( $name, $val ) {
2187 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2190 public function showFileCopyError( $old, $new ) {
2191 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2194 public function showFileRenameError( $old, $new ) {
2195 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2198 public function showFileDeleteError( $name ) {
2199 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2202 public function showFileNotFoundError( $name ) {
2203 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2207 * Add a "return to" link pointing to a specified title
2209 * @param $title Title to link
2210 * @param $query String: query string
2211 * @param $text String text of the link (input is not escaped)
2213 public function addReturnTo( $title, $query = array(), $text = null ) {
2215 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2218 $wgUser->getSkin()->link( $title, $text, array(), $query )
2220 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2224 * Add a "return to" link pointing to a specified title,
2225 * or the title indicated in the request, or else the main page
2227 * @param $unused No longer used
2228 * @param $returnto Title or String to return to
2229 * @param $returntoquery String: query string for the return to link
2231 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2234 if ( $returnto == null ) {
2235 $returnto = $wgRequest->getText( 'returnto' );
2238 if ( $returntoquery == null ) {
2239 $returntoquery = $wgRequest->getText( 'returntoquery' );
2242 if ( $returnto === '' ) {
2243 $returnto = Title
::newMainPage();
2246 if ( is_object( $returnto ) ) {
2247 $titleObj = $returnto;
2249 $titleObj = Title
::newFromText( $returnto );
2251 if ( !is_object( $titleObj ) ) {
2252 $titleObj = Title
::newMainPage();
2255 $this->addReturnTo( $titleObj, $returntoquery );
2259 * @param $sk Skin The given Skin
2260 * @param $includeStyle Boolean: unused
2261 * @return String: The doctype, opening <html>, and head element.
2263 public function headElement( Skin
$sk, $includeStyle = true ) {
2264 global $wgOutputEncoding, $wgMimeType;
2265 global $wgUseTrackbacks, $wgHtml5;
2266 global $wgUser, $wgRequest, $wgLang;
2268 if ( $sk->commonPrintStylesheet() ) {
2269 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2271 $sk->setupUserCss( $this );
2273 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2275 if ( $this->getHTMLTitle() == '' ) {
2276 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2279 $openHead = Html
::openElement( 'head' );
2281 # Don't bother with the newline if $head == ''
2282 $ret .= "$openHead\n";
2286 # More succinct than <meta http-equiv=Content-Type>, has the
2288 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2290 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2293 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2295 $ret .= implode( "\n", array(
2296 $this->getHeadLinks( $sk ),
2297 $this->buildCssLinks( $sk ),
2298 $this->getHeadItems()
2301 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2302 $ret .= $this->getTitle()->trackbackRDF();
2305 $closeHead = Html
::closeElement( 'head' );
2307 $ret .= "$closeHead\n";
2310 $bodyAttrs = array();
2312 # Crazy edit-on-double-click stuff
2313 $action = $wgRequest->getVal( 'action', 'view' );
2316 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2317 !in_array( $action, array( 'edit', 'submit' ) ) &&
2318 $wgUser->getOption( 'editondblclick' )
2321 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2325 $dir = wfUILang()->getDir();
2326 $bodyAttrs['class'] = "mediawiki $dir";
2328 if ( $wgLang->capitalizeAllNouns() ) {
2329 # A <body> class is probably not the best way to do this . . .
2330 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2332 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2333 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2334 $bodyAttrs['class'] .= ' ns-special';
2335 } elseif ( $this->getTitle()->isTalkPage() ) {
2336 $bodyAttrs['class'] .= ' ns-talk';
2338 $bodyAttrs['class'] .= ' ns-subject';
2340 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2341 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2343 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2344 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2346 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2352 * Get a ResourceLoader object associated with this OutputPage
2354 public function getResourceLoader() {
2355 if ( is_null( $this->mResourceLoader
) ) {
2356 $this->mResourceLoader
= new ResourceLoader();
2358 return $this->mResourceLoader
;
2364 * @param $modules Array/string with the module name
2365 * @param $only string May be styles, messages or scripts
2366 * @param $useESI boolean
2367 * @return string html <script> and <style> tags
2369 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2370 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2371 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2372 // Lazy-load ResourceLoader
2373 // TODO: Should this be a static function of ResourceLoader instead?
2374 // TODO: Divide off modules starting with "user", and add the user parameter to them
2376 'lang' => $wgLang->getCode(),
2377 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2378 'skin' => $skin->getSkinName(),
2381 // Propagate printable and handheld parameters if present
2382 if ( $wgRequest->getBool( 'printable' ) ) {
2383 $query['printable'] = 1;
2385 if ( $wgRequest->getBool( 'handheld' ) ) {
2386 $query['handheld'] = 1;
2389 if ( !count( $modules ) ) {
2393 if ( count( $modules ) > 1 ) {
2394 // Remove duplicate module requests
2395 $modules = array_unique( (array) $modules );
2396 // Sort module names so requests are more uniform
2399 if ( ResourceLoader
::inDebugMode() ) {
2400 // Recursively call us for every item
2402 foreach ( $modules as $name ) {
2403 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2409 // Create keyed-by-group list of module objects from modules list
2411 $resourceLoader = $this->getResourceLoader();
2412 foreach ( (array) $modules as $name ) {
2413 $module = $resourceLoader->getModule( $name );
2414 $group = $module->getGroup();
2415 if ( !isset( $groups[$group] ) ) {
2416 $groups[$group] = array();
2418 $groups[$group][$name] = $module;
2421 foreach ( $groups as $group => $modules ) {
2422 $query['modules'] = implode( '|', array_keys( $modules ) );
2423 // Special handling for user-specific groups
2424 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2425 $query['user'] = $wgUser->getName();
2427 // Support inlining of private modules if configured as such
2428 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2429 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2430 if ( $only == 'styles' ) {
2431 $links .= Html
::inlineStyle(
2432 $resourceLoader->makeModuleResponse( $context, $modules )
2435 $links .= Html
::inlineScript(
2436 ResourceLoader
::makeLoaderConditionalScript(
2437 $resourceLoader->makeModuleResponse( $context, $modules )
2443 // Special handling for user and site groups; because users might change their stuff
2444 // on-wiki like site or user pages, or user preferences; we need to find the highest
2445 // timestamp of these user-changable modules so we can ensure cache misses on change
2446 if ( $group === 'user' ||
$group === 'site' ) {
2447 // Create a fake request based on the one we are about to make so modules return
2449 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2450 // Get the maximum timestamp
2452 foreach ( $modules as $module ) {
2453 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2455 // Add a version parameter so cache will break when things change
2456 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, round( $timestamp, -2 ) );
2458 // Make queries uniform in order
2461 $url = wfAppendQuery( $wgLoadScript, $query );
2462 if ( $useESI && $wgResourceLoaderUseESI ) {
2463 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2464 if ( $only == 'styles' ) {
2465 $links .= Html
::inlineStyle( $esi );
2467 $links .= Html
::inlineScript( $esi );
2470 // Automatically select style/script elements
2471 if ( $only === 'styles' ) {
2472 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2474 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2482 * Gets the global variables and mScripts; also adds userjs to the end if
2483 * enabled. Despite the name, these scripts are no longer put in the
2484 * <head> but at the bottom of the <body>
2486 * @param $sk Skin object to use
2487 * @return String: HTML fragment
2489 function getHeadScripts( Skin
$sk ) {
2490 global $wgUser, $wgRequest, $wgUseSiteJs;
2492 // Startup - this will immediately load jquery and mediawiki modules
2493 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2495 // Configuration -- This could be merged together with the load and go, but
2496 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2497 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2499 // Script and Messages "only" requests
2500 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2501 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2503 // Modules requests - let the client calculate dependencies and batch requests as it likes
2504 if ( $this->getModules() ) {
2505 $scripts .= Html
::inlineScript(
2506 ResourceLoader
::makeLoaderConditionalScript(
2507 Xml
::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2508 Xml
::encodeJsCall( 'mediaWiki.loader.go', array() )
2514 $scripts .= "\n" . $this->mScripts
;
2516 // Add site JS if enabled
2517 if ( $wgUseSiteJs ) {
2518 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2521 // Add user JS if enabled - trying to load user.options as a bundle if possible
2522 $userOptionsAdded = false;
2523 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2524 $action = $wgRequest->getVal( 'action', 'view' );
2525 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2526 # XXX: additional security check/prompt?
2527 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2529 $scripts .= $this->makeResourceLoaderLink(
2530 $sk, array( 'user', 'user.options' ), 'scripts'
2532 $userOptionsAdded = true;
2535 if ( !$userOptionsAdded ) {
2536 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2543 * Add default \<meta\> tags
2545 protected function addDefaultMeta() {
2546 global $wgVersion, $wgHtml5;
2548 static $called = false;
2550 # Don't run this twice
2556 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2558 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2560 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2561 if( $p !== 'index,follow' ) {
2562 // http://www.robotstxt.org/wc/meta-user.html
2563 // Only show if it's different from the default robots policy
2564 $this->addMeta( 'robots', $p );
2567 if ( count( $this->mKeywords
) > 0 ) {
2569 "/<.*?" . ">/" => '',
2575 array_keys( $strip ),
2576 array_values( $strip ),
2577 implode( ',', $this->mKeywords
)
2584 * @return string HTML tag links to be put in the header.
2586 public function getHeadLinks( Skin
$sk ) {
2589 // Ideally this should happen earlier, somewhere. :P
2590 $this->addDefaultMeta();
2594 foreach ( $this->mMetatags
as $tag ) {
2595 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2597 $tag[0] = substr( $tag[0], 5 );
2601 $tags[] = Html
::element( 'meta',
2604 'content' => $tag[1]
2608 foreach ( $this->mLinktags
as $tag ) {
2609 $tags[] = Html
::element( 'link', $tag );
2613 foreach( $this->getSyndicationLinks() as $format => $link ) {
2614 # Use the page name for the title (accessed through $wgTitle since
2615 # there's no other way). In principle, this could lead to issues
2616 # with having the same name for different feeds corresponding to
2617 # the same page, but we can't avoid that at this low a level.
2619 $tags[] = $this->feedLink(
2622 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2623 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2627 # Recent changes feed should appear on every page (except recentchanges,
2628 # that would be redundant). Put it after the per-page feed to avoid
2629 # changing existing behavior. It's still available, probably via a
2630 # menu in your browser. Some sites might have a different feed they'd
2631 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2632 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2633 # If so, use it instead.
2635 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2636 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2638 if ( $wgOverrideSiteFeed ) {
2639 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2640 $tags[] = $this->feedLink(
2642 htmlspecialchars( $feedUrl ),
2643 wfMsg( "site-{$type}-feed", $wgSitename )
2646 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2647 foreach ( $wgAdvertisedFeedTypes as $format ) {
2648 $tags[] = $this->feedLink(
2650 $rctitle->getLocalURL( "feed={$format}" ),
2651 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2656 return implode( "\n", $tags );
2660 * Generate a <link rel/> for a feed.
2662 * @param $type String: feed type
2663 * @param $url String: URL to the feed
2664 * @param $text String: value of the "title" attribute
2665 * @return String: HTML fragment
2667 private function feedLink( $type, $url, $text ) {
2668 return Html
::element( 'link', array(
2669 'rel' => 'alternate',
2670 'type' => "application/$type+xml",
2677 * Add a local or specified stylesheet, with the given media options.
2678 * Meant primarily for internal use...
2680 * @param $style String: URL to the file
2681 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2682 * @param $condition String: for IE conditional comments, specifying an IE version
2683 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2685 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2687 // Even though we expect the media type to be lowercase, but here we
2688 // force it to lowercase to be safe.
2690 $options['media'] = $media;
2693 $options['condition'] = $condition;
2696 $options['dir'] = $dir;
2698 $this->styles
[$style] = $options;
2702 * Adds inline CSS styles
2703 * @param $style_css Mixed: inline CSS
2705 public function addInlineStyle( $style_css ){
2706 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2710 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2711 * These will be applied to various media & IE conditionals.
2712 * @param $sk Skin object
2714 public function buildCssLinks( $sk ) {
2716 // Add ResourceLoader styles
2717 // Split the styles into three groups
2718 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2719 $resourceLoader = $this->getResourceLoader();
2720 foreach ( $this->getModuleStyles() as $name ) {
2721 $group = $resourceLoader->getModule( $name )->getGroup();
2722 // Modules in groups named "other" or anything different than "user" or "site" will
2723 // be placed in the "other" group
2724 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2727 // We want site and user styles to override dynamically added styles from modules, but we want
2728 // dynamically added styles to override statically added styles from other modules. So the order
2729 // has to be other, dynamic, site, user
2730 // Add statically added styles for other modules
2731 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2732 // Add normal styles added through addStyle()/addInlineStyle() here
2733 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2734 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2735 // We use a <meta> tag with a made-up name for this because that's valid HTML
2736 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2737 // Add site and user styles
2738 $ret .= $this->makeResourceLoaderLink(
2739 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2744 public function buildCssLinksArray() {
2746 foreach( $this->styles
as $file => $options ) {
2747 $link = $this->styleLink( $file, $options );
2749 $links[$file] = $link;
2756 * Generate \<link\> tags for stylesheets
2758 * @param $style String: URL to the file
2759 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2761 * @return String: HTML fragment
2763 protected function styleLink( $style, $options ) {
2764 if( isset( $options['dir'] ) ) {
2765 $siteDir = wfUILang()->getDir();
2766 if( $siteDir != $options['dir'] ) {
2771 if( isset( $options['media'] ) ) {
2772 $media = self
::transformCssMedia( $options['media'] );
2773 if( is_null( $media ) ) {
2780 if( substr( $style, 0, 1 ) == '/' ||
2781 substr( $style, 0, 5 ) == 'http:' ||
2782 substr( $style, 0, 6 ) == 'https:' ) {
2785 global $wgStylePath, $wgStyleVersion;
2786 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2789 $link = Html
::linkedStyle( $url, $media );
2791 if( isset( $options['condition'] ) ) {
2792 $condition = htmlspecialchars( $options['condition'] );
2793 $link = "<!--[if $condition]>$link<![endif]-->";
2799 * Transform "media" attribute based on request parameters
2801 * @param $media String: current value of the "media" attribute
2802 * @return String: modified value of the "media" attribute
2804 public static function transformCssMedia( $media ) {
2805 global $wgRequest, $wgHandheldForIPhone;
2807 // Switch in on-screen display for media testing
2809 'printable' => 'print',
2810 'handheld' => 'handheld',
2812 foreach( $switches as $switch => $targetMedia ) {
2813 if( $wgRequest->getBool( $switch ) ) {
2814 if( $media == $targetMedia ) {
2816 } elseif( $media == 'screen' ) {
2822 // Expand longer media queries as iPhone doesn't grok 'handheld'
2823 if( $wgHandheldForIPhone ) {
2824 $mediaAliases = array(
2825 'screen' => 'screen and (min-device-width: 481px)',
2826 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2829 if( isset( $mediaAliases[$media] ) ) {
2830 $media = $mediaAliases[$media];
2838 * Turn off regular page output and return an error reponse
2839 * for when rate limiting has triggered.
2841 public function rateLimited() {
2842 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2843 $this->setRobotPolicy( 'noindex,follow' );
2844 $this->setArticleRelated( false );
2845 $this->enableClientCache( false );
2846 $this->mRedirect
= '';
2848 $this->setStatusCode( 503 );
2849 $this->addWikiMsg( 'actionthrottledtext' );
2851 $this->returnToMain( null, $this->getTitle() );
2855 * Show a warning about slave lag
2857 * If the lag is higher than $wgSlaveLagCritical seconds,
2858 * then the warning is a bit more obvious. If the lag is
2859 * lower than $wgSlaveLagWarning, then no warning is shown.
2861 * @param $lag Integer: slave lag
2863 public function showLagWarning( $lag ) {
2864 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2865 if( $lag >= $wgSlaveLagWarning ) {
2866 $message = $lag < $wgSlaveLagCritical
2869 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2870 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2875 * Add a wikitext-formatted message to the output.
2876 * This is equivalent to:
2878 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2880 public function addWikiMsg( /*...*/ ) {
2881 $args = func_get_args();
2882 $name = array_shift( $args );
2883 $this->addWikiMsgArray( $name, $args );
2887 * Add a wikitext-formatted message to the output.
2888 * Like addWikiMsg() except the parameters are taken as an array
2889 * instead of a variable argument list.
2891 * $options is passed through to wfMsgExt(), see that function for details.
2893 public function addWikiMsgArray( $name, $args, $options = array() ) {
2894 $options[] = 'parse';
2895 $text = wfMsgExt( $name, $options, $args );
2896 $this->addHTML( $text );
2900 * This function takes a number of message/argument specifications, wraps them in
2901 * some overall structure, and then parses the result and adds it to the output.
2903 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2904 * on. The subsequent arguments may either be strings, in which case they are the
2905 * message names, or arrays, in which case the first element is the message name,
2906 * and subsequent elements are the parameters to that message.
2908 * The special named parameter 'options' in a message specification array is passed
2909 * through to the $options parameter of wfMsgExt().
2911 * Don't use this for messages that are not in users interface language.
2915 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2919 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2921 * The newline after opening div is needed in some wikitext. See bug 19226.
2923 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2924 $msgSpecs = func_get_args();
2925 array_shift( $msgSpecs );
2926 $msgSpecs = array_values( $msgSpecs );
2928 foreach ( $msgSpecs as $n => $spec ) {
2930 if ( is_array( $spec ) ) {
2932 $name = array_shift( $args );
2933 if ( isset( $args['options'] ) ) {
2934 $options = $args['options'];
2935 unset( $args['options'] );
2941 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2943 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2947 * Include jQuery core. Use this to avoid loading it multiple times
2948 * before we get a usable script loader.
2950 * @param $modules Array: list of jQuery modules which should be loaded
2951 * @return Array: the list of modules which were not loaded.
2953 * @deprecated @since 1.17
2955 public function includeJQuery( $modules = array() ) {