2 if ( ! defined( 'MEDIAWIKI' ) )
9 var $mMetatags = array(), $mKeywords = array(), $mLinktags = array();
10 var $mExtStyles = array();
11 var $mPagetitle = '', $mBodytext = '', $mDebugtext = '';
12 var $mHTMLtitle = '', $mIsarticle = true, $mPrintable = false;
13 var $mSubtitle = '', $mRedirect = '', $mStatusCode;
14 var $mLastModified = '', $mETag = false;
15 var $mCategoryLinks = array(), $mLanguageLinks = array();
17 var $mScriptLoaderClassList = array();
19 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
20 var $mInlineMsg = array();
22 var $mTemplateIds = array();
25 var $mSuppressQuickbar = false;
26 var $mOnloadHandler = '';
27 var $mDoNothing = false;
28 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
29 var $mIsArticleRelated = true;
30 protected $mParserOptions = null; // lazy initialised, use parserOptions()
32 var $mFeedLinks = array();
34 var $mEnableClientCache = true;
35 var $mArticleBodyOnly = false;
37 var $mNewSectionLink = false;
38 var $mHideNewSectionLink = false;
39 var $mNoGallery = false;
40 var $mPageTitleActionText = '';
41 var $mParseWarnings = array();
42 var $mSquidMaxage = 0;
43 var $mRevisionId = null;
44 var $mScriptLoader = null;
45 protected $mTitle = null;
48 * An array of stylesheet filenames (relative from skins path), with options
49 * for CSS media, IE conditions, and RTL/LTR direction.
50 * For internal use; add settings in the skin via $this->addStyle()
52 var $styles = array();
54 private $mIndexPolicy = 'index';
55 private $mFollowPolicy = 'follow';
59 * Initialise private variables
61 function __construct() {
62 global $wgAllowUserJs;
63 $this->mAllowUserJs
= $wgAllowUserJs;
66 public function redirect( $url, $responsecode = '302' ) {
67 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
68 $this->mRedirect
= str_replace( "\n", '', $url );
69 $this->mRedirectCode
= $responsecode;
72 public function getRedirect() {
73 return $this->mRedirect
;
77 * Set the HTTP status code to send with the output.
79 * @param int $statusCode
82 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
85 * Add a new <meta> tag
86 * To add an http-equiv meta tag, precede the name with "http:"
88 * @param $name tag name
89 * @param $val tag value
91 function addMeta( $name, $val ) {
92 array_push( $this->mMetatags
, array( $name, $val ) );
95 function addKeyword( $text ) {
96 if( is_array( $text )) {
97 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
99 array_push( $this->mKeywords
, $text );
102 function addScript( $script ) {
103 $this->mScripts
.= $script . "\n";
107 * Register and add a stylesheet from an extension directory.
108 * @param $url String path to sheet. Provide either a full url (beginning
109 * with 'http', etc) or a relative path from the document root
110 * (beginning with '/'). Otherwise it behaves identically to
111 * addStyle() and draws from the /skins folder.
113 public function addExtensionStyle( $url ) {
114 array_push( $this->mExtStyles
, $url );
118 * Add a JavaScript file out of skins/common, or a given relative path.
119 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
121 function addScriptFile( $file ) {
122 global $wgStylePath, $wgScript, $wgUser;
123 global $wgEnableScriptLoader, $wgScriptPath;
125 if( substr( $file, 0, 1 ) == '/' ) {
128 $path = "{$wgStylePath}/common/{$file}";
131 // If the class can be determined, use the addScriptClass method
132 $js_class = $this->getJsClassFromPath( $path );
134 $this->addScriptClass( $js_class );
138 //do checks for wiki-titles
139 if( strpos( $path, $wgScript ) !== false ) {
140 $reqPath = str_replace( $wgScript . '?', '', $path );
141 $reqArgs = explode( '&', $reqPath );
144 foreach( $reqArgs as $arg ) {
145 list( $key, $var ) = explode( '=', $arg );
146 $reqSet[$key] = $var;
149 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
150 $jsTitleClass = 'WT:' . $reqSet['title'];
151 if( $wgEnableScriptLoader ) {
152 // Extract any extra parameters (for now just skin)
153 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
154 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
155 $this->mScriptLoaderClassList
[] = $jsTitleClass . $ext_param ;
158 $this->addScript( Html
::linkedScript(
159 wfAppendQuery( $path, $this->getURIDparam( $jsTitleClass ) )
166 // If the script loader could not be used, just add the script to the header
167 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
171 * Add the core scripts that are included on every page, for later output into the header
173 * this includes the conditional sitejs
175 function addCoreScripts2Top(){
176 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
177 global $wgUser, $wgJsMimeType;
178 // @todo We should deprecate wikibits in favor of some mv_embed pieces and jQuery
180 if( $wgEnableJS2system ){
181 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
183 $core_classes = array( 'wikibits' );
186 //make sure scripts are on top:
187 $postScripts = $this->mScripts
;
188 $this->mScripts
= '';
190 if( $wgEnableScriptLoader ){
191 //directly add script_loader call for addCoreScripts2Top
192 $this->mScripts
= $this->getScriptLoaderJs( $core_classes );
195 foreach( $core_classes as $js_class ){
196 $this->addScriptClass( $js_class );
199 //now re-append any scripts that got added prior to the addCoreScripts2Top call
200 $this->mScripts
= $this->mScripts
. $postScripts;
204 * @param string $js_class Name of the JavaScript class
205 * @return boolean False if the class wasn't found, true on success
207 function addScriptClass( $js_class ){
208 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
209 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath, $wgStylePath, $wgEnableJS2system;
211 $path = jsScriptLoader
::getJsPathFromClass( $js_class );
212 if( $path !== false ){
213 if( $wgEnableScriptLoader ) {
214 // Register it with the script loader
215 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ) {
216 $this->mScriptLoaderClassList
[] = $js_class;
219 // Source the script directly
220 $prefix = "skins/common/";
221 if( substr( $path, 0, 1 ) == '/' ) {
223 } elseif( substr( $path, 0, strlen( $prefix ) ) == $prefix ) {
224 // Respect $wgStypePath
225 $path = "{$wgStylePath}/common/" . substr( $path, strlen( $prefix ) );
227 $path = $wgScriptPath . '/' . $path;
229 $this->addScript( Html
::linkedScript( $path . "?" . $this->getURIDparam( $js_class ) ) );
231 // Merge in language text (if js2 is on and we have loadGM function & scriptLoader is "off")
232 if( $wgEnableJS2system ){
233 if( !$this->mScriptLoader
)
234 $this->mScriptLoader
= new jsScriptLoader();
236 $inlineMsg = $this->mScriptLoader
->getInlineLoadGMFromClass( $js_class );
237 if( $inlineMsg != '' )
238 $this->addScript( Html
::inlineScript( $inlineMsg ));
243 //print "could not find: $js_class\n";
244 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
245 return false; // could not find the class
249 * Get the <script> tag which will invoke the script loader
250 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
252 function getScriptLoaderJs( $classAry = array() ) {
253 global $wgRequest, $wgDebugJavaScript;
254 // If no class array was provided, use mScriptLoaderClassList
255 if( !count( $classAry ) ) {
256 $classAry = $this->mScriptLoaderClassList
;
258 $class_list = implode( ',', $classAry );
260 $debug_param = ( $wgDebugJavaScript ||
261 $wgRequest->getVal( 'debug' ) == 'true' ||
262 $wgRequest->getVal( 'debug' ) == '1' )
263 ?
'&debug=true' : '';
265 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
266 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) ) . "\n";
270 * Get the unique request ID parameter for the script-loader request
272 function getURIDparam( $classAry = array() ) {
273 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedFileCheck;
274 global $wgLang, $wgScriptModifiedMsgCheck;
276 //Always the language key param to keep urls distinct per language
277 $uriParam = 'uselang=' . $wgLang->getCode();
279 if( $wgDebugJavaScript ) {
280 return $uriParam . '&urid=' . time();
282 //support single class_name attr
283 if( gettype( $classAry) == 'string' ){
284 $classAry = array( $classAry );
287 foreach( $classAry as $class ) {
288 // Add the latest revision ID if the class set includes a WT (wiki title)
289 if( substr($class, 0, 3) == 'WT:'){
290 $title_str = substr($class, 3);
291 $t = Title
::newFromText( $title_str );
292 if( $t && $t->exists() ) {
293 if( $t->getLatestRevID() > $frev )
294 $frev = $t->getLatestRevID();
297 //check for file modified time:
298 if( $wgScriptModifiedFileCheck ) {
299 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
301 $cur_ftime = filemtime ( $IP ."/". $js_path );
302 if( $cur_ftime > $ftime )
308 //build the actual unique request id:
309 $uriParam = "&urid={$wgStyleVersion}";
311 // Add the file modification time if set
313 $uriParam .= "_" . $ftime;
315 //add the wiki rev id if set
317 $uriParam.= "_" . $frev;
319 //add the latest msg rev id if $wgScriptModifiedMsgCheck is enabled:
320 if( $wgScriptModifiedMsgCheck ){
321 $dbr = wfGetDB( DB_SLAVE
);
322 // Grab the latest mediaWiki msg rev id:
323 $res = $dbr->select( 'recentchanges',
325 array( 'rc_namespace'=> NS_MEDIAWIKI
),
327 array( 'ORDER BY' => 'rc_timestamp DESC', 'LIMIT' => 1 ,
328 'USE INDEX' => array('recentchanges' => 'rc_timestamp' )
331 if( $dbr->numRows($res) != 0){
332 $rc = $dbr->fetchObject( $res );
334 $uriParam.= '_' . $rc->rc_id
;
337 //@@todo we could otherwise use the the SVN version if not already covered by $wgStyleVersion above
343 * Given a script path, get the JS class name, or false if no such path is registered.
344 * @param $path string
346 function getJsClassFromPath( $path ) {
347 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
349 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
350 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
351 $js_path = "{$wgScriptPath}/{$js_path}";
352 if( $path == $js_path )
359 * Add a self-contained script tag with the given contents
360 * @param string $script JavaScript text, no <script> tags
362 function addInlineScript( $script ) {
363 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
367 * Get all registered JS and CSS tags for the header.
369 function getScript() {
370 global $wgEnableScriptLoader;
371 if( $wgEnableScriptLoader ){
372 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
374 return $this->mScripts
. $this->getHeadItems();
378 function getHeadItems() {
380 foreach ( $this->mHeadItems
as $item ) {
386 function addHeadItem( $name, $value ) {
387 $this->mHeadItems
[$name] = $value;
390 function hasHeadItem( $name ) {
391 return isset( $this->mHeadItems
[$name] );
394 function setETag($tag) { $this->mETag
= $tag; }
395 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
396 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
398 function addLink( $linkarr ) {
399 # $linkarr should be an associative array of attributes. We'll escape on output.
400 array_push( $this->mLinktags
, $linkarr );
403 # Get all links added by extensions
404 function getExtStyle() {
405 return $this->mExtStyles
;
408 function addMetadataLink( $linkarr ) {
409 # note: buggy CC software only reads first "meta" link
410 static $haveMeta = false;
411 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
412 $this->addLink( $linkarr );
417 * checkLastModified tells the client to use the client-cached page if
418 * possible. If sucessful, the OutputPage is disabled so that
419 * any future call to OutputPage->output() have no effect.
421 * Side effect: sets mLastModified for Last-Modified header
423 * @return bool True iff cache-ok headers was sent.
425 function checkLastModified( $timestamp ) {
426 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
428 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
429 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
432 if( !$wgCachePages ) {
433 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
436 if( $wgUser->getOption( 'nocache' ) ) {
437 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
441 $timestamp = wfTimestamp( TS_MW
, $timestamp );
442 $modifiedTimes = array(
443 'page' => $timestamp,
444 'user' => $wgUser->getTouched(),
445 'epoch' => $wgCacheEpoch
447 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
449 $maxModified = max( $modifiedTimes );
450 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
452 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
453 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
459 foreach ( $modifiedTimes as $name => $value ) {
460 if ( $info !== '' ) {
463 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
466 # IE sends sizes after the date like this:
467 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
468 # this breaks strtotime().
469 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
471 wfSuppressWarnings(); // E_STRICT system time bitching
472 $clientHeaderTime = strtotime( $clientHeader );
474 if ( !$clientHeaderTime ) {
475 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
478 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
480 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
481 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
482 wfDebug( __METHOD__
. ": effective Last-Modified: " .
483 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
484 if( $clientHeaderTime < $maxModified ) {
485 wfDebug( __METHOD__
. ": STALE, $info\n", false );
490 # Give a 304 response code and disable body output
491 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
492 ini_set('zlib.output_compression', 0);
493 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
494 $this->sendCacheControl();
497 // Don't output a compressed blob when using ob_gzhandler;
498 // it's technically against HTTP spec and seems to confuse
499 // Firefox when the response gets split over two packets.
500 wfClearOutputBuffers();
505 function setPageTitleActionText( $text ) {
506 $this->mPageTitleActionText
= $text;
509 function getPageTitleActionText () {
510 if ( isset( $this->mPageTitleActionText
) ) {
511 return $this->mPageTitleActionText
;
516 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
518 * @param $policy string The literal string to output as the contents of
519 * the meta tag. Will be parsed according to the spec and output in
523 public function setRobotPolicy( $policy ) {
524 $policy = Article
::formatRobotPolicy( $policy );
526 if( isset( $policy['index'] ) ){
527 $this->setIndexPolicy( $policy['index'] );
529 if( isset( $policy['follow'] ) ){
530 $this->setFollowPolicy( $policy['follow'] );
535 * Set the index policy for the page, but leave the follow policy un-
538 * @param $policy string Either 'index' or 'noindex'.
541 public function setIndexPolicy( $policy ) {
542 $policy = trim( $policy );
543 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
544 $this->mIndexPolicy
= $policy;
549 * Set the follow policy for the page, but leave the index policy un-
552 * @param $policy string Either 'follow' or 'nofollow'.
555 public function setFollowPolicy( $policy ) {
556 $policy = trim( $policy );
557 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
558 $this->mFollowPolicy
= $policy;
563 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
565 public function setHTMLTitle( $name ) {
566 $this->mHTMLtitle
= $name;
570 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
571 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
572 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
573 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
575 public function setPageTitle( $name ) {
577 $name = $wgContLang->convert( $name, true );
578 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
579 # but leave "<i>foobar</i>" alone
580 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
581 $this->mPagetitle
= $nameWithTags;
583 $taction = $this->getPageTitleActionText();
584 if( !empty( $taction ) ) {
585 $name .= ' - '.$taction;
588 # change "<i>foo&bar</i>" to "foo&bar"
589 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
592 public function setTitle( $t ) {
596 public function getTitle() {
597 if ( $this->mTitle
instanceof Title
) {
598 return $this->mTitle
;
601 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
607 public function getHTMLTitle() { return $this->mHTMLtitle
; }
608 public function getPageTitle() { return $this->mPagetitle
; }
609 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
610 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
611 public function getSubtitle() { return $this->mSubtitle
; }
612 public function isArticle() { return $this->mIsarticle
; }
613 public function setPrintable() { $this->mPrintable
= true; }
614 public function isPrintable() { return $this->mPrintable
; }
615 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
616 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
617 public function getOnloadHandler() { return $this->mOnloadHandler
; }
618 public function disable() { $this->mDoNothing
= true; }
619 public function isDisabled() { return $this->mDoNothing
; }
621 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
623 public function setFeedAppendQuery( $val ) {
624 global $wgFeedClasses;
626 $this->mFeedLinks
= array();
628 foreach( $wgFeedClasses as $type => $class ) {
629 $query = "feed=$type&".$val;
630 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
634 public function addFeedLink( $format, $href ) {
635 $this->mFeedLinks
[$format] = $href;
638 public function isSyndicated() { return count($this->mFeedLinks
); }
640 public function setArticleRelated( $v ) {
641 $this->mIsArticleRelated
= $v;
643 $this->mIsarticle
= false;
646 public function setArticleFlag( $v ) {
647 $this->mIsarticle
= $v;
649 $this->mIsArticleRelated
= $v;
653 public function isArticleRelated() { return $this->mIsArticleRelated
; }
655 public function getLanguageLinks() { return $this->mLanguageLinks
; }
656 public function addLanguageLinks($newLinkArray) {
657 $this->mLanguageLinks +
= $newLinkArray;
659 public function setLanguageLinks($newLinkArray) {
660 $this->mLanguageLinks
= $newLinkArray;
663 public function getCategoryLinks() {
664 return $this->mCategoryLinks
;
668 * Add an array of categories, with names in the keys
670 public function addCategoryLinks( $categories ) {
671 global $wgUser, $wgContLang;
673 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
677 # Add the links to a LinkBatch
678 $arr = array( NS_CATEGORY
=> $categories );
680 $lb->setArray( $arr );
682 # Fetch existence plus the hiddencat property
683 $dbr = wfGetDB( DB_SLAVE
);
684 $pageTable = $dbr->tableName( 'page' );
685 $where = $lb->constructSet( 'page', $dbr );
686 $propsTable = $dbr->tableName( 'page_props' );
687 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
688 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
689 $res = $dbr->query( $sql, __METHOD__
);
691 # Add the results to the link cache
692 $lb->addResultToCache( LinkCache
::singleton(), $res );
694 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
695 $categories = array_combine( array_keys( $categories ),
696 array_fill( 0, count( $categories ), 'normal' ) );
698 # Mark hidden categories
699 foreach ( $res as $row ) {
700 if ( isset( $row->pp_value
) ) {
701 $categories[$row->page_title
] = 'hidden';
705 # Add the remaining categories to the skin
706 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
707 $sk = $wgUser->getSkin();
708 foreach ( $categories as $category => $type ) {
709 $origcategory = $category;
710 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
711 $wgContLang->findVariantLink( $category, $title, true );
712 if ( $category != $origcategory )
713 if ( array_key_exists( $category, $categories ) )
715 $text = $wgContLang->convertHtml( $title->getText() );
716 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
721 public function setCategoryLinks($categories) {
722 $this->mCategoryLinks
= array();
723 $this->addCategoryLinks($categories);
726 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
727 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
729 public function disallowUserJs() { $this->mAllowUserJs
= false; }
730 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
732 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
733 public function addHTML( $text ) { $this->mBodytext
.= $text; }
734 public function clearHTML() { $this->mBodytext
= ''; }
735 public function getHTML() { return $this->mBodytext
; }
736 public function debug( $text ) { $this->mDebugtext
.= $text; }
739 public function setParserOptions( $options ) {
740 wfDeprecated( __METHOD__
);
741 return $this->parserOptions( $options );
744 public function parserOptions( $options = null ) {
745 if ( !$this->mParserOptions
) {
746 $this->mParserOptions
= new ParserOptions
;
748 return wfSetVar( $this->mParserOptions
, $options );
752 * Set the revision ID which will be seen by the wiki text parser
753 * for things such as embedded {{REVISIONID}} variable use.
754 * @param mixed $revid an integer, or NULL
755 * @return mixed previous value
757 public function setRevisionId( $revid ) {
758 $val = is_null( $revid ) ?
null : intval( $revid );
759 return wfSetVar( $this->mRevisionId
, $val );
762 public function getRevisionId() {
763 return $this->mRevisionId
;
767 * Convert wikitext to HTML and add it to the buffer
768 * Default assumes that the current page title will
771 * @param string $text
772 * @param bool $linestart
774 public function addWikiText( $text, $linestart = true ) {
775 $title = $this->getTitle(); // Work arround E_STRICT
776 $this->addWikiTextTitle( $text, $title, $linestart );
779 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
780 $this->addWikiTextTitle($text, $title, $linestart);
783 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
784 $this->addWikiTextTitle( $text, $title, $linestart, true );
787 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
790 wfProfileIn( __METHOD__
);
792 wfIncrStats( 'pcache_not_possible' );
794 $popts = $this->parserOptions();
795 $oldTidy = $popts->setTidy( $tidy );
797 $parserOutput = $wgParser->parse( $text, $title, $popts,
798 $linestart, true, $this->mRevisionId
);
800 $popts->setTidy( $oldTidy );
802 $this->addParserOutput( $parserOutput );
804 wfProfileOut( __METHOD__
);
809 * @param ParserOutput object &$parserOutput
811 public function addParserOutputNoText( &$parserOutput ) {
812 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
814 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
815 $this->addCategoryLinks( $parserOutput->getCategories() );
816 $this->mNewSectionLink
= $parserOutput->getNewSection();
817 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
819 $this->mParseWarnings
= $parserOutput->getWarnings();
820 if ( $parserOutput->getCacheTime() == -1 ) {
821 $this->enableClientCache( false );
823 $this->mNoGallery
= $parserOutput->getNoGallery();
824 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
826 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
827 if ( isset( $this->mTemplateIds
[$ns] ) ) {
828 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
830 $this->mTemplateIds
[$ns] = $dbks;
834 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
835 $this->setPageTitle( $dt );
836 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
837 $this->setPageTitle( $title );
839 // Hooks registered in the object
840 global $wgParserOutputHooks;
841 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
842 list( $hookName, $data ) = $hookInfo;
843 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
844 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
848 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
853 * @param ParserOutput &$parserOutput
855 function addParserOutput( &$parserOutput ) {
856 $this->addParserOutputNoText( $parserOutput );
857 $text = $parserOutput->getText();
858 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
859 $this->addHTML( $text );
863 * Add wikitext to the buffer, assuming that this is the primary text for a page view
864 * Saves the text into the parser cache if possible.
866 * @param string $text
867 * @param Article $article
869 * @deprecated Use Article::outputWikitext
871 public function addPrimaryWikiText( $text, $article, $cache = true ) {
874 wfDeprecated( __METHOD__
);
876 $popts = $this->parserOptions();
877 $popts->setTidy(true);
878 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
879 $popts, true, true, $this->mRevisionId
);
880 $popts->setTidy(false);
881 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
882 $parserCache = ParserCache
::singleton();
883 $parserCache->save( $parserOutput, $article, $popts);
886 $this->addParserOutput( $parserOutput );
890 * @deprecated use addWikiTextTidy()
892 public function addSecondaryWikiText( $text, $linestart = true ) {
893 wfDeprecated( __METHOD__
);
894 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
898 * Add wikitext with tidy enabled
900 public function addWikiTextTidy( $text, $linestart = true ) {
901 $title = $this->getTitle();
902 $this->addWikiTextTitleTidy($text, $title, $linestart);
907 * Add the output of a QuickTemplate to the output buffer
909 * @param QuickTemplate $template
911 public function addTemplate( &$template ) {
913 $template->execute();
914 $this->addHTML( ob_get_contents() );
919 * Parse wikitext and return the HTML.
921 * @param string $text
922 * @param bool $linestart Is this the start of a line?
923 * @param bool $interface ??
925 public function parse( $text, $linestart = true, $interface = false ) {
927 if( is_null( $this->getTitle() ) ) {
928 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
930 $popts = $this->parserOptions();
931 if ( $interface) { $popts->setInterfaceMessage(true); }
932 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
933 $linestart, true, $this->mRevisionId
);
934 if ( $interface) { $popts->setInterfaceMessage(false); }
935 return $parserOutput->getText();
938 /** Parse wikitext, strip paragraphs, and return the HTML. */
939 public function parseInline( $text, $linestart = true, $interface = false ) {
940 $parsed = $this->parse( $text, $linestart, $interface );
943 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
951 * @param Article $article
956 * @return bool True if successful, else false.
958 public function tryParserCache( &$article ) {
959 wfDeprecated( __METHOD__
);
960 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
962 if ($parserOutput !== false) {
963 $this->addParserOutput( $parserOutput );
971 * @param int $maxage Maximum cache time on the Squid, in seconds.
973 public function setSquidMaxage( $maxage ) {
974 $this->mSquidMaxage
= $maxage;
978 * Use enableClientCache(false) to force it to send nocache headers
981 public function enableClientCache( $state ) {
982 return wfSetVar( $this->mEnableClientCache
, $state );
985 function getCacheVaryCookies() {
986 global $wgCookiePrefix, $wgCacheVaryCookies;
988 if ( $cookies === null ) {
989 $cookies = array_merge(
991 "{$wgCookiePrefix}Token",
992 "{$wgCookiePrefix}LoggedOut",
997 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
1002 function uncacheableBecauseRequestVars() {
1004 return $wgRequest->getText('useskin', false) === false
1005 && $wgRequest->getText('uselang', false) === false;
1009 * Check if the request has a cache-varying cookie header
1010 * If it does, it's very important that we don't allow public caching
1012 function haveCacheVaryCookies() {
1014 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1015 if ( $cookieHeader === false ) {
1018 $cvCookies = $this->getCacheVaryCookies();
1019 foreach ( $cvCookies as $cookieName ) {
1020 # Check for a simple string match, like the way squid does it
1021 if ( strpos( $cookieHeader, $cookieName ) ) {
1022 wfDebug( __METHOD__
.": found $cookieName\n" );
1026 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
1030 /** Get a complete X-Vary-Options header */
1031 public function getXVO() {
1032 $cvCookies = $this->getCacheVaryCookies();
1033 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
1035 foreach ( $cvCookies as $cookieName ) {
1041 $xvo .= 'string-contains=' . $cookieName;
1046 public function sendCacheControl() {
1047 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1049 $response = $wgRequest->response();
1050 if ($wgUseETag && $this->mETag
)
1051 $response->header("ETag: $this->mETag");
1053 # don't serve compressed data to clients who can't handle it
1054 # maintain different caches for logged-in users and non-logged in ones
1055 $response->header( 'Vary: Accept-Encoding, Cookie' );
1058 # Add an X-Vary-Options header for Squid with Wikimedia patches
1059 $response->header( $this->getXVO() );
1062 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1063 if( $wgUseSquid && session_id() == '' &&
1064 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1067 # We'll purge the proxy cache explicitly, but require end user agents
1068 # to revalidate against the proxy on each visit.
1069 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1070 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1071 # start with a shorter timeout for initial testing
1072 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1073 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1074 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1076 # We'll purge the proxy cache for anons explicitly, but require end user agents
1077 # to revalidate against the proxy on each visit.
1078 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1079 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1080 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1081 # start with a shorter timeout for initial testing
1082 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1083 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1086 # We do want clients to cache if they can, but they *must* check for updates
1087 # on revisiting the page.
1088 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1089 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1090 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1092 if($this->mLastModified
) {
1093 $response->header( "Last-Modified: {$this->mLastModified}" );
1096 wfDebug( __METHOD__
. ": no caching **\n", false );
1098 # In general, the absence of a last modified header should be enough to prevent
1099 # the client from using its cache. We send a few other things just to make sure.
1100 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1101 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1102 $response->header( 'Pragma: no-cache' );
1107 * Finally, all the text has been munged and accumulated into
1108 * the object, let's actually output it:
1110 public function output() {
1111 global $wgUser, $wgOutputEncoding, $wgRequest;
1112 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1113 global $wgUseAjax, $wgAjaxWatch;
1114 global $wgEnableMWSuggest, $wgUniversalEditButton;
1117 if( $this->mDoNothing
){
1120 wfProfileIn( __METHOD__
);
1121 if ( '' != $this->mRedirect
) {
1122 # Standards require redirect URLs to be absolute
1123 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1124 if( $this->mRedirectCode
== '301') {
1125 if( !$wgDebugRedirects ) {
1126 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1128 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1130 $this->sendCacheControl();
1132 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1133 if( $wgDebugRedirects ) {
1134 $url = htmlspecialchars( $this->mRedirect
);
1135 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1136 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1137 print "</body>\n</html>\n";
1139 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1141 wfProfileOut( __METHOD__
);
1144 elseif ( $this->mStatusCode
)
1146 $statusMessage = array(
1148 101 => 'Switching Protocols',
1149 102 => 'Processing',
1153 203 => 'Non-Authoritative Information',
1154 204 => 'No Content',
1155 205 => 'Reset Content',
1156 206 => 'Partial Content',
1157 207 => 'Multi-Status',
1158 300 => 'Multiple Choices',
1159 301 => 'Moved Permanently',
1162 304 => 'Not Modified',
1164 307 => 'Temporary Redirect',
1165 400 => 'Bad Request',
1166 401 => 'Unauthorized',
1167 402 => 'Payment Required',
1170 405 => 'Method Not Allowed',
1171 406 => 'Not Acceptable',
1172 407 => 'Proxy Authentication Required',
1173 408 => 'Request Timeout',
1176 411 => 'Length Required',
1177 412 => 'Precondition Failed',
1178 413 => 'Request Entity Too Large',
1179 414 => 'Request-URI Too Large',
1180 415 => 'Unsupported Media Type',
1181 416 => 'Request Range Not Satisfiable',
1182 417 => 'Expectation Failed',
1183 422 => 'Unprocessable Entity',
1185 424 => 'Failed Dependency',
1186 500 => 'Internal Server Error',
1187 501 => 'Not Implemented',
1188 502 => 'Bad Gateway',
1189 503 => 'Service Unavailable',
1190 504 => 'Gateway Timeout',
1191 505 => 'HTTP Version Not Supported',
1192 507 => 'Insufficient Storage'
1195 if ( $statusMessage[$this->mStatusCode
] )
1196 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1199 $sk = $wgUser->getSkin();
1201 // Add our core scripts to output
1202 $this->addCoreScripts2Top();
1205 $this->addScriptFile( 'ajax.js' );
1207 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1209 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1210 $this->addScriptFile( 'ajaxwatch.js' );
1213 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1214 $this->addScriptFile( 'mwsuggest.js' );
1218 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1219 $this->addScriptFile( 'rightclickedit.js' );
1222 global $wgUseAJAXCategories, $wgEnableJS2system;
1223 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1224 global $wgAJAXCategoriesNamespaces;
1226 $title = $this->getTitle();
1228 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1229 $this->addScriptClass( 'ajaxCategories' );
1233 if( $wgUniversalEditButton ) {
1234 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1235 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1236 // Original UniversalEditButton
1237 $msg = wfMsg('edit');
1238 $this->addLink( array(
1239 'rel' => 'alternate',
1240 'type' => 'application/x-wiki',
1242 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1244 // Alternate edit link
1245 $this->addLink( array(
1248 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1253 # Buffer output; final headers may depend on later processing
1256 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1257 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1259 if ($this->mArticleBodyOnly
) {
1260 $this->out($this->mBodytext
);
1262 // Hook that allows last minute changes to the output page, e.g.
1263 // adding of CSS or Javascript by extensions.
1264 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1266 wfProfileIn( 'Output-skin' );
1267 $sk->outputPage( $this );
1268 wfProfileOut( 'Output-skin' );
1271 $this->sendCacheControl();
1273 wfProfileOut( __METHOD__
);
1277 * Actually output something with print(). Performs an iconv to the
1278 * output encoding, if needed.
1279 * @param string $ins The string to output
1281 public function out( $ins ) {
1282 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1283 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1286 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1287 if ( false === $outs ) { $outs = $ins; }
1295 public static function setEncodings() {
1296 global $wgInputEncoding, $wgOutputEncoding;
1299 $wgInputEncoding = strtolower( $wgInputEncoding );
1301 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1302 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1305 $wgOutputEncoding = $wgInputEncoding;
1309 * Deprecated, use wfReportTime() instead.
1313 public function reportTime() {
1314 wfDeprecated( __METHOD__
);
1315 $time = wfReportTime();
1320 * Produce a "user is blocked" page.
1322 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1325 function blockedPage( $return = true ) {
1326 global $wgUser, $wgContLang, $wgLang;
1328 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1329 $this->setRobotPolicy( 'noindex,nofollow' );
1330 $this->setArticleRelated( false );
1332 $name = User
::whoIs( $wgUser->blockedBy() );
1333 $reason = $wgUser->blockedFor();
1334 if( $reason == '' ) {
1335 $reason = wfMsg( 'blockednoreason' );
1337 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1340 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1342 $blockid = $wgUser->mBlock
->mId
;
1344 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1345 if ( $blockExpiry == 'infinity' ) {
1346 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1347 // Search for localization in 'ipboptions'
1348 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1349 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1350 if ( strpos( $option, ":" ) === false )
1352 list( $show, $value ) = explode( ":", $option );
1353 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1354 $blockExpiry = $show;
1359 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1362 if ( $wgUser->mBlock
->mAuto
) {
1363 $msg = 'autoblockedtext';
1365 $msg = 'blockedtext';
1368 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1369 * This could be a username, an ip range, or a single ip. */
1370 $intended = $wgUser->mBlock
->mAddress
;
1372 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1374 # Don't auto-return to special pages
1376 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1377 $this->returnToMain( null, $return );
1382 * Output a standard error page
1384 * @param string $title Message key for page title
1385 * @param string $msg Message key for page text
1386 * @param array $params Message parameters
1388 public function showErrorPage( $title, $msg, $params = array() ) {
1389 if ( $this->getTitle() ) {
1390 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1392 $this->setPageTitle( wfMsg( $title ) );
1393 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1394 $this->setRobotPolicy( 'noindex,nofollow' );
1395 $this->setArticleRelated( false );
1396 $this->enableClientCache( false );
1397 $this->mRedirect
= '';
1398 $this->mBodytext
= '';
1400 array_unshift( $params, 'parse' );
1401 array_unshift( $params, $msg );
1402 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1404 $this->returnToMain();
1408 * Output a standard permission error page
1410 * @param array $errors Error message keys
1412 public function showPermissionsErrorPage( $errors, $action = null )
1414 $this->mDebugtext
.= 'Original title: ' .
1415 $this->getTitle()->getPrefixedText() . "\n";
1416 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1417 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1418 $this->setRobotPolicy( 'noindex,nofollow' );
1419 $this->setArticleRelated( false );
1420 $this->enableClientCache( false );
1421 $this->mRedirect
= '';
1422 $this->mBodytext
= '';
1423 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1427 public function errorpage( $title, $msg ) {
1428 wfDeprecated( __METHOD__
);
1429 throw new ErrorPageError( $title, $msg );
1433 * Display an error page indicating that a given version of MediaWiki is
1434 * required to use it
1436 * @param mixed $version The version of MediaWiki needed to use the page
1438 public function versionRequired( $version ) {
1439 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1440 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1441 $this->setRobotPolicy( 'noindex,nofollow' );
1442 $this->setArticleRelated( false );
1443 $this->mBodytext
= '';
1445 $this->addWikiMsg( 'versionrequiredtext', $version );
1446 $this->returnToMain();
1450 * Display an error page noting that a given permission bit is required.
1452 * @param string $permission key required
1454 public function permissionRequired( $permission ) {
1457 $this->setPageTitle( wfMsg( 'badaccess' ) );
1458 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1459 $this->setRobotPolicy( 'noindex,nofollow' );
1460 $this->setArticleRelated( false );
1461 $this->mBodytext
= '';
1463 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1464 User
::getGroupsWithPermission( $permission ) );
1466 $this->addWikiMsg( 'badaccess-groups',
1467 $wgLang->commaList( $groups ),
1470 $this->addWikiMsg( 'badaccess-group0' );
1472 $this->returnToMain();
1476 * Use permissionRequired.
1479 public function sysopRequired() {
1480 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1484 * Use permissionRequired.
1487 public function developerRequired() {
1488 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1492 * Produce the stock "please login to use the wiki" page
1494 public function loginToUse() {
1495 global $wgUser, $wgContLang;
1497 if( $wgUser->isLoggedIn() ) {
1498 $this->permissionRequired( 'read' );
1502 $skin = $wgUser->getSkin();
1504 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1505 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1506 $this->setRobotPolicy( 'noindex,nofollow' );
1507 $this->setArticleFlag( false );
1509 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1510 $loginLink = $skin->link(
1512 wfMsgHtml( 'loginreqlink' ),
1514 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1515 array( 'known', 'noclasses' )
1517 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1518 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1520 # Don't return to the main page if the user can't read it
1521 # otherwise we'll end up in a pointless loop
1522 $mainPage = Title
::newMainPage();
1523 if( $mainPage->userCanRead() )
1524 $this->returnToMain( null, $mainPage );
1528 public function databaseError( $fname, $sql, $error, $errno ) {
1529 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1533 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1534 * @return string The wikitext error-messages, formatted into a list.
1536 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1537 if ($action == null) {
1538 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1541 $action_desc = wfMsgNoTrans( "action-$action" );
1542 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1545 if (count( $errors ) > 1) {
1546 $text .= '<ul class="permissions-errors">' . "\n";
1548 foreach( $errors as $error )
1551 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1556 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1563 * Display a page stating that the Wiki is in read-only mode,
1564 * and optionally show the source of the page that the user
1565 * was trying to edit. Should only be called (for this
1566 * purpose) after wfReadOnly() has returned true.
1568 * For historical reasons, this function is _also_ used to
1569 * show the error message when a user tries to edit a page
1570 * they are not allowed to edit. (Unless it's because they're
1571 * blocked, then we show blockedPage() instead.) In this
1572 * case, the second parameter should be set to true and a list
1573 * of reasons supplied as the third parameter.
1575 * @todo Needs to be split into multiple functions.
1577 * @param string $source Source code to show (or null).
1578 * @param bool $protected Is this a permissions error?
1579 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1581 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1583 $skin = $wgUser->getSkin();
1585 $this->setRobotPolicy( 'noindex,nofollow' );
1586 $this->setArticleRelated( false );
1588 // If no reason is given, just supply a default "I can't let you do
1589 // that, Dave" message. Should only occur if called by legacy code.
1590 if ( $protected && empty($reasons) ) {
1591 $reasons[] = array( 'badaccess-group0' );
1594 if ( !empty($reasons) ) {
1595 // Permissions error
1597 $this->setPageTitle( wfMsg( 'viewsource' ) );
1606 array( 'known', 'noclasses' )
1611 $this->setPageTitle( wfMsg( 'badaccess' ) );
1613 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1615 // Wiki is read only
1616 $this->setPageTitle( wfMsg( 'readonly' ) );
1617 $reason = wfReadOnlyReason();
1618 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1621 // Show source, if supplied
1622 if( is_string( $source ) ) {
1623 $this->addWikiMsg( 'viewsourcetext' );
1626 'id' => 'wpTextbox1',
1627 'name' => 'wpTextbox1',
1628 'cols' => $wgUser->getOption( 'cols' ),
1629 'rows' => $wgUser->getOption( 'rows' ),
1630 'readonly' => 'readonly'
1632 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1634 // Show templates used by this article
1635 $skin = $wgUser->getSkin();
1636 $article = new Article( $this->getTitle() );
1637 $this->addHTML( "<div class='templatesUsed'>
1638 {$skin->formatTemplates( $article->getUsedTemplates() )}
1643 # If the title doesn't exist, it's fairly pointless to print a return
1644 # link to it. After all, you just tried editing it and couldn't, so
1645 # what's there to do there?
1646 if( $this->getTitle()->exists() ) {
1647 $this->returnToMain( null, $this->getTitle() );
1652 public function fatalError( $message ) {
1653 wfDeprecated( __METHOD__
);
1654 throw new FatalError( $message );
1658 public function unexpectedValueError( $name, $val ) {
1659 wfDeprecated( __METHOD__
);
1660 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1664 public function fileCopyError( $old, $new ) {
1665 wfDeprecated( __METHOD__
);
1666 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1670 public function fileRenameError( $old, $new ) {
1671 wfDeprecated( __METHOD__
);
1672 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1676 public function fileDeleteError( $name ) {
1677 wfDeprecated( __METHOD__
);
1678 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1682 public function fileNotFoundError( $name ) {
1683 wfDeprecated( __METHOD__
);
1684 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1687 public function showFatalError( $message ) {
1688 $this->setPageTitle( wfMsg( "internalerror" ) );
1689 $this->setRobotPolicy( "noindex,nofollow" );
1690 $this->setArticleRelated( false );
1691 $this->enableClientCache( false );
1692 $this->mRedirect
= '';
1693 $this->mBodytext
= $message;
1696 public function showUnexpectedValueError( $name, $val ) {
1697 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1700 public function showFileCopyError( $old, $new ) {
1701 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1704 public function showFileRenameError( $old, $new ) {
1705 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1708 public function showFileDeleteError( $name ) {
1709 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1712 public function showFileNotFoundError( $name ) {
1713 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1717 * Add a "return to" link pointing to a specified title
1719 * @param Title $title Title to link
1720 * @param string $query Query string
1722 public function addReturnTo( $title, $query = array() ) {
1724 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1725 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1726 $title, null, array(), $query ) );
1727 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1731 * Add a "return to" link pointing to a specified title,
1732 * or the title indicated in the request, or else the main page
1734 * @param null $unused No longer used
1735 * @param Title $returnto Title to return to
1737 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1740 if ( $returnto == null ) {
1741 $returnto = $wgRequest->getText( 'returnto' );
1744 if ( $returntoquery == null ) {
1745 $returntoquery = $wgRequest->getText( 'returntoquery' );
1748 if ( '' === $returnto ) {
1749 $returnto = Title
::newMainPage();
1752 if ( is_object( $returnto ) ) {
1753 $titleObj = $returnto;
1755 $titleObj = Title
::newFromText( $returnto );
1757 if ( !is_object( $titleObj ) ) {
1758 $titleObj = Title
::newMainPage();
1761 $this->addReturnTo( $titleObj, $returntoquery );
1765 * @return string The doctype, opening <html>, and head element.
1767 * @param $sk Skin The given Skin
1769 public function headElement( Skin
$sk, $includeStyle = true ) {
1770 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1771 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1772 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1774 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1775 if ( $sk->commonPrintStylesheet() ) {
1776 $this->addStyle( 'common/wikiprintable.css', 'print' );
1778 $sk->setupUserCss( $this );
1782 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1783 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1786 if ( '' == $this->getHTMLTitle() ) {
1787 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1790 $dir = $wgContLang->getDir();
1793 $ret .= "<!doctype html>\n";
1794 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1796 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1797 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1798 foreach($wgXhtmlNamespaces as $tag => $ns) {
1799 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1801 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1805 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1806 $ret .= implode( "\n", array(
1807 $this->getHeadLinks(),
1808 $this->buildCssLinks(),
1809 $this->getHeadScripts( $sk ),
1810 $this->getHeadItems(),
1813 $ret .= Html
::inlineStyle( $sk->usercss
);
1816 if( $wgEnableScriptLoader )
1817 $ret .= $this->getScriptLoaderJs();
1819 if ($wgUseTrackbacks && $this->isArticleRelated())
1820 $ret .= $this->getTitle()->trackbackRDF();
1822 $ret .= "</head>\n";
1827 * gets the global variables and mScripts
1829 * also adds userjs to the end if enabled:
1831 function getHeadScripts( Skin
$sk ) {
1832 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1834 $vars = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1836 //add site JS if enabled:
1837 if( $wgUseSiteJs ) {
1838 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1839 $this->addScriptFile( Skin
::makeUrl( '-',
1840 "action=raw$jsCache&gen=js&useskin=" .
1841 urlencode( $sk->getSkinName() )
1846 //add user js if enabled:
1847 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1848 $action = $wgRequest->getVal( 'action', 'view' );
1849 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1850 # XXX: additional security check/prompt?
1851 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1853 $userpage = $wgUser->getUserPage();
1854 $userjs = Skin
::makeUrl(
1855 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1856 'action=raw&ctype=' . $wgJsMimeType );
1857 $this->addScriptFile( $userjs );
1861 return $vars . "\n" . $this->mScripts
;
1864 protected function addDefaultMeta() {
1865 global $wgVersion, $wgHtml5;
1867 static $called = false;
1869 # Don't run this twice
1875 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1877 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1879 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1880 if( $p !== 'index,follow' ) {
1881 // http://www.robotstxt.org/wc/meta-user.html
1882 // Only show if it's different from the default robots policy
1883 $this->addMeta( 'robots', $p );
1886 if ( count( $this->mKeywords
) > 0 ) {
1888 "/<.*?" . ">/" => '',
1891 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1896 * @return string HTML tag links to be put in the header.
1898 public function getHeadLinks() {
1899 global $wgRequest, $wgFeed;
1901 // Ideally this should happen earlier, somewhere. :P
1902 $this->addDefaultMeta();
1906 foreach ( $this->mMetatags
as $tag ) {
1907 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1909 $tag[0] = substr( $tag[0], 5 );
1913 $tags[] = Html
::element( 'meta',
1916 'content' => $tag[1] ) );
1918 foreach ( $this->mLinktags
as $tag ) {
1919 $tags[] = Html
::element( 'link', $tag );
1923 foreach( $this->getSyndicationLinks() as $format => $link ) {
1924 # Use the page name for the title (accessed through $wgTitle since
1925 # there's no other way). In principle, this could lead to issues
1926 # with having the same name for different feeds corresponding to
1927 # the same page, but we can't avoid that at this low a level.
1929 $tags[] = $this->feedLink(
1932 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1935 # Recent changes feed should appear on every page (except recentchanges,
1936 # that would be redundant). Put it after the per-page feed to avoid
1937 # changing existing behavior. It's still available, probably via a
1938 # menu in your browser. Some sites might have a different feed they'd
1939 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1940 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1941 # If so, use it instead.
1943 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1944 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1946 if ( $wgOverrideSiteFeed ) {
1947 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1948 $tags[] = $this->feedLink (
1950 htmlspecialchars( $feedUrl ),
1951 wfMsg( "site-{$type}-feed", $wgSitename ) );
1954 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1955 foreach( $wgFeedClasses as $format => $class ) {
1956 $tags[] = $this->feedLink(
1958 $rctitle->getLocalURL( "feed={$format}" ),
1959 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1964 return implode( "\n", $tags );
1968 * Return URLs for each supported syndication format for this page.
1969 * @return array associating format keys with URLs
1971 public function getSyndicationLinks() {
1972 return $this->mFeedLinks
;
1976 * Generate a <link rel/> for an RSS feed.
1978 private function feedLink( $type, $url, $text ) {
1979 return Html
::element( 'link', array(
1980 'rel' => 'alternate',
1981 'type' => "application/$type+xml",
1987 * Add a local or specified stylesheet, with the given media options.
1988 * Meant primarily for internal use...
1990 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1991 * @param $conditional -- for IE conditional comments, specifying an IE version
1992 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1994 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1996 // Even though we expect the media type to be lowercase, but here we
1997 // force it to lowercase to be safe.
1999 $options['media'] = $media;
2001 $options['condition'] = $condition;
2003 $options['dir'] = $dir;
2004 $this->styles
[$style] = $options;
2008 * Adds inline CSS styles
2009 * @param $style_css Mixed: inline CSS
2011 public function addInlineStyle( $style_css ){
2012 $this->mScripts
.= Html
::inlineStyle( $style_css );
2016 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2017 * These will be applied to various media & IE conditionals.
2019 public function buildCssLinks() {
2021 foreach( $this->styles
as $file => $options ) {
2022 $link = $this->styleLink( $file, $options );
2027 return implode( "\n", $links );
2030 protected function styleLink( $style, $options ) {
2033 if( isset( $options['dir'] ) ) {
2035 $siteDir = $wgContLang->getDir();
2036 if( $siteDir != $options['dir'] )
2040 if( isset( $options['media'] ) ) {
2041 $media = $this->transformCssMedia( $options['media'] );
2042 if( is_null( $media ) ) {
2049 if( substr( $style, 0, 1 ) == '/' ||
2050 substr( $style, 0, 5 ) == 'http:' ||
2051 substr( $style, 0, 6 ) == 'https:' ) {
2054 global $wgStylePath, $wgStyleVersion;
2055 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2058 $link = Html
::linkedStyle( $url, $media );
2060 if( isset( $options['condition'] ) ) {
2061 $condition = htmlspecialchars( $options['condition'] );
2062 $link = "<!--[if $condition]>$link<![endif]-->";
2067 function transformCssMedia( $media ) {
2068 global $wgRequest, $wgHandheldForIPhone;
2070 // Switch in on-screen display for media testing
2072 'printable' => 'print',
2073 'handheld' => 'handheld',
2075 foreach( $switches as $switch => $targetMedia ) {
2076 if( $wgRequest->getBool( $switch ) ) {
2077 if( $media == $targetMedia ) {
2079 } elseif( $media == 'screen' ) {
2085 // Expand longer media queries as iPhone doesn't grok 'handheld'
2086 if( $wgHandheldForIPhone ) {
2087 $mediaAliases = array(
2088 'screen' => 'screen and (min-device-width: 481px)',
2089 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2092 if( isset( $mediaAliases[$media] ) ) {
2093 $media = $mediaAliases[$media];
2101 * Turn off regular page output and return an error reponse
2102 * for when rate limiting has triggered.
2104 public function rateLimited() {
2106 $this->setPageTitle(wfMsg('actionthrottled'));
2107 $this->setRobotPolicy( 'noindex,follow' );
2108 $this->setArticleRelated( false );
2109 $this->enableClientCache( false );
2110 $this->mRedirect
= '';
2112 $this->setStatusCode(503);
2113 $this->addWikiMsg( 'actionthrottledtext' );
2115 $this->returnToMain( null, $this->getTitle() );
2119 * Show an "add new section" link?
2123 public function showNewSectionLink() {
2124 return $this->mNewSectionLink
;
2128 * Forcibly hide the new section link?
2132 public function forceHideNewSectionLink() {
2133 return $this->mHideNewSectionLink
;
2137 * Show a warning about slave lag
2139 * If the lag is higher than $wgSlaveLagCritical seconds,
2140 * then the warning is a bit more obvious. If the lag is
2141 * lower than $wgSlaveLagWarning, then no warning is shown.
2143 * @param int $lag Slave lag
2145 public function showLagWarning( $lag ) {
2146 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2147 if( $lag >= $wgSlaveLagWarning ) {
2148 $message = $lag < $wgSlaveLagCritical
2151 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2152 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2157 * Add a wikitext-formatted message to the output.
2158 * This is equivalent to:
2160 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2162 public function addWikiMsg( /*...*/ ) {
2163 $args = func_get_args();
2164 $name = array_shift( $args );
2165 $this->addWikiMsgArray( $name, $args );
2169 * Add a wikitext-formatted message to the output.
2170 * Like addWikiMsg() except the parameters are taken as an array
2171 * instead of a variable argument list.
2173 * $options is passed through to wfMsgExt(), see that function for details.
2175 public function addWikiMsgArray( $name, $args, $options = array() ) {
2176 $options[] = 'parse';
2177 $text = wfMsgExt( $name, $options, $args );
2178 $this->addHTML( $text );
2182 * This function takes a number of message/argument specifications, wraps them in
2183 * some overall structure, and then parses the result and adds it to the output.
2185 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2186 * on. The subsequent arguments may either be strings, in which case they are the
2187 * message names, or arrays, in which case the first element is the message name,
2188 * and subsequent elements are the parameters to that message.
2190 * The special named parameter 'options' in a message specification array is passed
2191 * through to the $options parameter of wfMsgExt().
2193 * Don't use this for messages that are not in users interface language.
2197 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2201 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2203 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2204 $msgSpecs = func_get_args();
2205 array_shift( $msgSpecs );
2206 $msgSpecs = array_values( $msgSpecs );
2208 foreach ( $msgSpecs as $n => $spec ) {
2210 if ( is_array( $spec ) ) {
2212 $name = array_shift( $args );
2213 if ( isset( $args['options'] ) ) {
2214 $options = $args['options'];
2215 unset( $args['options'] );
2221 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2223 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );