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'
70 // mLastModified and mEtag are used for sending cache control.
71 // The whole caching system should probably be moved in its own class.
72 var $mLastModified = '';
75 * Should be private. No getter but used in sendCacheControl();
76 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
77 * as a unique identifier for the content. It is later used by the client
78 * to compare its cache version with the server version. Client sends
79 * headers If-Match and If-None-Match containing its local cache ETAG value.
81 * To get more information, you will have to look at HTTP1/1 protocols which
82 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
86 var $mCategoryLinks = array();
87 var $mCategories = array();
89 // Should be private. Associative array mapping language code to the page name
90 var $mLanguageLinks = array();
93 * Should be private. Used for javascript (or VB?)
94 * We should split js / css.
95 * mScripts content is inserted as is in <head> by Skin. This might contains
96 * either a link to a stylesheet or inline css.
99 var $mInlineStyles = ''; // ???
105 * Used by skin template.
106 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
108 var $mPageLinkTitle = '';
110 // Array of <head> elements. Parser might add its own headers!
111 var $mHeadItems = array();
113 // Next variables probably comes from the ressource loader @todo FIXME
114 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
115 var $mResourceLoader;
117 /** @fixme is this still used ?*/
118 var $mInlineMsg = array();
120 var $mTemplateIds = array();
122 // Initialized with a global value. Let us override it.
123 // Should probably get deleted / rewritten ...
127 * This was for the old skins and for users with 640x480 screen.
128 * Please note old sckins are still used and might prove useful for
129 * users having old computers or visually impaired.
131 var $mSuppressQuickbar = false;
134 * @EasterEgg I just love the name for this self documenting variable.
137 var $mDoNothing = false;
140 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
143 * should be private. Has get/set methods properly documented.
144 * Stores "article flag" toggle.
146 var $mIsArticleRelated = true;
148 // lazy initialised, use parserOptions()
149 protected $mParserOptions = null;
152 * Handles the atom / rss links.
153 * We probably only support atom in 2011.
154 * Looks like a private variable.
156 var $mFeedLinks = array();
158 // Gwicke work on squid caching? Roughly from 2003.
159 var $mEnableClientCache = true;
162 * Flag if output should only contain the body of the article.
165 var $mArticleBodyOnly = false;
167 var $mNewSectionLink = false;
168 var $mHideNewSectionLink = false;
171 * Comes from the parser. This was probably made to laod CSS/JS only
172 * if we had <gallery>. Used directly in CategoryPage.php
173 * Looks like resource loader can replace this.
175 var $mNoGallery = false;
177 // should be private.
178 var $mPageTitleActionText = '';
179 var $mParseWarnings = array();
181 // Cache stuff. Looks like mEnableClientCache
182 var $mSquidMaxage = 0;
185 var $mPreventClickjacking = true;
187 // should be private. To include the variable {{REVISIONID}}
188 var $mRevisionId = null;
190 // Stores a Title object.
191 protected $mTitle = null;
194 * An array of stylesheet filenames (relative from skins path), with options
195 * for CSS media, IE conditions, and RTL/LTR direction.
196 * For internal use; add settings in the skin via $this->addStyle()
198 * Style again! This seems like a code duplication since we already have
199 * mStyles. This is what makes OpenSource amazing.
201 var $styles = array();
204 * Whether to load jQuery core.
206 protected $mJQueryDone = false;
208 private $mIndexPolicy = 'index';
209 private $mFollowPolicy = 'follow';
210 private $mVaryHeader = array(
211 'Accept-Encoding' => array( 'list-contains=gzip' ),
217 * Initialise private variables
219 function __construct() {
220 global $wgAllowUserJs;
221 $this->mAllowUserJs
= $wgAllowUserJs;
225 * Redirect to $url rather than displaying the normal page
227 * @param $url String: URL
228 * @param $responsecode String: HTTP status code
230 public function redirect( $url, $responsecode = '302' ) {
231 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
232 $this->mRedirect
= str_replace( "\n", '', $url );
233 $this->mRedirectCode
= $responsecode;
237 * Get the URL to redirect to, or an empty string if not redirect URL set
241 public function getRedirect() {
242 return $this->mRedirect
;
246 * Set the HTTP status code to send with the output.
248 * @param $statusCode Integer
251 public function setStatusCode( $statusCode ) {
252 $this->mStatusCode
= $statusCode;
256 * Add a new <meta> tag
257 * To add an http-equiv meta tag, precede the name with "http:"
259 * @param $name tag name
260 * @param $val tag value
262 function addMeta( $name, $val ) {
263 array_push( $this->mMetatags
, array( $name, $val ) );
267 * Add a keyword or a list of keywords in the page header
269 * @param $text String or array of strings
271 function addKeyword( $text ) {
272 if( is_array( $text ) ) {
273 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
275 array_push( $this->mKeywords
, $text );
280 * Add a new \<link\> tag to the page header
282 * @param $linkarr Array: associative array of attributes.
284 function addLink( $linkarr ) {
285 array_push( $this->mLinktags
, $linkarr );
289 * Add a new \<link\> with "rel" attribute set to "meta"
291 * @param $linkarr Array: associative array mapping attribute names to their
292 * values, both keys and values will be escaped, and the
293 * "rel" attribute will be automatically added
295 function addMetadataLink( $linkarr ) {
296 # note: buggy CC software only reads first "meta" link
297 static $haveMeta = false;
298 $linkarr['rel'] = $haveMeta ?
'alternate meta' : 'meta';
299 $this->addLink( $linkarr );
304 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
306 * @param $script String: raw HTML
308 function addScript( $script ) {
309 $this->mScripts
.= $script . "\n";
313 * Register and add a stylesheet from an extension directory.
315 * @param $url String path to sheet. Provide either a full url (beginning
316 * with 'http', etc) or a relative path from the document root
317 * (beginning with '/'). Otherwise it behaves identically to
318 * addStyle() and draws from the /skins folder.
320 public function addExtensionStyle( $url ) {
321 array_push( $this->mExtStyles
, $url );
325 * Get all links added by extensions
329 function getExtStyle() {
330 return $this->mExtStyles
;
334 * Add a JavaScript file out of skins/common, or a given relative path.
336 * @param $file String: filename in skins/common or complete on-server path
338 * @param $version String: style version of the file. Defaults to $wgStyleVersion
340 public function addScriptFile( $file, $version = null ) {
341 global $wgStylePath, $wgStyleVersion;
342 // See if $file parameter is an absolute URL or begins with a slash
343 if( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
346 $path = "{$wgStylePath}/common/{$file}";
348 if ( is_null( $version ) )
349 $version = $wgStyleVersion;
350 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
354 * Add a self-contained script tag with the given contents
356 * @param $script String: JavaScript text, no <script> tags
358 public function addInlineScript( $script ) {
359 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
363 * Get all registered JS and CSS tags for the header.
367 function getScript() {
368 return $this->mScripts
. $this->getHeadItems();
372 * Get the list of modules to include on this page
374 * @return Array of module names
376 public function getModules() {
377 return array_values( array_unique( $this->mModules
) );
381 * Add one or more modules recognized by the resource loader. Modules added
382 * through this function will be loaded by the resource loader when the
385 * @param $modules Mixed: module name (string) or array of module names
387 public function addModules( $modules ) {
388 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
392 * Get the list of module JS to include on this page
393 * @return array of module names
395 public function getModuleScripts() {
396 return array_values( array_unique( $this->mModuleScripts
) );
400 * Add only JS of one or more modules recognized by the resource loader. Module
401 * scripts added through this function will be loaded by the resource loader when
404 * @param $modules Mixed: module name (string) or array of module names
406 public function addModuleScripts( $modules ) {
407 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
411 * Get the list of module CSS to include on this page
413 * @return Array of module names
415 public function getModuleStyles() {
416 return array_values( array_unique( $this->mModuleStyles
) );
420 * Add only CSS of one or more modules recognized by the resource loader. Module
421 * styles added through this function will be loaded by the resource loader when
424 * @param $modules Mixed: module name (string) or array of module names
426 public function addModuleStyles( $modules ) {
427 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
431 * Get the list of module messages to include on this page
433 * @return Array of module names
435 public function getModuleMessages() {
436 return array_values( array_unique( $this->mModuleMessages
) );
440 * Add only messages of one or more modules recognized by the resource loader.
441 * Module messages added through this function will be loaded by the resource
442 * loader when the page loads.
444 * @param $modules Mixed: module name (string) or array of module names
446 public function addModuleMessages( $modules ) {
447 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
451 * Get all header items in a string
455 function getHeadItems() {
457 foreach ( $this->mHeadItems
as $item ) {
464 * Add or replace an header item to the output
466 * @param $name String: item name
467 * @param $value String: raw HTML
469 public function addHeadItem( $name, $value ) {
470 $this->mHeadItems
[$name] = $value;
474 * Check if the header item $name is already set
476 * @param $name String: item name
479 public function hasHeadItem( $name ) {
480 return isset( $this->mHeadItems
[$name] );
484 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
486 * @param $tag String: value of "ETag" header
488 function setETag( $tag ) {
493 * Set whether the output should only contain the body of the article,
494 * without any skin, sidebar, etc.
495 * Used e.g. when calling with "action=render".
497 * @param $only Boolean: whether to output only the body of the article
499 public function setArticleBodyOnly( $only ) {
500 $this->mArticleBodyOnly
= $only;
504 * Return whether the output will contain only the body of the article
508 public function getArticleBodyOnly() {
509 return $this->mArticleBodyOnly
;
513 * checkLastModified tells the client to use the client-cached page if
514 * possible. If sucessful, the OutputPage is disabled so that
515 * any future call to OutputPage->output() have no effect.
517 * Side effect: sets mLastModified for Last-Modified header
519 * @return Boolean: true iff cache-ok headers was sent.
521 public function checkLastModified( $timestamp ) {
522 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
524 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
525 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
528 if( !$wgCachePages ) {
529 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
532 if( $wgUser->getOption( 'nocache' ) ) {
533 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
537 $timestamp = wfTimestamp( TS_MW
, $timestamp );
538 $modifiedTimes = array(
539 'page' => $timestamp,
540 'user' => $wgUser->getTouched(),
541 'epoch' => $wgCacheEpoch
543 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
545 $maxModified = max( $modifiedTimes );
546 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
548 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
549 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
555 foreach ( $modifiedTimes as $name => $value ) {
556 if ( $info !== '' ) {
559 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
562 # IE sends sizes after the date like this:
563 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
564 # this breaks strtotime().
565 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
567 wfSuppressWarnings(); // E_STRICT system time bitching
568 $clientHeaderTime = strtotime( $clientHeader );
570 if ( !$clientHeaderTime ) {
571 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
574 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
576 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
577 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
578 wfDebug( __METHOD__
. ": effective Last-Modified: " .
579 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
580 if( $clientHeaderTime < $maxModified ) {
581 wfDebug( __METHOD__
. ": STALE, $info\n", false );
586 # Give a 304 response code and disable body output
587 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
588 ini_set( 'zlib.output_compression', 0 );
589 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
590 $this->sendCacheControl();
593 // Don't output a compressed blob when using ob_gzhandler;
594 // it's technically against HTTP spec and seems to confuse
595 // Firefox when the response gets split over two packets.
596 wfClearOutputBuffers();
602 * Override the last modified timestamp
604 * @param $timestamp String: new timestamp, in a format readable by
607 public function setLastModified( $timestamp ) {
608 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
612 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
614 * @param $policy String: the literal string to output as the contents of
615 * the meta tag. Will be parsed according to the spec and output in
619 public function setRobotPolicy( $policy ) {
620 $policy = Article
::formatRobotPolicy( $policy );
622 if( isset( $policy['index'] ) ) {
623 $this->setIndexPolicy( $policy['index'] );
625 if( isset( $policy['follow'] ) ) {
626 $this->setFollowPolicy( $policy['follow'] );
631 * Set the index policy for the page, but leave the follow policy un-
634 * @param $policy string Either 'index' or 'noindex'.
637 public function setIndexPolicy( $policy ) {
638 $policy = trim( $policy );
639 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
640 $this->mIndexPolicy
= $policy;
645 * Set the follow policy for the page, but leave the index policy un-
648 * @param $policy String: either 'follow' or 'nofollow'.
651 public function setFollowPolicy( $policy ) {
652 $policy = trim( $policy );
653 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
654 $this->mFollowPolicy
= $policy;
659 * Set the new value of the "action text", this will be added to the
660 * "HTML title", separated from it with " - ".
662 * @param $text String: new value of the "action text"
664 public function setPageTitleActionText( $text ) {
665 $this->mPageTitleActionText
= $text;
669 * Get the value of the "action text"
673 public function getPageTitleActionText() {
674 if ( isset( $this->mPageTitleActionText
) ) {
675 return $this->mPageTitleActionText
;
680 * "HTML title" means the contents of <title>.
681 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
683 public function setHTMLTitle( $name ) {
684 $this->mHTMLtitle
= $name;
688 * Return the "HTML title", i.e. the content of the <title> tag.
692 public function getHTMLTitle() {
693 return $this->mHTMLtitle
;
697 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
698 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
699 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
700 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
702 public function setPageTitle( $name ) {
703 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
704 # but leave "<i>foobar</i>" alone
705 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
706 $this->mPagetitle
= $nameWithTags;
708 # change "<i>foo&bar</i>" to "foo&bar"
709 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
713 * Return the "page title", i.e. the content of the \<h1\> tag.
717 public function getPageTitle() {
718 return $this->mPagetitle
;
722 * Set the Title object to use
724 * @param $t Title object
726 public function setTitle( $t ) {
731 * Get the Title object used in this instance
735 public function getTitle() {
736 if ( $this->mTitle
instanceof Title
) {
737 return $this->mTitle
;
739 wfDebug( __METHOD__
. " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
746 * Replace the subtile with $str
748 * @param $str String: new value of the subtitle
750 public function setSubtitle( $str ) {
751 $this->mSubtitle
= /*$this->parse(*/ $str /*)*/; // @bug 2514
755 * Add $str to the subtitle
757 * @param $str String to add to the subtitle
759 public function appendSubtitle( $str ) {
760 $this->mSubtitle
.= /*$this->parse(*/ $str /*)*/; // @bug 2514
768 public function getSubtitle() {
769 return $this->mSubtitle
;
773 * Set the page as printable, i.e. it'll be displayed with with all
774 * print styles included
776 public function setPrintable() {
777 $this->mPrintable
= true;
781 * Return whether the page is "printable"
785 public function isPrintable() {
786 return $this->mPrintable
;
790 * Disable output completely, i.e. calling output() will have no effect
792 public function disable() {
793 $this->mDoNothing
= true;
797 * Return whether the output will be completely disabled
801 public function isDisabled() {
802 return $this->mDoNothing
;
806 * Show an "add new section" link?
810 public function showNewSectionLink() {
811 return $this->mNewSectionLink
;
815 * Forcibly hide the new section link?
819 public function forceHideNewSectionLink() {
820 return $this->mHideNewSectionLink
;
824 * Add or remove feed links in the page header
825 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
826 * for the new version
829 * @param $show Boolean: true: add default feeds, false: remove all feeds
831 public function setSyndicated( $show = true ) {
833 $this->setFeedAppendQuery( false );
835 $this->mFeedLinks
= array();
840 * Add default feeds to the page header
841 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
842 * for the new version
845 * @param $val String: query to append to feed links or false to output
848 public function setFeedAppendQuery( $val ) {
849 global $wgAdvertisedFeedTypes;
851 $this->mFeedLinks
= array();
853 foreach ( $wgAdvertisedFeedTypes as $type ) {
854 $query = "feed=$type";
855 if ( is_string( $val ) ) {
856 $query .= '&' . $val;
858 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
863 * Add a feed link to the page header
865 * @param $format String: feed type, should be a key of $wgFeedClasses
866 * @param $href String: URL
868 public function addFeedLink( $format, $href ) {
869 global $wgAdvertisedFeedTypes;
871 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
872 $this->mFeedLinks
[$format] = $href;
877 * Should we output feed links for this page?
880 public function isSyndicated() {
881 return count( $this->mFeedLinks
) > 0;
885 * Return URLs for each supported syndication format for this page.
886 * @return array associating format keys with URLs
888 public function getSyndicationLinks() {
889 return $this->mFeedLinks
;
893 * Will currently always return null
897 public function getFeedAppendQuery() {
898 return $this->mFeedLinksAppendQuery
;
902 * Set whether the displayed content is related to the source of the
903 * corresponding article on the wiki
904 * Setting true will cause the change "article related" toggle to true
908 public function setArticleFlag( $v ) {
909 $this->mIsarticle
= $v;
911 $this->mIsArticleRelated
= $v;
916 * Return whether the content displayed page is related to the source of
917 * the corresponding article on the wiki
921 public function isArticle() {
922 return $this->mIsarticle
;
926 * Set whether this page is related an article on the wiki
927 * Setting false will cause the change of "article flag" toggle to false
931 public function setArticleRelated( $v ) {
932 $this->mIsArticleRelated
= $v;
934 $this->mIsarticle
= false;
939 * Return whether this page is related an article on the wiki
943 public function isArticleRelated() {
944 return $this->mIsArticleRelated
;
948 * Add new language links
950 * @param $newLinkArray Associative array mapping language code to the page
953 public function addLanguageLinks( $newLinkArray ) {
954 $this->mLanguageLinks +
= $newLinkArray;
958 * Reset the language links and add new language links
960 * @param $newLinkArray Associative array mapping language code to the page
963 public function setLanguageLinks( $newLinkArray ) {
964 $this->mLanguageLinks
= $newLinkArray;
968 * Get the list of language links
970 * @return Associative array mapping language code to the page name
972 public function getLanguageLinks() {
973 return $this->mLanguageLinks
;
977 * Add an array of categories, with names in the keys
979 * @param $categories Associative array mapping category name to its sort key
981 public function addCategoryLinks( $categories ) {
982 global $wgUser, $wgContLang;
984 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
988 # Add the links to a LinkBatch
989 $arr = array( NS_CATEGORY
=> $categories );
991 $lb->setArray( $arr );
993 # Fetch existence plus the hiddencat property
994 $dbr = wfGetDB( DB_SLAVE
);
995 $pageTable = $dbr->tableName( 'page' );
996 $where = $lb->constructSet( 'page', $dbr );
997 $propsTable = $dbr->tableName( 'page_props' );
998 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, page_latest, pp_value
999 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
1000 $res = $dbr->query( $sql, __METHOD__
);
1002 # Add the results to the link cache
1003 $lb->addResultToCache( LinkCache
::singleton(), $res );
1005 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1006 $categories = array_combine(
1007 array_keys( $categories ),
1008 array_fill( 0, count( $categories ), 'normal' )
1011 # Mark hidden categories
1012 foreach ( $res as $row ) {
1013 if ( isset( $row->pp_value
) ) {
1014 $categories[$row->page_title
] = 'hidden';
1018 # Add the remaining categories to the skin
1019 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
1020 $sk = $wgUser->getSkin();
1021 foreach ( $categories as $category => $type ) {
1022 $origcategory = $category;
1023 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1024 $wgContLang->findVariantLink( $category, $title, true );
1025 if ( $category != $origcategory ) {
1026 if ( array_key_exists( $category, $categories ) ) {
1030 $text = $wgContLang->convertHtml( $title->getText() );
1031 $this->mCategories
[] = $title->getText();
1032 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
1038 * Reset the category links (but not the category list) and add $categories
1040 * @param $categories Associative array mapping category name to its sort key
1042 public function setCategoryLinks( $categories ) {
1043 $this->mCategoryLinks
= array();
1044 $this->addCategoryLinks( $categories );
1048 * Get the list of category links, in a 2-D array with the following format:
1049 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1050 * hidden categories) and $link a HTML fragment with a link to the category
1055 public function getCategoryLinks() {
1056 return $this->mCategoryLinks
;
1060 * Get the list of category names this page belongs to
1062 * @return Array of strings
1064 public function getCategories() {
1065 return $this->mCategories
;
1069 * Suppress the quickbar from the output, only for skin supporting
1072 public function suppressQuickbar() {
1073 $this->mSuppressQuickbar
= true;
1077 * Return whether the quickbar should be suppressed from the output
1081 public function isQuickbarSuppressed() {
1082 return $this->mSuppressQuickbar
;
1086 * Remove user JavaScript from scripts to load
1088 public function disallowUserJs() {
1089 $this->mAllowUserJs
= false;
1093 * Return whether user JavaScript is allowed for this page
1097 public function isUserJsAllowed() {
1098 return $this->mAllowUserJs
;
1102 * Prepend $text to the body HTML
1104 * @param $text String: HTML
1106 public function prependHTML( $text ) {
1107 $this->mBodytext
= $text . $this->mBodytext
;
1111 * Append $text to the body HTML
1113 * @param $text String: HTML
1115 public function addHTML( $text ) {
1116 $this->mBodytext
.= $text;
1120 * Clear the body HTML
1122 public function clearHTML() {
1123 $this->mBodytext
= '';
1129 * @return String: HTML
1131 public function getHTML() {
1132 return $this->mBodytext
;
1136 * Add $text to the debug output
1138 * @param $text String: debug text
1140 public function debug( $text ) {
1141 $this->mDebugtext
.= $text;
1145 * Get/set the ParserOptions object to use for wikitext parsing
1147 * @param $options either the ParserOption to use or null to only get the
1148 * current ParserOption object
1149 * @return current ParserOption object
1151 public function parserOptions( $options = null ) {
1152 if ( !$this->mParserOptions
) {
1153 $this->mParserOptions
= new ParserOptions
;
1155 return wfSetVar( $this->mParserOptions
, $options );
1159 * Set the revision ID which will be seen by the wiki text parser
1160 * for things such as embedded {{REVISIONID}} variable use.
1162 * @param $revid Mixed: an positive integer, or null
1163 * @return Mixed: previous value
1165 public function setRevisionId( $revid ) {
1166 $val = is_null( $revid ) ?
null : intval( $revid );
1167 return wfSetVar( $this->mRevisionId
, $val );
1171 * Get the current revision ID
1175 public function getRevisionId() {
1176 return $this->mRevisionId
;
1180 * Convert wikitext to HTML and add it to the buffer
1181 * Default assumes that the current page title will be used.
1183 * @param $text String
1184 * @param $linestart Boolean: is this the start of a line?
1186 public function addWikiText( $text, $linestart = true ) {
1187 $title = $this->getTitle(); // Work arround E_STRICT
1188 $this->addWikiTextTitle( $text, $title, $linestart );
1192 * Add wikitext with a custom Title object
1194 * @param $text String: wikitext
1195 * @param $title Title object
1196 * @param $linestart Boolean: is this the start of a line?
1198 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1199 $this->addWikiTextTitle( $text, $title, $linestart );
1203 * Add wikitext with a custom Title object and
1205 * @param $text String: wikitext
1206 * @param $title Title object
1207 * @param $linestart Boolean: is this the start of a line?
1209 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1210 $this->addWikiTextTitle( $text, $title, $linestart, true );
1214 * Add wikitext with tidy enabled
1216 * @param $text String: wikitext
1217 * @param $linestart Boolean: is this the start of a line?
1219 public function addWikiTextTidy( $text, $linestart = true ) {
1220 $title = $this->getTitle();
1221 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1225 * Add wikitext with a custom Title object
1227 * @param $text String: wikitext
1228 * @param $title Title object
1229 * @param $linestart Boolean: is this the start of a line?
1230 * @param $tidy Boolean: whether to use tidy
1232 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1235 wfProfileIn( __METHOD__
);
1237 wfIncrStats( 'pcache_not_possible' );
1239 $popts = $this->parserOptions();
1240 $oldTidy = $popts->setTidy( $tidy );
1242 $parserOutput = $wgParser->parse(
1243 $text, $title, $popts,
1244 $linestart, true, $this->mRevisionId
1247 $popts->setTidy( $oldTidy );
1249 $this->addParserOutput( $parserOutput );
1251 wfProfileOut( __METHOD__
);
1255 * Add a ParserOutput object, but without Html
1257 * @param $parserOutput ParserOutput object
1259 public function addParserOutputNoText( &$parserOutput ) {
1260 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1261 $this->addCategoryLinks( $parserOutput->getCategories() );
1262 $this->mNewSectionLink
= $parserOutput->getNewSection();
1263 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1265 $this->mParseWarnings
= $parserOutput->getWarnings();
1266 if ( !$parserOutput->isCacheable() ) {
1267 $this->enableClientCache( false );
1269 $this->mNoGallery
= $parserOutput->getNoGallery();
1270 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1271 $this->addModules( $parserOutput->getModules() );
1273 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
1274 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1275 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1277 $this->mTemplateIds
[$ns] = $dbks;
1281 // Hooks registered in the object
1282 global $wgParserOutputHooks;
1283 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1284 list( $hookName, $data ) = $hookInfo;
1285 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1286 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1290 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1294 * Add a ParserOutput object
1296 * @param $parserOutput ParserOutput
1298 function addParserOutput( &$parserOutput ) {
1299 $this->addParserOutputNoText( $parserOutput );
1300 $text = $parserOutput->getText();
1301 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1302 $this->addHTML( $text );
1307 * Add the output of a QuickTemplate to the output buffer
1309 * @param $template QuickTemplate
1311 public function addTemplate( &$template ) {
1313 $template->execute();
1314 $this->addHTML( ob_get_contents() );
1319 * Parse wikitext and return the HTML.
1321 * @param $text String
1322 * @param $linestart Boolean: is this the start of a line?
1323 * @param $interface Boolean: use interface language ($wgLang instead of
1324 * $wgContLang) while parsing language sensitive magic
1325 * words like GRAMMAR and PLURAL
1326 * @param $language Language object: target language object, will override
1328 * @return String: HTML
1330 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1331 // Check one for one common cause for parser state resetting
1332 $callers = wfGetAllCallers( 10 );
1333 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1334 throw new MWException( "wfMsg* function with parsing cannot be used " .
1335 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1340 if( is_null( $this->getTitle() ) ) {
1341 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1344 $popts = $this->parserOptions();
1346 $popts->setInterfaceMessage( true );
1348 if ( $language !== null ) {
1349 $oldLang = $popts->setTargetLanguage( $language );
1352 $parserOutput = $wgParser->parse(
1353 $text, $this->getTitle(), $popts,
1354 $linestart, true, $this->mRevisionId
1358 $popts->setInterfaceMessage( false );
1360 if ( $language !== null ) {
1361 $popts->setTargetLanguage( $oldLang );
1364 return $parserOutput->getText();
1368 * Parse wikitext, strip paragraphs, and return the HTML.
1370 * @param $text String
1371 * @param $linestart Boolean: is this the start of a line?
1372 * @param $interface Boolean: use interface language ($wgLang instead of
1373 * $wgContLang) while parsing language sensitive magic
1374 * words like GRAMMAR and PLURAL
1375 * @return String: HTML
1377 public function parseInline( $text, $linestart = true, $interface = false ) {
1378 $parsed = $this->parse( $text, $linestart, $interface );
1381 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1389 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1391 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1393 public function setSquidMaxage( $maxage ) {
1394 $this->mSquidMaxage
= $maxage;
1398 * Use enableClientCache(false) to force it to send nocache headers
1402 public function enableClientCache( $state ) {
1403 return wfSetVar( $this->mEnableClientCache
, $state );
1407 * Get the list of cookies that will influence on the cache
1411 function getCacheVaryCookies() {
1412 global $wgCookiePrefix, $wgCacheVaryCookies;
1414 if ( $cookies === null ) {
1415 $cookies = array_merge(
1417 "{$wgCookiePrefix}Token",
1418 "{$wgCookiePrefix}LoggedOut",
1423 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1429 * Return whether this page is not cacheable because "useskin" or "uselang"
1430 * URL parameters were passed.
1434 function uncacheableBecauseRequestVars() {
1436 return $wgRequest->getText( 'useskin', false ) === false
1437 && $wgRequest->getText( 'uselang', false ) === false;
1441 * Check if the request has a cache-varying cookie header
1442 * If it does, it's very important that we don't allow public caching
1446 function haveCacheVaryCookies() {
1448 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1449 if ( $cookieHeader === false ) {
1452 $cvCookies = $this->getCacheVaryCookies();
1453 foreach ( $cvCookies as $cookieName ) {
1454 # Check for a simple string match, like the way squid does it
1455 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1456 wfDebug( __METHOD__
. ": found $cookieName\n" );
1460 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1465 * Add an HTTP header that will influence on the cache
1467 * @param $header String: header name
1468 * @param $option either an Array or null
1470 public function addVaryHeader( $header, $option = null ) {
1471 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1472 $this->mVaryHeader
[$header] = $option;
1473 } elseif( is_array( $option ) ) {
1474 if( is_array( $this->mVaryHeader
[$header] ) ) {
1475 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1477 $this->mVaryHeader
[$header] = $option;
1480 $this->mVaryHeader
[$header] = array_unique( $this->mVaryHeader
[$header] );
1484 * Get a complete X-Vary-Options header
1488 public function getXVO() {
1489 $cvCookies = $this->getCacheVaryCookies();
1491 $cookiesOption = array();
1492 foreach ( $cvCookies as $cookieName ) {
1493 $cookiesOption[] = 'string-contains=' . $cookieName;
1495 $this->addVaryHeader( 'Cookie', $cookiesOption );
1498 foreach( $this->mVaryHeader
as $header => $option ) {
1499 $newheader = $header;
1500 if( is_array( $option ) ) {
1501 $newheader .= ';' . implode( ';', $option );
1503 $headers[] = $newheader;
1505 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1511 * bug 21672: Add Accept-Language to Vary and XVO headers
1512 * if there's no 'variant' parameter existed in GET.
1515 * /w/index.php?title=Main_page should always be served; but
1516 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1518 function addAcceptLanguage() {
1519 global $wgRequest, $wgContLang;
1520 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1521 $variants = $wgContLang->getVariants();
1522 $aloption = array();
1523 foreach ( $variants as $variant ) {
1524 if( $variant === $wgContLang->getCode() ) {
1527 $aloption[] = 'string-contains=' . $variant;
1529 // IE and some other browsers use another form of language code
1530 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1531 // We should handle these too.
1532 $ievariant = explode( '-', $variant );
1533 if ( count( $ievariant ) == 2 ) {
1534 $ievariant[1] = strtoupper( $ievariant[1] );
1535 $ievariant = implode( '-', $ievariant );
1536 $aloption[] = 'string-contains=' . $ievariant;
1540 $this->addVaryHeader( 'Accept-Language', $aloption );
1545 * Set a flag which will cause an X-Frame-Options header appropriate for
1546 * edit pages to be sent. The header value is controlled by
1547 * $wgEditPageFrameOptions.
1549 * This is the default for special pages. If you display a CSRF-protected
1550 * form on an ordinary view page, then you need to call this function.
1552 public function preventClickjacking( $enable = true ) {
1553 $this->mPreventClickjacking
= $enable;
1557 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1558 * This can be called from pages which do not contain any CSRF-protected
1561 public function allowClickjacking() {
1562 $this->mPreventClickjacking
= false;
1566 * Get the X-Frame-Options header value (without the name part), or false
1567 * if there isn't one. This is used by Skin to determine whether to enable
1568 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1570 public function getFrameOptions() {
1571 global $wgBreakFrames, $wgEditPageFrameOptions;
1572 if ( $wgBreakFrames ) {
1574 } elseif ( $this->mPreventClickjacking
&& $wgEditPageFrameOptions ) {
1575 return $wgEditPageFrameOptions;
1580 * Send cache control HTTP headers
1582 public function sendCacheControl() {
1583 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1585 $response = $wgRequest->response();
1586 if ( $wgUseETag && $this->mETag
) {
1587 $response->header( "ETag: $this->mETag" );
1590 $this->addAcceptLanguage();
1592 # don't serve compressed data to clients who can't handle it
1593 # maintain different caches for logged-in users and non-logged in ones
1594 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) ) );
1597 # Add an X-Vary-Options header for Squid with Wikimedia patches
1598 $response->header( $this->getXVO() );
1601 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1603 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1604 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
1608 # We'll purge the proxy cache explicitly, but require end user agents
1609 # to revalidate against the proxy on each visit.
1610 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1611 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1612 # start with a shorter timeout for initial testing
1613 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1614 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1615 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1617 # We'll purge the proxy cache for anons explicitly, but require end user agents
1618 # to revalidate against the proxy on each visit.
1619 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1620 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1621 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1622 # start with a shorter timeout for initial testing
1623 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1624 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1627 # We do want clients to cache if they can, but they *must* check for updates
1628 # on revisiting the page.
1629 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1630 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1631 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1633 if($this->mLastModified
) {
1634 $response->header( "Last-Modified: {$this->mLastModified}" );
1637 wfDebug( __METHOD__
. ": no caching **\n", false );
1639 # In general, the absence of a last modified header should be enough to prevent
1640 # the client from using its cache. We send a few other things just to make sure.
1641 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1642 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1643 $response->header( 'Pragma: no-cache' );
1648 * Get the message associed with the HTTP response code $code
1650 * @param $code Integer: status code
1651 * @return String or null: message or null if $code is not in the list of
1654 public static function getStatusMessage( $code ) {
1655 static $statusMessage = array(
1657 101 => 'Switching Protocols',
1658 102 => 'Processing',
1662 203 => 'Non-Authoritative Information',
1663 204 => 'No Content',
1664 205 => 'Reset Content',
1665 206 => 'Partial Content',
1666 207 => 'Multi-Status',
1667 300 => 'Multiple Choices',
1668 301 => 'Moved Permanently',
1671 304 => 'Not Modified',
1673 307 => 'Temporary Redirect',
1674 400 => 'Bad Request',
1675 401 => 'Unauthorized',
1676 402 => 'Payment Required',
1679 405 => 'Method Not Allowed',
1680 406 => 'Not Acceptable',
1681 407 => 'Proxy Authentication Required',
1682 408 => 'Request Timeout',
1685 411 => 'Length Required',
1686 412 => 'Precondition Failed',
1687 413 => 'Request Entity Too Large',
1688 414 => 'Request-URI Too Large',
1689 415 => 'Unsupported Media Type',
1690 416 => 'Request Range Not Satisfiable',
1691 417 => 'Expectation Failed',
1692 422 => 'Unprocessable Entity',
1694 424 => 'Failed Dependency',
1695 500 => 'Internal Server Error',
1696 501 => 'Not Implemented',
1697 502 => 'Bad Gateway',
1698 503 => 'Service Unavailable',
1699 504 => 'Gateway Timeout',
1700 505 => 'HTTP Version Not Supported',
1701 507 => 'Insufficient Storage'
1703 return isset( $statusMessage[$code] ) ?
$statusMessage[$code] : null;
1707 * Finally, all the text has been munged and accumulated into
1708 * the object, let's actually output it:
1710 public function output() {
1711 global $wgUser, $wgOutputEncoding, $wgRequest;
1712 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1713 global $wgUseAjax, $wgAjaxWatch;
1714 global $wgEnableMWSuggest, $wgUniversalEditButton;
1716 if( $this->mDoNothing
) {
1719 wfProfileIn( __METHOD__
);
1720 if ( $this->mRedirect
!= '' ) {
1721 # Standards require redirect URLs to be absolute
1722 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1723 if( $this->mRedirectCode
== '301' ||
$this->mRedirectCode
== '303' ) {
1724 if( !$wgDebugRedirects ) {
1725 $message = self
::getStatusMessage( $this->mRedirectCode
);
1726 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1728 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1730 $this->sendCacheControl();
1732 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1733 if( $wgDebugRedirects ) {
1734 $url = htmlspecialchars( $this->mRedirect
);
1735 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1736 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1737 print "</body>\n</html>\n";
1739 $wgRequest->response()->header( 'Location: ' . $this->mRedirect
);
1741 wfProfileOut( __METHOD__
);
1743 } elseif ( $this->mStatusCode
) {
1744 $message = self
::getStatusMessage( $this->mStatusCode
);
1746 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
1750 $sk = $wgUser->getSkin();
1752 // Add base resources
1753 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1755 // Add various resources if required
1757 $this->addModules( 'mediawiki.legacy.ajax' );
1759 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1761 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1762 $this->addModules( 'mediawiki.action.watch.ajax' );
1765 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1766 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1770 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1771 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1774 if( $wgUniversalEditButton ) {
1775 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1776 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1777 // Original UniversalEditButton
1778 $msg = wfMsg( 'edit' );
1779 $this->addLink( array(
1780 'rel' => 'alternate',
1781 'type' => 'application/x-wiki',
1783 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1785 // Alternate edit link
1786 $this->addLink( array(
1789 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1795 # Buffer output; final headers may depend on later processing
1798 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1799 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1801 // Prevent framing, if requested
1802 $frameOptions = $this->getFrameOptions();
1803 if ( $frameOptions ) {
1804 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1807 if ( $this->mArticleBodyOnly
) {
1808 $this->out( $this->mBodytext
);
1810 // Hook that allows last minute changes to the output page, e.g.
1811 // adding of CSS or Javascript by extensions.
1812 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1814 wfProfileIn( 'Output-skin' );
1815 $sk->outputPage( $this );
1816 wfProfileOut( 'Output-skin' );
1819 $this->sendCacheControl();
1821 wfProfileOut( __METHOD__
);
1825 * Actually output something with print(). Performs an iconv to the
1826 * output encoding, if needed.
1828 * @param $ins String: the string to output
1830 public function out( $ins ) {
1831 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1832 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1835 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1836 if ( false === $outs ) {
1844 * Produce a "user is blocked" page.
1846 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1849 function blockedPage( $return = true ) {
1850 global $wgUser, $wgContLang, $wgLang;
1852 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1853 $this->setRobotPolicy( 'noindex,nofollow' );
1854 $this->setArticleRelated( false );
1856 $name = User
::whoIs( $wgUser->blockedBy() );
1857 $reason = $wgUser->blockedFor();
1858 if( $reason == '' ) {
1859 $reason = wfMsg( 'blockednoreason' );
1861 $blockTimestamp = $wgLang->timeanddate(
1862 wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true
1866 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1868 $blockid = $wgUser->mBlock
->mId
;
1870 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1871 if ( $blockExpiry == 'infinity' ) {
1872 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1873 // Search for localization in 'ipboptions'
1874 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1875 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1876 if ( strpos( $option, ':' ) === false ) {
1879 list( $show, $value ) = explode( ':', $option );
1880 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1881 $blockExpiry = $show;
1886 $blockExpiry = $wgLang->timeanddate(
1887 wfTimestamp( TS_MW
, $blockExpiry ),
1892 if ( $wgUser->mBlock
->mAuto
) {
1893 $msg = 'autoblockedtext';
1895 $msg = 'blockedtext';
1898 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1899 * This could be a username, an IP range, or a single IP. */
1900 $intended = $wgUser->mBlock
->mAddress
;
1903 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1904 $intended, $blockTimestamp
1907 # Don't auto-return to special pages
1909 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1910 $this->returnToMain( null, $return );
1915 * Output a standard error page
1917 * @param $title String: message key for page title
1918 * @param $msg String: message key for page text
1919 * @param $params Array: message parameters
1921 public function showErrorPage( $title, $msg, $params = array() ) {
1922 if ( $this->getTitle() ) {
1923 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1925 $this->setPageTitle( wfMsg( $title ) );
1926 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1927 $this->setRobotPolicy( 'noindex,nofollow' );
1928 $this->setArticleRelated( false );
1929 $this->enableClientCache( false );
1930 $this->mRedirect
= '';
1931 $this->mBodytext
= '';
1933 $this->addWikiMsgArray( $msg, $params );
1935 $this->returnToMain();
1939 * Output a standard permission error page
1941 * @param $errors Array: error message keys
1942 * @param $action String: action that was denied or null if unknown
1944 public function showPermissionsErrorPage( $errors, $action = null ) {
1945 $this->mDebugtext
.= 'Original title: ' .
1946 $this->getTitle()->getPrefixedText() . "\n";
1947 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1948 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1949 $this->setRobotPolicy( 'noindex,nofollow' );
1950 $this->setArticleRelated( false );
1951 $this->enableClientCache( false );
1952 $this->mRedirect
= '';
1953 $this->mBodytext
= '';
1954 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1958 * Display an error page indicating that a given version of MediaWiki is
1959 * required to use it
1961 * @param $version Mixed: the version of MediaWiki needed to use the page
1963 public function versionRequired( $version ) {
1964 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1965 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1966 $this->setRobotPolicy( 'noindex,nofollow' );
1967 $this->setArticleRelated( false );
1968 $this->mBodytext
= '';
1970 $this->addWikiMsg( 'versionrequiredtext', $version );
1971 $this->returnToMain();
1975 * Display an error page noting that a given permission bit is required.
1977 * @param $permission String: key required
1979 public function permissionRequired( $permission ) {
1982 $this->setPageTitle( wfMsg( 'badaccess' ) );
1983 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1984 $this->setRobotPolicy( 'noindex,nofollow' );
1985 $this->setArticleRelated( false );
1986 $this->mBodytext
= '';
1988 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1989 User
::getGroupsWithPermission( $permission ) );
1993 $wgLang->commaList( $groups ),
1997 $this->addWikiMsg( 'badaccess-group0' );
1999 $this->returnToMain();
2003 * Produce the stock "please login to use the wiki" page
2005 public function loginToUse() {
2008 if( $wgUser->isLoggedIn() ) {
2009 $this->permissionRequired( 'read' );
2013 $skin = $wgUser->getSkin();
2015 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2016 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2017 $this->setRobotPolicy( 'noindex,nofollow' );
2018 $this->setArticleRelated( false );
2020 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2021 $loginLink = $skin->link(
2023 wfMsgHtml( 'loginreqlink' ),
2025 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2026 array( 'known', 'noclasses' )
2028 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
2029 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2031 # Don't return to the main page if the user can't read it
2032 # otherwise we'll end up in a pointless loop
2033 $mainPage = Title
::newMainPage();
2034 if( $mainPage->userCanRead() ) {
2035 $this->returnToMain( null, $mainPage );
2040 * Format a list of error messages
2042 * @param $errors An array of arrays returned by Title::getUserPermissionsErrors
2043 * @param $action String: action that was denied or null if unknown
2044 * @return String: the wikitext error-messages, formatted into a list.
2046 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2047 if ( $action == null ) {
2048 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2050 $action_desc = wfMsgNoTrans( "action-$action" );
2051 $text = wfMsgNoTrans(
2052 'permissionserrorstext-withaction',
2058 if ( count( $errors ) > 1 ) {
2059 $text .= '<ul class="permissions-errors">' . "\n";
2061 foreach( $errors as $error ) {
2063 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2068 $text .= "<div class=\"permissions-errors\">\n" .
2069 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2077 * Display a page stating that the Wiki is in read-only mode,
2078 * and optionally show the source of the page that the user
2079 * was trying to edit. Should only be called (for this
2080 * purpose) after wfReadOnly() has returned true.
2082 * For historical reasons, this function is _also_ used to
2083 * show the error message when a user tries to edit a page
2084 * they are not allowed to edit. (Unless it's because they're
2085 * blocked, then we show blockedPage() instead.) In this
2086 * case, the second parameter should be set to true and a list
2087 * of reasons supplied as the third parameter.
2089 * @todo Needs to be split into multiple functions.
2091 * @param $source String: source code to show (or null).
2092 * @param $protected Boolean: is this a permissions error?
2093 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2094 * @param $action String: action that was denied or null if unknown
2096 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2098 $skin = $wgUser->getSkin();
2100 $this->setRobotPolicy( 'noindex,nofollow' );
2101 $this->setArticleRelated( false );
2103 // If no reason is given, just supply a default "I can't let you do
2104 // that, Dave" message. Should only occur if called by legacy code.
2105 if ( $protected && empty( $reasons ) ) {
2106 $reasons[] = array( 'badaccess-group0' );
2109 if ( !empty( $reasons ) ) {
2110 // Permissions error
2112 $this->setPageTitle( wfMsg( 'viewsource' ) );
2114 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2117 $this->setPageTitle( wfMsg( 'badaccess' ) );
2119 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2121 // Wiki is read only
2122 $this->setPageTitle( wfMsg( 'readonly' ) );
2123 $reason = wfReadOnlyReason();
2124 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2127 // Show source, if supplied
2128 if( is_string( $source ) ) {
2129 $this->addWikiMsg( 'viewsourcetext' );
2132 'id' => 'wpTextbox1',
2133 'name' => 'wpTextbox1',
2134 'cols' => $wgUser->getOption( 'cols' ),
2135 'rows' => $wgUser->getOption( 'rows' ),
2136 'readonly' => 'readonly'
2138 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
2140 // Show templates used by this article
2141 $skin = $wgUser->getSkin();
2142 $article = new Article( $this->getTitle() );
2143 $this->addHTML( "<div class='templatesUsed'>
2144 {$skin->formatTemplates( $article->getUsedTemplates() )}
2149 # If the title doesn't exist, it's fairly pointless to print a return
2150 # link to it. After all, you just tried editing it and couldn't, so
2151 # what's there to do there?
2152 if( $this->getTitle()->exists() ) {
2153 $this->returnToMain( null, $this->getTitle() );
2158 * Adds JS-based password security checker
2159 * @param $passwordId String ID of input box containing password
2160 * @param $retypeId String ID of input box containing retyped password
2163 public function addPasswordSecurity( $passwordId, $retypeId ) {
2165 'password' => '#' . $passwordId,
2166 'retype' => '#' . $retypeId,
2167 'messages' => array(),
2169 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2170 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2172 $data['messages'][$message] = wfMsg( $message );
2174 $this->addScript( Html
::inlineScript( 'var passwordSecurity=' . FormatJson
::encode( $data ) ) );
2175 $this->addModules( 'mediawiki.legacy.password' );
2178 public function showFatalError( $message ) {
2179 $this->setPageTitle( wfMsg( 'internalerror' ) );
2180 $this->setRobotPolicy( 'noindex,nofollow' );
2181 $this->setArticleRelated( false );
2182 $this->enableClientCache( false );
2183 $this->mRedirect
= '';
2184 $this->mBodytext
= $message;
2187 public function showUnexpectedValueError( $name, $val ) {
2188 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2191 public function showFileCopyError( $old, $new ) {
2192 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2195 public function showFileRenameError( $old, $new ) {
2196 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2199 public function showFileDeleteError( $name ) {
2200 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2203 public function showFileNotFoundError( $name ) {
2204 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2208 * Add a "return to" link pointing to a specified title
2210 * @param $title Title to link
2211 * @param $query String: query string
2212 * @param $text String text of the link (input is not escaped)
2214 public function addReturnTo( $title, $query = array(), $text = null ) {
2216 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2219 $wgUser->getSkin()->link( $title, $text, array(), $query )
2221 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2225 * Add a "return to" link pointing to a specified title,
2226 * or the title indicated in the request, or else the main page
2228 * @param $unused No longer used
2229 * @param $returnto Title or String to return to
2230 * @param $returntoquery String: query string for the return to link
2232 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2235 if ( $returnto == null ) {
2236 $returnto = $wgRequest->getText( 'returnto' );
2239 if ( $returntoquery == null ) {
2240 $returntoquery = $wgRequest->getText( 'returntoquery' );
2243 if ( $returnto === '' ) {
2244 $returnto = Title
::newMainPage();
2247 if ( is_object( $returnto ) ) {
2248 $titleObj = $returnto;
2250 $titleObj = Title
::newFromText( $returnto );
2252 if ( !is_object( $titleObj ) ) {
2253 $titleObj = Title
::newMainPage();
2256 $this->addReturnTo( $titleObj, $returntoquery );
2260 * @param $sk Skin The given Skin
2261 * @param $includeStyle Boolean: unused
2262 * @return String: The doctype, opening <html>, and head element.
2264 public function headElement( Skin
$sk, $includeStyle = true ) {
2265 global $wgOutputEncoding, $wgMimeType;
2266 global $wgUseTrackbacks, $wgHtml5;
2267 global $wgUser, $wgRequest, $wgLang;
2269 if ( $sk->commonPrintStylesheet() ) {
2270 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2272 $sk->setupUserCss( $this );
2274 $ret = Html
::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2276 if ( $this->getHTMLTitle() == '' ) {
2277 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2280 $openHead = Html
::openElement( 'head' );
2282 # Don't bother with the newline if $head == ''
2283 $ret .= "$openHead\n";
2287 # More succinct than <meta http-equiv=Content-Type>, has the
2289 $ret .= Html
::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2291 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2294 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2296 $ret .= implode( "\n", array(
2297 $this->getHeadLinks( $sk ),
2298 $this->buildCssLinks( $sk ),
2299 $this->getHeadItems()
2302 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2303 $ret .= $this->getTitle()->trackbackRDF();
2306 $closeHead = Html
::closeElement( 'head' );
2308 $ret .= "$closeHead\n";
2311 $bodyAttrs = array();
2313 # Crazy edit-on-double-click stuff
2314 $action = $wgRequest->getVal( 'action', 'view' );
2317 $this->getTitle()->getNamespace() != NS_SPECIAL
&&
2318 !in_array( $action, array( 'edit', 'submit' ) ) &&
2319 $wgUser->getOption( 'editondblclick' )
2322 $bodyAttrs['ondblclick'] = "document.location = '" . Xml
::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2326 $dir = wfUILang()->getDir();
2327 $bodyAttrs['class'] = "mediawiki $dir";
2329 if ( $wgLang->capitalizeAllNouns() ) {
2330 # A <body> class is probably not the best way to do this . . .
2331 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2333 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2334 if ( $this->getTitle()->getNamespace() == NS_SPECIAL
) {
2335 $bodyAttrs['class'] .= ' ns-special';
2336 } elseif ( $this->getTitle()->isTalkPage() ) {
2337 $bodyAttrs['class'] .= ' ns-talk';
2339 $bodyAttrs['class'] .= ' ns-subject';
2341 $bodyAttrs['class'] .= ' ' . Sanitizer
::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2342 $bodyAttrs['class'] .= ' skin-' . Sanitizer
::escapeClass( $wgUser->getSkin()->getSkinName() );
2344 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2345 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2347 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2353 * Get a ResourceLoader object associated with this OutputPage
2355 public function getResourceLoader() {
2356 if ( is_null( $this->mResourceLoader
) ) {
2357 $this->mResourceLoader
= new ResourceLoader();
2359 return $this->mResourceLoader
;
2365 * @param $modules Array/string with the module name
2366 * @param $only string May be styles, messages or scripts
2367 * @param $useESI boolean
2368 * @return string html <script> and <style> tags
2370 protected function makeResourceLoaderLink( Skin
$skin, $modules, $only, $useESI = false ) {
2371 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2372 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2373 // Lazy-load ResourceLoader
2374 // TODO: Should this be a static function of ResourceLoader instead?
2375 // TODO: Divide off modules starting with "user", and add the user parameter to them
2377 'lang' => $wgLang->getCode(),
2378 'debug' => ResourceLoader
::inDebugMode() ?
'true' : 'false',
2379 'skin' => $skin->getSkinName(),
2382 // Propagate printable and handheld parameters if present
2383 if ( $wgRequest->getBool( 'printable' ) ) {
2384 $query['printable'] = 1;
2386 if ( $wgRequest->getBool( 'handheld' ) ) {
2387 $query['handheld'] = 1;
2390 if ( !count( $modules ) ) {
2394 if ( count( $modules ) > 1 ) {
2395 // Remove duplicate module requests
2396 $modules = array_unique( (array) $modules );
2397 // Sort module names so requests are more uniform
2400 if ( ResourceLoader
::inDebugMode() ) {
2401 // Recursively call us for every item
2403 foreach ( $modules as $name ) {
2404 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2410 // Create keyed-by-group list of module objects from modules list
2412 $resourceLoader = $this->getResourceLoader();
2413 foreach ( (array) $modules as $name ) {
2414 $module = $resourceLoader->getModule( $name );
2415 $group = $module->getGroup();
2416 if ( !isset( $groups[$group] ) ) {
2417 $groups[$group] = array();
2419 $groups[$group][$name] = $module;
2422 foreach ( $groups as $group => $modules ) {
2423 $query['modules'] = implode( '|', array_keys( $modules ) );
2424 // Special handling for user-specific groups
2425 if ( ( $group === 'user' ||
$group === 'private' ) && $wgUser->isLoggedIn() ) {
2426 $query['user'] = $wgUser->getName();
2428 // Support inlining of private modules if configured as such
2429 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2430 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2431 if ( $only == 'styles' ) {
2432 $links .= Html
::inlineStyle(
2433 $resourceLoader->makeModuleResponse( $context, $modules )
2436 $links .= Html
::inlineScript(
2437 ResourceLoader
::makeLoaderConditionalScript(
2438 $resourceLoader->makeModuleResponse( $context, $modules )
2444 // Special handling for user and site groups; because users might change their stuff
2445 // on-wiki like site or user pages, or user preferences; we need to find the highest
2446 // timestamp of these user-changable modules so we can ensure cache misses on change
2447 if ( $group === 'user' ||
$group === 'site' ) {
2448 // Create a fake request based on the one we are about to make so modules return
2450 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2451 // Get the maximum timestamp
2453 foreach ( $modules as $module ) {
2454 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2456 // Add a version parameter so cache will break when things change
2457 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, round( $timestamp, -2 ) );
2459 // Make queries uniform in order
2462 $url = wfAppendQuery( $wgLoadScript, $query );
2463 if ( $useESI && $wgResourceLoaderUseESI ) {
2464 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2465 if ( $only == 'styles' ) {
2466 $links .= Html
::inlineStyle( $esi );
2468 $links .= Html
::inlineScript( $esi );
2471 // Automatically select style/script elements
2472 if ( $only === 'styles' ) {
2473 $links .= Html
::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2475 $links .= Html
::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2483 * Gets the global variables and mScripts; also adds userjs to the end if
2484 * enabled. Despite the name, these scripts are no longer put in the
2485 * <head> but at the bottom of the <body>
2487 * @param $sk Skin object to use
2488 * @return String: HTML fragment
2490 function getHeadScripts( Skin
$sk ) {
2491 global $wgUser, $wgRequest, $wgUseSiteJs;
2493 // Startup - this will immediately load jquery and mediawiki modules
2494 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2496 // Configuration -- This could be merged together with the load and go, but
2497 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2498 $scripts .= Skin
::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2500 // Script and Messages "only" requests
2501 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2502 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2504 // Modules requests - let the client calculate dependencies and batch requests as it likes
2505 if ( $this->getModules() ) {
2506 $scripts .= Html
::inlineScript(
2507 ResourceLoader
::makeLoaderConditionalScript(
2508 Xml
::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2509 Xml
::encodeJsCall( 'mediaWiki.loader.go', array() )
2515 $scripts .= "\n" . $this->mScripts
;
2517 // Add site JS if enabled
2518 if ( $wgUseSiteJs ) {
2519 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2522 // Add user JS if enabled - trying to load user.options as a bundle if possible
2523 $userOptionsAdded = false;
2524 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2525 $action = $wgRequest->getVal( 'action', 'view' );
2526 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2527 # XXX: additional security check/prompt?
2528 $scripts .= Html
::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2530 $scripts .= $this->makeResourceLoaderLink(
2531 $sk, array( 'user', 'user.options' ), 'scripts'
2533 $userOptionsAdded = true;
2536 if ( !$userOptionsAdded ) {
2537 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2544 * Add default \<meta\> tags
2546 protected function addDefaultMeta() {
2547 global $wgVersion, $wgHtml5;
2549 static $called = false;
2551 # Don't run this twice
2557 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2559 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2561 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2562 if( $p !== 'index,follow' ) {
2563 // http://www.robotstxt.org/wc/meta-user.html
2564 // Only show if it's different from the default robots policy
2565 $this->addMeta( 'robots', $p );
2568 if ( count( $this->mKeywords
) > 0 ) {
2570 "/<.*?" . ">/" => '',
2576 array_keys( $strip ),
2577 array_values( $strip ),
2578 implode( ',', $this->mKeywords
)
2585 * @return string HTML tag links to be put in the header.
2587 public function getHeadLinks( Skin
$sk ) {
2590 // Ideally this should happen earlier, somewhere. :P
2591 $this->addDefaultMeta();
2595 foreach ( $this->mMetatags
as $tag ) {
2596 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2598 $tag[0] = substr( $tag[0], 5 );
2602 $tags[] = Html
::element( 'meta',
2605 'content' => $tag[1]
2609 foreach ( $this->mLinktags
as $tag ) {
2610 $tags[] = Html
::element( 'link', $tag );
2614 foreach( $this->getSyndicationLinks() as $format => $link ) {
2615 # Use the page name for the title (accessed through $wgTitle since
2616 # there's no other way). In principle, this could lead to issues
2617 # with having the same name for different feeds corresponding to
2618 # the same page, but we can't avoid that at this low a level.
2620 $tags[] = $this->feedLink(
2623 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2624 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2628 # Recent changes feed should appear on every page (except recentchanges,
2629 # that would be redundant). Put it after the per-page feed to avoid
2630 # changing existing behavior. It's still available, probably via a
2631 # menu in your browser. Some sites might have a different feed they'd
2632 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2633 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2634 # If so, use it instead.
2636 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2637 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
2639 if ( $wgOverrideSiteFeed ) {
2640 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2641 $tags[] = $this->feedLink(
2643 htmlspecialchars( $feedUrl ),
2644 wfMsg( "site-{$type}-feed", $wgSitename )
2647 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2648 foreach ( $wgAdvertisedFeedTypes as $format ) {
2649 $tags[] = $this->feedLink(
2651 $rctitle->getLocalURL( "feed={$format}" ),
2652 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2657 return implode( "\n", $tags );
2661 * Generate a <link rel/> for a feed.
2663 * @param $type String: feed type
2664 * @param $url String: URL to the feed
2665 * @param $text String: value of the "title" attribute
2666 * @return String: HTML fragment
2668 private function feedLink( $type, $url, $text ) {
2669 return Html
::element( 'link', array(
2670 'rel' => 'alternate',
2671 'type' => "application/$type+xml",
2678 * Add a local or specified stylesheet, with the given media options.
2679 * Meant primarily for internal use...
2681 * @param $style String: URL to the file
2682 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2683 * @param $condition String: for IE conditional comments, specifying an IE version
2684 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2686 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2688 // Even though we expect the media type to be lowercase, but here we
2689 // force it to lowercase to be safe.
2691 $options['media'] = $media;
2694 $options['condition'] = $condition;
2697 $options['dir'] = $dir;
2699 $this->styles
[$style] = $options;
2703 * Adds inline CSS styles
2704 * @param $style_css Mixed: inline CSS
2706 public function addInlineStyle( $style_css ){
2707 $this->mInlineStyles
.= Html
::inlineStyle( $style_css );
2711 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2712 * These will be applied to various media & IE conditionals.
2713 * @param $sk Skin object
2715 public function buildCssLinks( $sk ) {
2717 // Add ResourceLoader styles
2718 // Split the styles into three groups
2719 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2720 $resourceLoader = $this->getResourceLoader();
2721 foreach ( $this->getModuleStyles() as $name ) {
2722 $group = $resourceLoader->getModule( $name )->getGroup();
2723 // Modules in groups named "other" or anything different than "user" or "site" will
2724 // be placed in the "other" group
2725 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
2728 // We want site and user styles to override dynamically added styles from modules, but we want
2729 // dynamically added styles to override statically added styles from other modules. So the order
2730 // has to be other, dynamic, site, user
2731 // Add statically added styles for other modules
2732 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2733 // Add normal styles added through addStyle()/addInlineStyle() here
2734 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
2735 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2736 // We use a <meta> tag with a made-up name for this because that's valid HTML
2737 $ret .= Html
::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2738 // Add site and user styles
2739 $ret .= $this->makeResourceLoaderLink(
2740 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2745 public function buildCssLinksArray() {
2747 foreach( $this->styles
as $file => $options ) {
2748 $link = $this->styleLink( $file, $options );
2750 $links[$file] = $link;
2757 * Generate \<link\> tags for stylesheets
2759 * @param $style String: URL to the file
2760 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2762 * @return String: HTML fragment
2764 protected function styleLink( $style, $options ) {
2765 if( isset( $options['dir'] ) ) {
2766 $siteDir = wfUILang()->getDir();
2767 if( $siteDir != $options['dir'] ) {
2772 if( isset( $options['media'] ) ) {
2773 $media = self
::transformCssMedia( $options['media'] );
2774 if( is_null( $media ) ) {
2781 if( substr( $style, 0, 1 ) == '/' ||
2782 substr( $style, 0, 5 ) == 'http:' ||
2783 substr( $style, 0, 6 ) == 'https:' ) {
2786 global $wgStylePath, $wgStyleVersion;
2787 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2790 $link = Html
::linkedStyle( $url, $media );
2792 if( isset( $options['condition'] ) ) {
2793 $condition = htmlspecialchars( $options['condition'] );
2794 $link = "<!--[if $condition]>$link<![endif]-->";
2800 * Transform "media" attribute based on request parameters
2802 * @param $media String: current value of the "media" attribute
2803 * @return String: modified value of the "media" attribute
2805 public static function transformCssMedia( $media ) {
2806 global $wgRequest, $wgHandheldForIPhone;
2808 // Switch in on-screen display for media testing
2810 'printable' => 'print',
2811 'handheld' => 'handheld',
2813 foreach( $switches as $switch => $targetMedia ) {
2814 if( $wgRequest->getBool( $switch ) ) {
2815 if( $media == $targetMedia ) {
2817 } elseif( $media == 'screen' ) {
2823 // Expand longer media queries as iPhone doesn't grok 'handheld'
2824 if( $wgHandheldForIPhone ) {
2825 $mediaAliases = array(
2826 'screen' => 'screen and (min-device-width: 481px)',
2827 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2830 if( isset( $mediaAliases[$media] ) ) {
2831 $media = $mediaAliases[$media];
2839 * Turn off regular page output and return an error reponse
2840 * for when rate limiting has triggered.
2842 public function rateLimited() {
2843 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2844 $this->setRobotPolicy( 'noindex,follow' );
2845 $this->setArticleRelated( false );
2846 $this->enableClientCache( false );
2847 $this->mRedirect
= '';
2849 $this->setStatusCode( 503 );
2850 $this->addWikiMsg( 'actionthrottledtext' );
2852 $this->returnToMain( null, $this->getTitle() );
2856 * Show a warning about slave lag
2858 * If the lag is higher than $wgSlaveLagCritical seconds,
2859 * then the warning is a bit more obvious. If the lag is
2860 * lower than $wgSlaveLagWarning, then no warning is shown.
2862 * @param $lag Integer: slave lag
2864 public function showLagWarning( $lag ) {
2865 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2866 if( $lag >= $wgSlaveLagWarning ) {
2867 $message = $lag < $wgSlaveLagCritical
2870 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2871 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2876 * Add a wikitext-formatted message to the output.
2877 * This is equivalent to:
2879 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2881 public function addWikiMsg( /*...*/ ) {
2882 $args = func_get_args();
2883 $name = array_shift( $args );
2884 $this->addWikiMsgArray( $name, $args );
2888 * Add a wikitext-formatted message to the output.
2889 * Like addWikiMsg() except the parameters are taken as an array
2890 * instead of a variable argument list.
2892 * $options is passed through to wfMsgExt(), see that function for details.
2894 public function addWikiMsgArray( $name, $args, $options = array() ) {
2895 $options[] = 'parse';
2896 $text = wfMsgExt( $name, $options, $args );
2897 $this->addHTML( $text );
2901 * This function takes a number of message/argument specifications, wraps them in
2902 * some overall structure, and then parses the result and adds it to the output.
2904 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2905 * on. The subsequent arguments may either be strings, in which case they are the
2906 * message names, or arrays, in which case the first element is the message name,
2907 * and subsequent elements are the parameters to that message.
2909 * The special named parameter 'options' in a message specification array is passed
2910 * through to the $options parameter of wfMsgExt().
2912 * Don't use this for messages that are not in users interface language.
2916 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2920 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2922 * The newline after opening div is needed in some wikitext. See bug 19226.
2924 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2925 $msgSpecs = func_get_args();
2926 array_shift( $msgSpecs );
2927 $msgSpecs = array_values( $msgSpecs );
2929 foreach ( $msgSpecs as $n => $spec ) {
2931 if ( is_array( $spec ) ) {
2933 $name = array_shift( $args );
2934 if ( isset( $args['options'] ) ) {
2935 $options = $args['options'];
2936 unset( $args['options'] );
2942 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2944 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2948 * Include jQuery core. Use this to avoid loading it multiple times
2949 * before we get a usable script loader.
2951 * @param $modules Array: list of jQuery modules which should be loaded
2952 * @return Array: the list of modules which were not loaded.
2954 * @deprecated @since 1.17
2956 public function includeJQuery( $modules = array() ) {