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();
18 // the most recent id of any script that is grouped in the script request
19 var $mLatestScriptRevID = 0;
21 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = 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()
31 var $mShowFeedLinks = false;
32 var $mFeedLinksAppendQuery = false;
33 var $mEnableClientCache = true;
34 var $mArticleBodyOnly = false;
36 var $mNewSectionLink = false;
37 var $mHideNewSectionLink = false;
38 var $mNoGallery = false;
39 var $mPageTitleActionText = '';
40 var $mParseWarnings = array();
41 var $mSquidMaxage = 0;
42 var $mRevisionId = null;
43 protected $mTitle = null;
46 * An array of stylesheet filenames (relative from skins path), with options
47 * for CSS media, IE conditions, and RTL/LTR direction.
48 * For internal use; add settings in the skin via $this->addStyle()
50 var $styles = array();
52 private $mIndexPolicy = 'index';
53 private $mFollowPolicy = 'follow';
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= "\t\t" . $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
113 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url );
115 # type attribute is mandatory in XHTML 1.0 Transitional
116 $linkarr['type'] = 'text/css';
118 array_push( $this->mExtStyles
, $linkarr );
122 * Add a JavaScript file out of skins/common, or a given relative path.
123 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
125 function addScriptFile( $file ) {
126 global $wgStylePath, $wgStyleVersion, $wgJsMimeType, $wgScript, $wgUser, $wgHtml5;
127 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
129 if( substr( $file, 0, 1 ) == '/' ) {
132 $path = "{$wgStylePath}/common/{$file}";
135 if( $wgEnableScriptLoader ){
136 if( strpos( $path, $wgScript ) !== false ){
137 $reqPath = str_replace( $wgScript . '?', '', $path );
138 $reqArgs = explode( '&', $reqPath );
141 foreach( $reqArgs as $arg ){
142 list( $key, $var ) = explode( '=', $arg );
143 $reqSet[$key] = $var;
146 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
147 // extract any extra param (for now just skin)
148 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' ) ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
149 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
150 // add the title revision to the key
151 $t = Title
::newFromText( $reqSet['title'] );
152 // if there is no title (don't worry we just use the $wgStyleVersion var (which should be updated on relevant commits)
153 if( $t && $t->exists() ){
154 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
155 $this->mLatestScriptRevID
= $t->getLatestRevID();
161 // check for class from path:
162 $js_class = $this->getJsClassFromPath( $path );
164 // add to the class list:
165 $this->mScriptLoaderClassList
[] = $js_class;
170 // if the script loader did not find a way to add the script than add using addScript
171 $attrs = array( 'src' => wfAppendQuery( $path, $this->getURIDparam() ) );
173 $attrs['type'] = $wgJsMimeType;
175 $this->addScript( Xml
::element( 'script', $attrs, '', false ) );
179 * This is the core script that is included on every page
180 * (they are requested separately to improve caching across
181 * different page load types (edit, upload, view, etc)
183 function addCoreScripts2Top(){
184 global $wgEnableScriptLoader, $wgStyleVersion, $wgJSAutoloadLocalClasses,
185 $wgJsMimeType, $wgScriptPath, $wgEnableJS2system, $wgHtml5;
186 //@@todo we should deprecate wikibits in favor of mv_embed and native jQuery functions
188 if( $wgEnableJS2system ){
189 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
191 $core_classes = array( 'wikibits' );
194 if( $wgEnableScriptLoader ){
195 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
198 foreach( $core_classes as $s ){
199 if( isset( $wgJSAutoloadLocalClasses[$s] ) ){
200 $attrs = array( 'src' => "{$wgScriptPath}/{$wgJSAutoloadLocalClasses[$s]}?" . $this->getURIDparam() );
202 $attrs['type'] = $wgJsMimeType;
204 $so.= Xml
::element( 'script', $attrs, '', false );
207 $this->mScripts
= $so . $this->mScripts
;
212 * @param $js_class String: name of JavaScript class
213 * @return Boolean: false if class wasn't found, true on success
215 function addScriptClass( $js_class ){
216 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
217 $wgJsMimeType, $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath, $wgHtml5;
219 if( isset( $wgJSAutoloadClasses[$js_class] ) ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
220 if( $wgEnableScriptLoader ){
221 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ){
222 $this->mScriptLoaderClassList
[] = $js_class;
225 // do a normal load of without the script-loader:
226 $path = $wgScriptPath . '/';
227 if( isset( $wgJSAutoloadClasses[$js_class] ) ){
228 $path.= $wgJSAutoloadClasses[$js_class];
229 }else if( isset( $wgJSAutoloadLocalClasses[$js_class] ) ){
230 $path.= $wgJSAutoloadLocalClasses[$js_class];
232 $urlAppend = ( $wgDebugJavaScript) ?
time() : $wgStyleVersion;
233 $attrs = array( 'src' => "$path?$urlAppend" );
235 $attrs['type'] = $wgJsMimeType;
237 $this->addScript( Xml
::element( 'script', $attrs, '', false ) );
241 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
242 return false; // could not find the class
246 * gets the scriptLoader javascript include
247 * @param $forcClassAry Boolean: false by default
249 function getScriptLoaderJs( $forceClassAry = false ){
250 global $wgJsMimeType, $wgStyleVersion, $wgRequest, $wgDebugJavaScript, $wgHtml5;
252 if( !$forceClassAry ){
253 $class_list = implode( ',', $this->mScriptLoaderClassList
);
255 $class_list = implode( ',', $forceClassAry );
258 $debug_param = ( $wgDebugJavaScript ||
259 $wgRequest->getVal( 'debug' ) == 'true' ||
260 $wgRequest->getVal( 'debug' ) == '1' )
261 ?
'&debug=true' : '';
263 //@@todo intelligent unique id generation based on svn version of file (rather than just grabbing the $wgStyleVersion var)
264 //@@todo we should check the packaged message text in this javascript file for updates and update the $mScriptLoaderURID id (in getJsClassFromPath)
266 //generate the unique request param (combine with the most recent revision id of any wiki page with the $wgStyleVersion var)
268 $attrs = array( 'src' => wfScript( 'mwScriptLoader' ) . "?class={$class_list}{$debug_param}&".$this->getURIDparam() );
270 $attrs['type'] = $wgJsMimeType;
272 return Xml
::element( 'script', $attrs, '', false );
275 function getURIDparam(){
276 global $wgDebugJavaScript, $wgStyleVersion;
277 if( $wgDebugJavaScript ){
278 return 'urid=' . time();
280 return "urid={$wgStyleVersion}_{$this->mLatestScriptRevID}";
284 function getJsClassFromPath( $path ){
285 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
287 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
288 foreach( $scriptLoaderPaths as $js_class => $js_path ){
289 $js_path = "{$wgScriptPath}/{$js_path}";
290 if( $path == $js_path )
297 * Add a self-contained script tag with the given contents
298 * @param string $script JavaScript text, no <script> tags
300 function addInlineScript( $script ) {
301 global $wgJsMimeType, $wgHtml5;
302 $this->mScripts
.= "\t\t<script" . ($wgHtml5 ?
'' : " type=\"$wgJsMimeType\"")
303 . ">/*<![CDATA[*/\n\t\t$script\n\t\t/*]]>*/</script>\n";
306 function getScript() {
307 global $wgEnableScriptLoader;
308 if( $wgEnableScriptLoader ){
309 //include $this->mScripts (for anything that we could not package into the scriptloader
310 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
312 return $this->mScripts
. $this->getHeadItems();
316 function getHeadItems() {
318 foreach ( $this->mHeadItems
as $item ) {
324 function addHeadItem( $name, $value ) {
325 $this->mHeadItems
[$name] = $value;
328 function hasHeadItem( $name ) {
329 return isset( $this->mHeadItems
[$name] );
332 function setETag($tag) { $this->mETag
= $tag; }
333 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
334 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly
; }
336 function addLink( $linkarr ) {
337 # $linkarr should be an associative array of attributes. We'll escape on output.
338 array_push( $this->mLinktags
, $linkarr );
341 # Get all links added by extensions
342 function getExtStyle() {
343 return $this->mExtStyles
;
346 function addMetadataLink( $linkarr ) {
347 # note: buggy CC software only reads first "meta" link
348 static $haveMeta = false;
349 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
350 $this->addLink( $linkarr );
355 * checkLastModified tells the client to use the client-cached page if
356 * possible. If sucessful, the OutputPage is disabled so that
357 * any future call to OutputPage->output() have no effect.
359 * Side effect: sets mLastModified for Last-Modified header
361 * @return bool True iff cache-ok headers was sent.
363 function checkLastModified( $timestamp ) {
364 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
366 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
367 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
370 if( !$wgCachePages ) {
371 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
374 if( $wgUser->getOption( 'nocache' ) ) {
375 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
379 $timestamp = wfTimestamp( TS_MW
, $timestamp );
380 $modifiedTimes = array(
381 'page' => $timestamp,
382 'user' => $wgUser->getTouched(),
383 'epoch' => $wgCacheEpoch
385 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
387 $maxModified = max( $modifiedTimes );
388 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
390 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
391 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
397 foreach ( $modifiedTimes as $name => $value ) {
398 if ( $info !== '' ) {
401 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
404 # IE sends sizes after the date like this:
405 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
406 # this breaks strtotime().
407 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
409 wfSuppressWarnings(); // E_STRICT system time bitching
410 $clientHeaderTime = strtotime( $clientHeader );
412 if ( !$clientHeaderTime ) {
413 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
416 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
418 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
419 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
420 wfDebug( __METHOD__
. ": effective Last-Modified: " .
421 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
422 if( $clientHeaderTime < $maxModified ) {
423 wfDebug( __METHOD__
. ": STALE, $info\n", false );
428 # Give a 304 response code and disable body output
429 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
430 ini_set('zlib.output_compression', 0);
431 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
432 $this->sendCacheControl();
435 // Don't output a compressed blob when using ob_gzhandler;
436 // it's technically against HTTP spec and seems to confuse
437 // Firefox when the response gets split over two packets.
438 wfClearOutputBuffers();
443 function setPageTitleActionText( $text ) {
444 $this->mPageTitleActionText
= $text;
447 function getPageTitleActionText () {
448 if ( isset( $this->mPageTitleActionText
) ) {
449 return $this->mPageTitleActionText
;
454 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
456 * @param $policy string The literal string to output as the contents of
457 * the meta tag. Will be parsed according to the spec and output in
461 public function setRobotPolicy( $policy ) {
462 $policy = explode( ',', $policy );
463 $policy = array_map( 'trim', $policy );
465 # The default policy is follow, so if nothing is said explicitly, we
467 if( in_array( 'nofollow', $policy ) ) {
468 $this->mFollowPolicy
= 'nofollow';
470 $this->mFollowPolicy
= 'follow';
473 if( in_array( 'noindex', $policy ) ) {
474 $this->mIndexPolicy
= 'noindex';
476 $this->mIndexPolicy
= 'index';
481 * Set the index policy for the page, but leave the follow policy un-
484 * @param $policy string Either 'index' or 'noindex'.
487 public function setIndexPolicy( $policy ) {
488 $policy = trim( $policy );
489 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
490 $this->mIndexPolicy
= $policy;
495 * Set the follow policy for the page, but leave the index policy un-
498 * @param $policy string Either 'follow' or 'nofollow'.
501 public function setFollowPolicy( $policy ) {
502 $policy = trim( $policy );
503 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
504 $this->mFollowPolicy
= $policy;
509 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
511 public function setHTMLTitle( $name ) {
512 $this->mHTMLtitle
= $name;
516 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
517 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
518 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
519 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
521 public function setPageTitle( $name ) {
523 $name = $wgContLang->convert( $name, true );
524 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
525 # but leave "<i>foobar</i>" alone
526 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
527 $this->mPagetitle
= $nameWithTags;
529 $taction = $this->getPageTitleActionText();
530 if( !empty( $taction ) ) {
531 $name .= ' - '.$taction;
534 # change "<i>foo&bar</i>" to "foo&bar"
535 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
538 public function setTitle( $t ) {
542 public function getTitle() {
543 if ( $this->mTitle
instanceof Title
) {
544 return $this->mTitle
;
547 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
553 public function getHTMLTitle() { return $this->mHTMLtitle
; }
554 public function getPageTitle() { return $this->mPagetitle
; }
555 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
556 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
557 public function getSubtitle() { return $this->mSubtitle
; }
558 public function isArticle() { return $this->mIsarticle
; }
559 public function setPrintable() { $this->mPrintable
= true; }
560 public function isPrintable() { return $this->mPrintable
; }
561 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
562 public function isSyndicated() { return $this->mShowFeedLinks
; }
563 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
564 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
565 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
566 public function getOnloadHandler() { return $this->mOnloadHandler
; }
567 public function disable() { $this->mDoNothing
= true; }
568 public function isDisabled() { return $this->mDoNothing
; }
570 public function setArticleRelated( $v ) {
571 $this->mIsArticleRelated
= $v;
573 $this->mIsarticle
= false;
576 public function setArticleFlag( $v ) {
577 $this->mIsarticle
= $v;
579 $this->mIsArticleRelated
= $v;
583 public function isArticleRelated() { return $this->mIsArticleRelated
; }
585 public function getLanguageLinks() { return $this->mLanguageLinks
; }
586 public function addLanguageLinks($newLinkArray) {
587 $this->mLanguageLinks +
= $newLinkArray;
589 public function setLanguageLinks($newLinkArray) {
590 $this->mLanguageLinks
= $newLinkArray;
593 public function getCategoryLinks() {
594 return $this->mCategoryLinks
;
598 * Add an array of categories, with names in the keys
600 public function addCategoryLinks( $categories ) {
601 global $wgUser, $wgContLang;
603 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
607 # Add the links to a LinkBatch
608 $arr = array( NS_CATEGORY
=> $categories );
610 $lb->setArray( $arr );
612 # Fetch existence plus the hiddencat property
613 $dbr = wfGetDB( DB_SLAVE
);
614 $pageTable = $dbr->tableName( 'page' );
615 $where = $lb->constructSet( 'page', $dbr );
616 $propsTable = $dbr->tableName( 'page_props' );
617 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
618 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
619 $res = $dbr->query( $sql, __METHOD__
);
621 # Add the results to the link cache
622 $lb->addResultToCache( LinkCache
::singleton(), $res );
624 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
625 $categories = array_combine( array_keys( $categories ),
626 array_fill( 0, count( $categories ), 'normal' ) );
628 # Mark hidden categories
629 foreach ( $res as $row ) {
630 if ( isset( $row->pp_value
) ) {
631 $categories[$row->page_title
] = 'hidden';
635 # Add the remaining categories to the skin
636 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
637 $sk = $wgUser->getSkin();
638 foreach ( $categories as $category => $type ) {
639 $origcategory = $category;
640 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
641 $wgContLang->findVariantLink( $category, $title, true );
642 if ( $category != $origcategory )
643 if ( array_key_exists( $category, $categories ) )
645 $text = $wgContLang->convertHtml( $title->getText() );
646 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
651 public function setCategoryLinks($categories) {
652 $this->mCategoryLinks
= array();
653 $this->addCategoryLinks($categories);
656 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
657 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
659 public function disallowUserJs() { $this->mAllowUserJs
= false; }
660 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
662 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
663 public function addHTML( $text ) { $this->mBodytext
.= $text; }
664 public function clearHTML() { $this->mBodytext
= ''; }
665 public function getHTML() { return $this->mBodytext
; }
666 public function debug( $text ) { $this->mDebugtext
.= $text; }
669 public function setParserOptions( $options ) {
670 wfDeprecated( __METHOD__
);
671 return $this->parserOptions( $options );
674 public function parserOptions( $options = null ) {
675 if ( !$this->mParserOptions
) {
676 $this->mParserOptions
= new ParserOptions
;
678 return wfSetVar( $this->mParserOptions
, $options );
682 * Set the revision ID which will be seen by the wiki text parser
683 * for things such as embedded {{REVISIONID}} variable use.
684 * @param mixed $revid an integer, or NULL
685 * @return mixed previous value
687 public function setRevisionId( $revid ) {
688 $val = is_null( $revid ) ?
null : intval( $revid );
689 return wfSetVar( $this->mRevisionId
, $val );
692 public function getRevisionId() {
693 return $this->mRevisionId
;
697 * Convert wikitext to HTML and add it to the buffer
698 * Default assumes that the current page title will
701 * @param string $text
702 * @param bool $linestart
704 public function addWikiText( $text, $linestart = true ) {
705 $title = $this->getTitle(); // Work arround E_STRICT
706 $this->addWikiTextTitle( $text, $title, $linestart );
709 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
710 $this->addWikiTextTitle($text, $title, $linestart);
713 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
714 $this->addWikiTextTitle( $text, $title, $linestart, true );
717 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
720 wfProfileIn( __METHOD__
);
722 wfIncrStats( 'pcache_not_possible' );
724 $popts = $this->parserOptions();
725 $oldTidy = $popts->setTidy( $tidy );
727 $parserOutput = $wgParser->parse( $text, $title, $popts,
728 $linestart, true, $this->mRevisionId
);
730 $popts->setTidy( $oldTidy );
732 $this->addParserOutput( $parserOutput );
734 wfProfileOut( __METHOD__
);
739 * @param ParserOutput object &$parserOutput
741 public function addParserOutputNoText( &$parserOutput ) {
742 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
744 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
745 $this->addCategoryLinks( $parserOutput->getCategories() );
746 $this->mNewSectionLink
= $parserOutput->getNewSection();
747 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
749 if( is_null( $wgExemptFromUserRobotsControl ) ) {
750 $bannedNamespaces = $wgContentNamespaces;
752 $bannedNamespaces = $wgExemptFromUserRobotsControl;
754 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
755 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
757 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
760 $this->mParseWarnings
= $parserOutput->getWarnings();
761 if ( $parserOutput->getCacheTime() == -1 ) {
762 $this->enableClientCache( false );
764 $this->mNoGallery
= $parserOutput->getNoGallery();
765 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
767 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
768 if ( isset( $this->mTemplateIds
[$ns] ) ) {
769 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
771 $this->mTemplateIds
[$ns] = $dbks;
775 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
776 $this->setPageTitle( $dt );
777 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
778 $this->setPageTitle( $title );
780 // Hooks registered in the object
781 global $wgParserOutputHooks;
782 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
783 list( $hookName, $data ) = $hookInfo;
784 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
785 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
789 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
794 * @param ParserOutput &$parserOutput
796 function addParserOutput( &$parserOutput ) {
797 $this->addParserOutputNoText( $parserOutput );
798 $text = $parserOutput->getText();
799 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
800 $this->addHTML( $text );
804 * Add wikitext to the buffer, assuming that this is the primary text for a page view
805 * Saves the text into the parser cache if possible.
807 * @param string $text
808 * @param Article $article
810 * @deprecated Use Article::outputWikitext
812 public function addPrimaryWikiText( $text, $article, $cache = true ) {
815 wfDeprecated( __METHOD__
);
817 $popts = $this->parserOptions();
818 $popts->setTidy(true);
819 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
820 $popts, true, true, $this->mRevisionId
);
821 $popts->setTidy(false);
822 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
823 $parserCache = ParserCache
::singleton();
824 $parserCache->save( $parserOutput, $article, $popts);
827 $this->addParserOutput( $parserOutput );
831 * @deprecated use addWikiTextTidy()
833 public function addSecondaryWikiText( $text, $linestart = true ) {
834 wfDeprecated( __METHOD__
);
835 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
839 * Add wikitext with tidy enabled
841 public function addWikiTextTidy( $text, $linestart = true ) {
842 $title = $this->getTitle();
843 $this->addWikiTextTitleTidy($text, $title, $linestart);
848 * Add the output of a QuickTemplate to the output buffer
850 * @param QuickTemplate $template
852 public function addTemplate( &$template ) {
854 $template->execute();
855 $this->addHTML( ob_get_contents() );
860 * Parse wikitext and return the HTML.
862 * @param string $text
863 * @param bool $linestart Is this the start of a line?
864 * @param bool $interface ??
866 public function parse( $text, $linestart = true, $interface = false ) {
868 if( is_null( $this->getTitle() ) ) {
869 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
871 $popts = $this->parserOptions();
872 if ( $interface) { $popts->setInterfaceMessage(true); }
873 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
874 $linestart, true, $this->mRevisionId
);
875 if ( $interface) { $popts->setInterfaceMessage(false); }
876 return $parserOutput->getText();
879 /** Parse wikitext, strip paragraphs, and return the HTML. */
880 public function parseInline( $text, $linestart = true, $interface = false ) {
881 $parsed = $this->parse( $text, $linestart, $interface );
884 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
892 * @param Article $article
897 * @return bool True if successful, else false.
899 public function tryParserCache( &$article ) {
900 wfDeprecated( __METHOD__
);
901 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
903 if ($parserOutput !== false) {
904 $this->addParserOutput( $parserOutput );
912 * @param int $maxage Maximum cache time on the Squid, in seconds.
914 public function setSquidMaxage( $maxage ) {
915 $this->mSquidMaxage
= $maxage;
919 * Use enableClientCache(false) to force it to send nocache headers
922 public function enableClientCache( $state ) {
923 return wfSetVar( $this->mEnableClientCache
, $state );
926 function getCacheVaryCookies() {
927 global $wgCookiePrefix, $wgCacheVaryCookies;
929 if ( $cookies === null ) {
930 $cookies = array_merge(
932 "{$wgCookiePrefix}Token",
933 "{$wgCookiePrefix}LoggedOut",
938 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
943 function uncacheableBecauseRequestVars() {
945 return $wgRequest->getText('useskin', false) === false
946 && $wgRequest->getText('uselang', false) === false;
950 * Check if the request has a cache-varying cookie header
951 * If it does, it's very important that we don't allow public caching
953 function haveCacheVaryCookies() {
955 $cookieHeader = $wgRequest->getHeader( 'cookie' );
956 if ( $cookieHeader === false ) {
959 $cvCookies = $this->getCacheVaryCookies();
960 foreach ( $cvCookies as $cookieName ) {
961 # Check for a simple string match, like the way squid does it
962 if ( strpos( $cookieHeader, $cookieName ) ) {
963 wfDebug( __METHOD__
.": found $cookieName\n" );
967 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
971 /** Get a complete X-Vary-Options header */
972 public function getXVO() {
973 $cvCookies = $this->getCacheVaryCookies();
974 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
976 foreach ( $cvCookies as $cookieName ) {
982 $xvo .= 'string-contains=' . $cookieName;
987 public function sendCacheControl() {
988 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
990 $response = $wgRequest->response();
991 if ($wgUseETag && $this->mETag
)
992 $response->header("ETag: $this->mETag");
994 # don't serve compressed data to clients who can't handle it
995 # maintain different caches for logged-in users and non-logged in ones
996 $response->header( 'Vary: Accept-Encoding, Cookie' );
999 # Add an X-Vary-Options header for Squid with Wikimedia patches
1000 $response->header( $this->getXVO() );
1003 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1004 if( $wgUseSquid && session_id() == '' &&
1005 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1008 # We'll purge the proxy cache explicitly, but require end user agents
1009 # to revalidate against the proxy on each visit.
1010 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1011 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1012 # start with a shorter timeout for initial testing
1013 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1014 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1015 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1017 # We'll purge the proxy cache for anons explicitly, but require end user agents
1018 # to revalidate against the proxy on each visit.
1019 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1020 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1021 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1022 # start with a shorter timeout for initial testing
1023 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1024 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1027 # We do want clients to cache if they can, but they *must* check for updates
1028 # on revisiting the page.
1029 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1030 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1031 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1033 if($this->mLastModified
) {
1034 $response->header( "Last-Modified: {$this->mLastModified}" );
1037 wfDebug( __METHOD__
. ": no caching **\n", false );
1039 # In general, the absence of a last modified header should be enough to prevent
1040 # the client from using its cache. We send a few other things just to make sure.
1041 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1042 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1043 $response->header( 'Pragma: no-cache' );
1048 * Finally, all the text has been munged and accumulated into
1049 * the object, let's actually output it:
1051 public function output() {
1052 global $wgUser, $wgOutputEncoding, $wgRequest;
1053 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1054 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
1055 global $wgEnableMWSuggest, $wgUniversalEditButton;
1058 if( $this->mDoNothing
){
1061 wfProfileIn( __METHOD__
);
1062 if ( '' != $this->mRedirect
) {
1063 # Standards require redirect URLs to be absolute
1064 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1065 if( $this->mRedirectCode
== '301') {
1066 if( !$wgDebugRedirects ) {
1067 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1069 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1071 $this->sendCacheControl();
1073 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1074 if( $wgDebugRedirects ) {
1075 $url = htmlspecialchars( $this->mRedirect
);
1076 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1077 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1078 print "</body>\n</html>\n";
1080 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1082 wfProfileOut( __METHOD__
);
1085 elseif ( $this->mStatusCode
)
1087 $statusMessage = array(
1089 101 => 'Switching Protocols',
1090 102 => 'Processing',
1094 203 => 'Non-Authoritative Information',
1095 204 => 'No Content',
1096 205 => 'Reset Content',
1097 206 => 'Partial Content',
1098 207 => 'Multi-Status',
1099 300 => 'Multiple Choices',
1100 301 => 'Moved Permanently',
1103 304 => 'Not Modified',
1105 307 => 'Temporary Redirect',
1106 400 => 'Bad Request',
1107 401 => 'Unauthorized',
1108 402 => 'Payment Required',
1111 405 => 'Method Not Allowed',
1112 406 => 'Not Acceptable',
1113 407 => 'Proxy Authentication Required',
1114 408 => 'Request Timeout',
1117 411 => 'Length Required',
1118 412 => 'Precondition Failed',
1119 413 => 'Request Entity Too Large',
1120 414 => 'Request-URI Too Large',
1121 415 => 'Unsupported Media Type',
1122 416 => 'Request Range Not Satisfiable',
1123 417 => 'Expectation Failed',
1124 422 => 'Unprocessable Entity',
1126 424 => 'Failed Dependency',
1127 500 => 'Internal Server Error',
1128 501 => 'Not Implemented',
1129 502 => 'Bad Gateway',
1130 503 => 'Service Unavailable',
1131 504 => 'Gateway Timeout',
1132 505 => 'HTTP Version Not Supported',
1133 507 => 'Insufficient Storage'
1136 if ( $statusMessage[$this->mStatusCode
] )
1137 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1140 $sk = $wgUser->getSkin();
1142 // add our core scripts to output
1143 $this->addCoreScripts2Top();
1146 $this->addScriptFile( 'ajax.js' );
1148 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1150 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1151 $this->addScriptFile( 'ajaxwatch.js' );
1154 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1155 $this->addScriptFile( 'mwsuggest.js' );
1159 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1160 $this->addScriptFile( 'rightclickedit.js' );
1163 if( $wgUniversalEditButton ) {
1164 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1165 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1166 // Original UniversalEditButton
1167 $this->addLink( array(
1168 'rel' => 'alternate',
1169 'type' => 'application/x-wiki',
1170 'title' => wfMsg( 'edit' ),
1171 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1173 // Alternate edit link
1174 $this->addLink( array(
1176 'title' => wfMsg( 'edit' ),
1177 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1182 # Buffer output; final headers may depend on later processing
1185 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1186 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1188 if ($this->mArticleBodyOnly
) {
1189 $this->out($this->mBodytext
);
1191 // Hook that allows last minute changes to the output page, e.g.
1192 // adding of CSS or Javascript by extensions.
1193 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1195 wfProfileIn( 'Output-skin' );
1196 $sk->outputPage( $this );
1197 wfProfileOut( 'Output-skin' );
1200 $this->sendCacheControl();
1202 wfProfileOut( __METHOD__
);
1206 * Actually output something with print(). Performs an iconv to the
1207 * output encoding, if needed.
1208 * @param string $ins The string to output
1210 public function out( $ins ) {
1211 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1212 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1215 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1216 if ( false === $outs ) { $outs = $ins; }
1224 public static function setEncodings() {
1225 global $wgInputEncoding, $wgOutputEncoding;
1228 $wgInputEncoding = strtolower( $wgInputEncoding );
1230 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1231 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1234 $wgOutputEncoding = $wgInputEncoding;
1238 * Deprecated, use wfReportTime() instead.
1242 public function reportTime() {
1243 wfDeprecated( __METHOD__
);
1244 $time = wfReportTime();
1249 * Produce a "user is blocked" page.
1251 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1254 function blockedPage( $return = true ) {
1255 global $wgUser, $wgContLang, $wgLang;
1257 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1258 $this->setRobotPolicy( 'noindex,nofollow' );
1259 $this->setArticleRelated( false );
1261 $name = User
::whoIs( $wgUser->blockedBy() );
1262 $reason = $wgUser->blockedFor();
1263 if( $reason == '' ) {
1264 $reason = wfMsg( 'blockednoreason' );
1266 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1269 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1271 $blockid = $wgUser->mBlock
->mId
;
1273 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1274 if ( $blockExpiry == 'infinity' ) {
1275 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1276 // Search for localization in 'ipboptions'
1277 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1278 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1279 if ( strpos( $option, ":" ) === false )
1281 list( $show, $value ) = explode( ":", $option );
1282 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1283 $blockExpiry = $show;
1288 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1291 if ( $wgUser->mBlock
->mAuto
) {
1292 $msg = 'autoblockedtext';
1294 $msg = 'blockedtext';
1297 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1298 * This could be a username, an ip range, or a single ip. */
1299 $intended = $wgUser->mBlock
->mAddress
;
1301 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1303 # Don't auto-return to special pages
1305 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1306 $this->returnToMain( null, $return );
1311 * Output a standard error page
1313 * @param string $title Message key for page title
1314 * @param string $msg Message key for page text
1315 * @param array $params Message parameters
1317 public function showErrorPage( $title, $msg, $params = array() ) {
1318 if ( $this->getTitle() ) {
1319 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1321 $this->setPageTitle( wfMsg( $title ) );
1322 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1323 $this->setRobotPolicy( 'noindex,nofollow' );
1324 $this->setArticleRelated( false );
1325 $this->enableClientCache( false );
1326 $this->mRedirect
= '';
1327 $this->mBodytext
= '';
1329 array_unshift( $params, 'parse' );
1330 array_unshift( $params, $msg );
1331 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1333 $this->returnToMain();
1337 * Output a standard permission error page
1339 * @param array $errors Error message keys
1341 public function showPermissionsErrorPage( $errors, $action = null )
1343 $this->mDebugtext
.= 'Original title: ' .
1344 $this->getTitle()->getPrefixedText() . "\n";
1345 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1346 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1347 $this->setRobotPolicy( 'noindex,nofollow' );
1348 $this->setArticleRelated( false );
1349 $this->enableClientCache( false );
1350 $this->mRedirect
= '';
1351 $this->mBodytext
= '';
1352 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1356 public function errorpage( $title, $msg ) {
1357 wfDeprecated( __METHOD__
);
1358 throw new ErrorPageError( $title, $msg );
1362 * Display an error page indicating that a given version of MediaWiki is
1363 * required to use it
1365 * @param mixed $version The version of MediaWiki needed to use the page
1367 public function versionRequired( $version ) {
1368 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1369 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1370 $this->setRobotPolicy( 'noindex,nofollow' );
1371 $this->setArticleRelated( false );
1372 $this->mBodytext
= '';
1374 $this->addWikiMsg( 'versionrequiredtext', $version );
1375 $this->returnToMain();
1379 * Display an error page noting that a given permission bit is required.
1381 * @param string $permission key required
1383 public function permissionRequired( $permission ) {
1386 $this->setPageTitle( wfMsg( 'badaccess' ) );
1387 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1388 $this->setRobotPolicy( 'noindex,nofollow' );
1389 $this->setArticleRelated( false );
1390 $this->mBodytext
= '';
1392 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1393 User
::getGroupsWithPermission( $permission ) );
1395 $this->addWikiMsg( 'badaccess-groups',
1396 $wgLang->commaList( $groups ),
1399 $this->addWikiMsg( 'badaccess-group0' );
1401 $this->returnToMain();
1405 * Use permissionRequired.
1408 public function sysopRequired() {
1409 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1413 * Use permissionRequired.
1416 public function developerRequired() {
1417 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1421 * Produce the stock "please login to use the wiki" page
1423 public function loginToUse() {
1424 global $wgUser, $wgContLang;
1426 if( $wgUser->isLoggedIn() ) {
1427 $this->permissionRequired( 'read' );
1431 $skin = $wgUser->getSkin();
1433 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1434 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1435 $this->setRobotPolicy( 'noindex,nofollow' );
1436 $this->setArticleFlag( false );
1438 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1439 $loginLink = $skin->link(
1441 wfMsgHtml( 'loginreqlink' ),
1443 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1444 array( 'known', 'noclasses' )
1446 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1447 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1449 # Don't return to the main page if the user can't read it
1450 # otherwise we'll end up in a pointless loop
1451 $mainPage = Title
::newMainPage();
1452 if( $mainPage->userCanRead() )
1453 $this->returnToMain( null, $mainPage );
1457 public function databaseError( $fname, $sql, $error, $errno ) {
1458 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1462 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1463 * @return string The wikitext error-messages, formatted into a list.
1465 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1466 if ($action == null) {
1467 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1470 $action_desc = wfMsgNoTrans( "action-$action" );
1471 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1474 if (count( $errors ) > 1) {
1475 $text .= '<ul class="permissions-errors">' . "\n";
1477 foreach( $errors as $error )
1480 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1485 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1492 * Display a page stating that the Wiki is in read-only mode,
1493 * and optionally show the source of the page that the user
1494 * was trying to edit. Should only be called (for this
1495 * purpose) after wfReadOnly() has returned true.
1497 * For historical reasons, this function is _also_ used to
1498 * show the error message when a user tries to edit a page
1499 * they are not allowed to edit. (Unless it's because they're
1500 * blocked, then we show blockedPage() instead.) In this
1501 * case, the second parameter should be set to true and a list
1502 * of reasons supplied as the third parameter.
1504 * @todo Needs to be split into multiple functions.
1506 * @param string $source Source code to show (or null).
1507 * @param bool $protected Is this a permissions error?
1508 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1510 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1512 $skin = $wgUser->getSkin();
1514 $this->setRobotPolicy( 'noindex,nofollow' );
1515 $this->setArticleRelated( false );
1517 // If no reason is given, just supply a default "I can't let you do
1518 // that, Dave" message. Should only occur if called by legacy code.
1519 if ( $protected && empty($reasons) ) {
1520 $reasons[] = array( 'badaccess-group0' );
1523 if ( !empty($reasons) ) {
1524 // Permissions error
1526 $this->setPageTitle( wfMsg( 'viewsource' ) );
1535 array( 'known', 'noclasses' )
1540 $this->setPageTitle( wfMsg( 'badaccess' ) );
1542 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1544 // Wiki is read only
1545 $this->setPageTitle( wfMsg( 'readonly' ) );
1546 $reason = wfReadOnlyReason();
1547 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1550 // Show source, if supplied
1551 if( is_string( $source ) ) {
1552 $this->addWikiMsg( 'viewsourcetext' );
1553 $text = Xml
::openElement( 'textarea',
1554 array( 'id' => 'wpTextbox1',
1555 'name' => 'wpTextbox1',
1556 'cols' => $wgUser->getOption( 'cols' ),
1557 'rows' => $wgUser->getOption( 'rows' ),
1558 'readonly' => 'readonly' ) );
1559 $text .= htmlspecialchars( $source );
1560 $text .= Xml
::closeElement( 'textarea' );
1561 $this->addHTML( $text );
1563 // Show templates used by this article
1564 $skin = $wgUser->getSkin();
1565 $article = new Article( $this->getTitle() );
1566 $this->addHTML( "<div class='templatesUsed'>
1567 {$skin->formatTemplates( $article->getUsedTemplates() )}
1572 # If the title doesn't exist, it's fairly pointless to print a return
1573 # link to it. After all, you just tried editing it and couldn't, so
1574 # what's there to do there?
1575 if( $this->getTitle()->exists() ) {
1576 $this->returnToMain( null, $this->getTitle() );
1581 public function fatalError( $message ) {
1582 wfDeprecated( __METHOD__
);
1583 throw new FatalError( $message );
1587 public function unexpectedValueError( $name, $val ) {
1588 wfDeprecated( __METHOD__
);
1589 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1593 public function fileCopyError( $old, $new ) {
1594 wfDeprecated( __METHOD__
);
1595 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1599 public function fileRenameError( $old, $new ) {
1600 wfDeprecated( __METHOD__
);
1601 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1605 public function fileDeleteError( $name ) {
1606 wfDeprecated( __METHOD__
);
1607 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1611 public function fileNotFoundError( $name ) {
1612 wfDeprecated( __METHOD__
);
1613 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1616 public function showFatalError( $message ) {
1617 $this->setPageTitle( wfMsg( "internalerror" ) );
1618 $this->setRobotPolicy( "noindex,nofollow" );
1619 $this->setArticleRelated( false );
1620 $this->enableClientCache( false );
1621 $this->mRedirect
= '';
1622 $this->mBodytext
= $message;
1625 public function showUnexpectedValueError( $name, $val ) {
1626 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1629 public function showFileCopyError( $old, $new ) {
1630 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1633 public function showFileRenameError( $old, $new ) {
1634 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1637 public function showFileDeleteError( $name ) {
1638 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1641 public function showFileNotFoundError( $name ) {
1642 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1646 * Add a "return to" link pointing to a specified title
1648 * @param Title $title Title to link
1649 * @param string $query Query string
1651 public function addReturnTo( $title, $query = array() ) {
1653 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1654 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1655 $title, null, array(), $query ) );
1656 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1660 * Add a "return to" link pointing to a specified title,
1661 * or the title indicated in the request, or else the main page
1663 * @param null $unused No longer used
1664 * @param Title $returnto Title to return to
1666 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1669 if ( $returnto == null ) {
1670 $returnto = $wgRequest->getText( 'returnto' );
1673 if ( $returntoquery == null ) {
1674 $returntoquery = $wgRequest->getText( 'returntoquery' );
1677 if ( '' === $returnto ) {
1678 $returnto = Title
::newMainPage();
1681 if ( is_object( $returnto ) ) {
1682 $titleObj = $returnto;
1684 $titleObj = Title
::newFromText( $returnto );
1686 if ( !is_object( $titleObj ) ) {
1687 $titleObj = Title
::newMainPage();
1690 $this->addReturnTo( $titleObj, $returntoquery );
1694 * @return string The doctype, opening <html>, and head element.
1696 public function headElement( Skin
$sk ) {
1697 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1698 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1699 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1701 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1702 if ( $sk->commonPrintStylesheet() ) {
1703 $this->addStyle( 'common/wikiprintable.css', 'print' );
1705 $sk->setupUserCss( $this );
1709 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1710 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1713 if ( '' == $this->getHTMLTitle() ) {
1714 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1717 $dir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1720 $ret .= "<!doctype html>\n";
1721 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1723 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1724 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1725 foreach($wgXhtmlNamespaces as $tag => $ns) {
1726 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1728 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1731 $ret .= "<head>\n\t<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t";
1732 $ret .= implode( "\n", array(
1733 $this->getHeadLinks(),
1734 $this->buildCssLinks(),
1735 $sk->getHeadScripts( $this ),
1736 $this->getHeadItems(),
1739 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1742 if( $wgEnableScriptLoader )
1743 $ret .= $this->getScriptLoaderJs();
1745 if ($wgUseTrackbacks && $this->isArticleRelated())
1746 $ret .= $this->getTitle()->trackbackRDF();
1748 $ret .= "</head>\n";
1752 protected function addDefaultMeta() {
1753 global $wgVersion, $wgHtml5;
1755 static $called = false;
1757 # Don't run this twice
1763 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1765 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1767 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1768 if( $p !== 'index,follow' ) {
1769 // http://www.robotstxt.org/wc/meta-user.html
1770 // Only show if it's different from the default robots policy
1771 $this->addMeta( 'robots', $p );
1774 if ( count( $this->mKeywords
) > 0 ) {
1776 "/<.*?" . ">/" => '',
1779 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1784 * @return string HTML tag links to be put in the header.
1786 public function getHeadLinks() {
1787 global $wgRequest, $wgFeed;
1789 // Ideally this should happen earlier, somewhere. :P
1790 $this->addDefaultMeta();
1794 foreach ( $this->mMetatags
as $tag ) {
1795 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1797 $tag[0] = substr( $tag[0], 5 );
1801 $tags[] = Xml
::element( 'meta',
1804 'content' => $tag[1] ) );
1806 foreach ( $this->mLinktags
as $tag ) {
1807 $tags[] = Xml
::element( 'link', $tag );
1811 foreach( $this->getSyndicationLinks() as $format => $link ) {
1812 # Use the page name for the title (accessed through $wgTitle since
1813 # there's no other way). In principle, this could lead to issues
1814 # with having the same name for different feeds corresponding to
1815 # the same page, but we can't avoid that at this low a level.
1817 $tags[] = $this->feedLink(
1820 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1823 # Recent changes feed should appear on every page (except recentchanges,
1824 # that would be redundant). Put it after the per-page feed to avoid
1825 # changing existing behavior. It's still available, probably via a
1826 # menu in your browser. Some sites might have a different feed they'd
1827 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1828 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1829 # If so, use it instead.
1831 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1832 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1834 if ( $wgOverrideSiteFeed ) {
1835 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1836 $tags[] = $this->feedLink (
1838 htmlspecialchars( $feedUrl ),
1839 wfMsg( "site-{$type}-feed", $wgSitename ) );
1842 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1843 foreach( $wgFeedClasses as $format => $class ) {
1844 $tags[] = $this->feedLink(
1846 $rctitle->getLocalURL( "feed={$format}" ),
1847 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1852 return implode( "\n\t", $tags ) . "\n";
1856 * Return URLs for each supported syndication format for this page.
1857 * @return array associating format keys with URLs
1859 public function getSyndicationLinks() {
1860 global $wgFeedClasses;
1863 if( $this->isSyndicated() ) {
1864 if( is_string( $this->getFeedAppendQuery() ) ) {
1865 $appendQuery = "&" . $this->getFeedAppendQuery();
1870 foreach( $wgFeedClasses as $format => $class ) {
1871 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1878 * Generate a <link rel/> for an RSS feed.
1880 private function feedLink( $type, $url, $text ) {
1881 return Xml
::element( 'link', array(
1882 'rel' => 'alternate',
1883 'type' => "application/$type+xml",
1889 * Add a local or specified stylesheet, with the given media options.
1890 * Meant primarily for internal use...
1892 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1893 * @param $conditional -- for IE conditional comments, specifying an IE version
1894 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1896 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1898 // In Opera, fullscreen mode is treated as projection mode, and it causes
1899 // styles set for screen to not be loaded - thus breaking the page - so
1900 // we can just append projection to the media attribute when it's screen
1901 // so the browser is happy and - with no side-effects on other browsers.
1902 // Also - even though we expect the media type to be lowercase, but here
1903 // we force it to lowercase to be safe.
1904 if ( strtolower( $media ) == 'screen' )
1905 $media .= ',projection';
1907 $options['media'] = $media;
1909 $options['condition'] = $condition;
1911 $options['dir'] = $dir;
1912 $this->styles
[$style] = $options;
1916 * Adds inline CSS styles
1917 * @param $style_css Mixed: inline CSS
1919 public function addInlineStyle( $style_css ){
1920 $this->mScripts
.= "<style type=\"text/css\">$style_css</style>";
1924 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1925 * These will be applied to various media & IE conditionals.
1927 public function buildCssLinks() {
1929 foreach( $this->styles
as $file => $options ) {
1930 $link = $this->styleLink( $file, $options );
1935 return "\t" . implode( "\n\t", $links );
1939 * Return a <link rel="stylesheet"> with the given parameters.
1941 * @param $style string Relative or absolute URL. If $style begins with
1942 * '/', 'http:', or 'https:' it's used for the href as-is. Otherwise,
1943 * it's assumed to refer to some file within $wgStylePath, so the URL
1944 * used is "$wgStylePath/$style?$wgStyleVersion".
1945 * @param $options array Associative array with the following possible
1947 * 'dir': 'rtl' or 'ltr'. If the site language direction doesn't match
1948 * this, the empty string is returned.
1949 * 'media': Contents of the media attribute (will be mangled a bit,
1950 * e.g. 'screen' -> 'screen,projection' so Opera fullscreen works)
1951 * 'condition': Wrap in an IE conditional comment, e.g., 'lt IE 7'.
1952 * @return string Raw HTML
1954 protected function styleLink( $style, $options ) {
1955 global $wgRequest, $wgHtml5;
1957 if( isset( $options['dir'] ) ) {
1959 $siteDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
1960 if( $siteDir != $options['dir'] )
1964 if( isset( $options['media'] ) ) {
1965 $media = $this->transformCssMedia( $options['media'] );
1966 if( is_null( $media ) ) {
1973 if( substr( $style, 0, 1 ) == '/' ||
1974 substr( $style, 0, 5 ) == 'http:' ||
1975 substr( $style, 0, 6 ) == 'https:' ) {
1978 global $wgStylePath, $wgStyleVersion;
1979 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1983 'rel' => 'stylesheet',
1986 $attribs['type'] = 'text/css';
1989 $attribs['media'] = $media;
1992 $link = Xml
::element( 'link', $attribs );
1994 if( isset( $options['condition'] ) ) {
1995 $condition = htmlspecialchars( $options['condition'] );
1996 $link = "<!--[if $condition]>$link<![endif]-->";
2001 function transformCssMedia( $media ) {
2002 global $wgRequest, $wgHandheldForIPhone;
2004 // Switch in on-screen display for media testing
2006 'printable' => 'print',
2007 'handheld' => 'handheld',
2009 foreach( $switches as $switch => $targetMedia ) {
2010 if( $wgRequest->getBool( $switch ) ) {
2011 if( $media == $targetMedia ) {
2013 } elseif( $media == 'screen' ) {
2019 // Expand longer media queries as iPhone doesn't grok 'handheld'
2020 if( $wgHandheldForIPhone ) {
2021 $mediaAliases = array(
2022 'screen' => 'screen and (min-device-width: 481px)',
2023 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2026 if( isset( $mediaAliases[$media] ) ) {
2027 $media = $mediaAliases[$media];
2035 * Turn off regular page output and return an error reponse
2036 * for when rate limiting has triggered.
2038 public function rateLimited() {
2040 $this->setPageTitle(wfMsg('actionthrottled'));
2041 $this->setRobotPolicy( 'noindex,follow' );
2042 $this->setArticleRelated( false );
2043 $this->enableClientCache( false );
2044 $this->mRedirect
= '';
2046 $this->setStatusCode(503);
2047 $this->addWikiMsg( 'actionthrottledtext' );
2049 $this->returnToMain( null, $this->getTitle() );
2053 * Show an "add new section" link?
2057 public function showNewSectionLink() {
2058 return $this->mNewSectionLink
;
2062 * Forcibly hide the new section link?
2066 public function forceHideNewSectionLink() {
2067 return $this->mHideNewSectionLink
;
2071 * Show a warning about slave lag
2073 * If the lag is higher than $wgSlaveLagCritical seconds,
2074 * then the warning is a bit more obvious. If the lag is
2075 * lower than $wgSlaveLagWarning, then no warning is shown.
2077 * @param int $lag Slave lag
2079 public function showLagWarning( $lag ) {
2080 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2081 if( $lag >= $wgSlaveLagWarning ) {
2082 $message = $lag < $wgSlaveLagCritical
2085 $warning = wfMsgExt( $message, 'parse', $lag );
2086 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2091 * Add a wikitext-formatted message to the output.
2092 * This is equivalent to:
2094 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2096 public function addWikiMsg( /*...*/ ) {
2097 $args = func_get_args();
2098 $name = array_shift( $args );
2099 $this->addWikiMsgArray( $name, $args );
2103 * Add a wikitext-formatted message to the output.
2104 * Like addWikiMsg() except the parameters are taken as an array
2105 * instead of a variable argument list.
2107 * $options is passed through to wfMsgExt(), see that function for details.
2109 public function addWikiMsgArray( $name, $args, $options = array() ) {
2110 $options[] = 'parse';
2111 $text = wfMsgExt( $name, $options, $args );
2112 $this->addHTML( $text );
2116 * This function takes a number of message/argument specifications, wraps them in
2117 * some overall structure, and then parses the result and adds it to the output.
2119 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2120 * on. The subsequent arguments may either be strings, in which case they are the
2121 * message names, or arrays, in which case the first element is the message name,
2122 * and subsequent elements are the parameters to that message.
2124 * The special named parameter 'options' in a message specification array is passed
2125 * through to the $options parameter of wfMsgExt().
2127 * Don't use this for messages that are not in users interface language.
2131 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2135 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2137 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2138 $msgSpecs = func_get_args();
2139 array_shift( $msgSpecs );
2140 $msgSpecs = array_values( $msgSpecs );
2142 foreach ( $msgSpecs as $n => $spec ) {
2144 if ( is_array( $spec ) ) {
2146 $name = array_shift( $args );
2147 if ( isset( $args['options'] ) ) {
2148 $options = $args['options'];
2149 unset( $args['options'] );
2155 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2157 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );