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 protected $mTitle = null;
47 * An array of stylesheet filenames (relative from skins path), with options
48 * for CSS media, IE conditions, and RTL/LTR direction.
49 * For internal use; add settings in the skin via $this->addStyle()
51 var $styles = array();
53 private $mIndexPolicy = 'index';
54 private $mFollowPolicy = 'follow';
58 * Initialise private variables
60 function __construct() {
61 global $wgAllowUserJs;
62 $this->mAllowUserJs
= $wgAllowUserJs;
65 public function redirect( $url, $responsecode = '302' ) {
66 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
67 $this->mRedirect
= str_replace( "\n", '', $url );
68 $this->mRedirectCode
= $responsecode;
71 public function getRedirect() {
72 return $this->mRedirect
;
76 * Set the HTTP status code to send with the output.
78 * @param int $statusCode
81 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
84 * Add a new <meta> tag
85 * To add an http-equiv meta tag, precede the name with "http:"
87 * @param $name tag name
88 * @param $val tag value
90 function addMeta( $name, $val ) {
91 array_push( $this->mMetatags
, array( $name, $val ) );
94 function addKeyword( $text ) {
95 if( is_array( $text )) {
96 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
98 array_push( $this->mKeywords
, $text );
101 function addScript( $script ) {
102 $this->mScripts
.= $script . "\n";
106 * Register and add a stylesheet from an extension directory.
107 * @param $url String path to sheet. Provide either a full url (beginning
108 * with 'http', etc) or a relative path from the document root
109 * (beginning with '/'). Otherwise it behaves identically to
110 * addStyle() and draws from the /skins folder.
112 public function addExtensionStyle( $url ) {
113 array_push( $this->mExtStyles
, $url );
117 * Add a JavaScript file out of skins/common, or a given relative path.
118 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
120 function addScriptFile( $file ) {
121 global $wgStylePath, $wgScript, $wgUser;
122 global $wgEnableScriptLoader, $wgScriptPath;
124 if( substr( $file, 0, 1 ) == '/' ) {
127 $path = "{$wgStylePath}/common/{$file}";
130 // If the class can be determined, use the addScriptClass method
131 $js_class = $this->getJsClassFromPath( $path );
133 $this->addScriptClass( $js_class );
137 //do checks for wiki-titles
138 if( strpos( $path, $wgScript ) !== false ) {
139 $reqPath = str_replace( $wgScript . '?', '', $path );
140 $reqArgs = explode( '&', $reqPath );
143 foreach( $reqArgs as $arg ) {
144 list( $key, $var ) = explode( '=', $arg );
145 $reqSet[$key] = $var;
148 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
149 $jsTitleClass = 'WT:' . $reqSet['title'];
150 if( $wgEnableScriptLoader ) {
151 // Extract any extra parameters (for now just skin)
152 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
153 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
154 $this->mScriptLoaderClassList
[] = $jsTitleClass . $ext_param ;
157 $this->addScript( Html
::linkedScript(
158 wfAppendQuery( $path, $this->getURIDparam( $jsTitleClass ) )
165 // If the script loader could not be used, just add the script to the header
166 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
170 * Add the core scripts that are included on every page, for later output into the header
172 * this includes the conditional sitejs
174 function addCoreScripts2Top(){
175 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
176 global $wgUser, $wgJsMimeType;
177 // @todo We should deprecate wikibits in favor of some mv_embed pieces and jQuery
179 if( $wgEnableJS2system ){
180 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
182 $core_classes = array( 'wikibits' );
185 //make sure scripts are on top:
186 $postScripts = $this->mScripts
;
187 $this->mScripts
= '';
189 if( $wgEnableScriptLoader ){
190 //directly add script_loader call
191 //(separate from other scriptloader calls that may include extensions with conditional js)
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 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $this->getURIDparam( $js_class );
230 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
232 //merge in language text (if js2 is on and we have loadGM function)
233 if( $wgEnableJS2system ){
234 $inlineMsg = jsScriptLoader
::getLocalizedMsgsFromClass( $js_class );
235 if( $inlineMsg != '' )
236 $this->addScript( Html
::inlineScript( $inlineMsg ));
241 print "could not find: $js_class\n";
242 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
243 return false; // could not find the class
247 * Get the <script> tag which will invoke the script loader
248 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
250 function getScriptLoaderJs( $classAry = array() ) {
251 global $wgRequest, $wgDebugJavaScript;
252 // If no class array was provided, use mScriptLoaderClassList
253 if( !count( $classAry ) ) {
254 $classAry = $this->mScriptLoaderClassList
;
256 $class_list = implode( ',', $classAry );
258 $debug_param = ( $wgDebugJavaScript ||
259 $wgRequest->getVal( 'debug' ) == 'true' ||
260 $wgRequest->getVal( 'debug' ) == '1' )
261 ?
'&debug=true' : '';
263 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
264 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) ) . "\n";
268 * Get the unique request ID parameter for the script-loader request
270 function getURIDparam( $classAry = array() ) {
271 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
272 if( $wgDebugJavaScript ) {
273 return 'urid=' . time();
275 //support single class_name attr
276 if( gettype( $classAry) == 'string' ){
277 $classAry = array( $classAry );
280 foreach( $classAry as $class ) {
281 if( $wgScriptModifiedCheck ) {
282 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
284 $cur_ftime = filemtime ( $IP ."/". $js_path );
285 if( $cur_ftime > $ftime )
289 // Add the latest revision ID if the class set includes a WT (wiki title)
290 if( substr($class, 0, 3) == 'WT:'){
291 $title_str = substr($class, 3);
292 $t = Title
::newFromText( $title_str );
293 if( $t && $t->exists() ) {
294 if( $t->getLatestRevID() > $frev )
295 $frev = $t->getLatestRevID();
299 //build the actual unique request id:
300 $urid = "urid={$wgStyleVersion}";
302 // Add the file modification time if set
304 $urid .= "_" . $ftime;
306 //add the wiki rev id if set
315 * Given a script path, get the JS class name, or false if no such path is registered.
316 * @param $path string
318 function getJsClassFromPath( $path ) {
319 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
321 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
322 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
323 $js_path = "{$wgScriptPath}/{$js_path}";
324 if( $path == $js_path )
331 * Add a self-contained script tag with the given contents
332 * @param string $script JavaScript text, no <script> tags
334 function addInlineScript( $script ) {
335 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
339 * Get all registered JS and CSS tags for the header.
341 function getScript() {
342 global $wgEnableScriptLoader;
343 if( $wgEnableScriptLoader ){
344 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
346 return $this->mScripts
. $this->getHeadItems();
350 function getHeadItems() {
352 foreach ( $this->mHeadItems
as $item ) {
358 function addHeadItem( $name, $value ) {
359 $this->mHeadItems
[$name] = $value;
362 function hasHeadItem( $name ) {
363 return isset( $this->mHeadItems
[$name] );
366 function setETag($tag) { $this->mETag
= $tag; }
367 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
368 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
370 function addLink( $linkarr ) {
371 # $linkarr should be an associative array of attributes. We'll escape on output.
372 array_push( $this->mLinktags
, $linkarr );
375 # Get all links added by extensions
376 function getExtStyle() {
377 return $this->mExtStyles
;
380 function addMetadataLink( $linkarr ) {
381 # note: buggy CC software only reads first "meta" link
382 static $haveMeta = false;
383 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
384 $this->addLink( $linkarr );
389 * checkLastModified tells the client to use the client-cached page if
390 * possible. If sucessful, the OutputPage is disabled so that
391 * any future call to OutputPage->output() have no effect.
393 * Side effect: sets mLastModified for Last-Modified header
395 * @return bool True iff cache-ok headers was sent.
397 function checkLastModified( $timestamp ) {
398 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
400 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
401 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
404 if( !$wgCachePages ) {
405 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
408 if( $wgUser->getOption( 'nocache' ) ) {
409 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
413 $timestamp = wfTimestamp( TS_MW
, $timestamp );
414 $modifiedTimes = array(
415 'page' => $timestamp,
416 'user' => $wgUser->getTouched(),
417 'epoch' => $wgCacheEpoch
419 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
421 $maxModified = max( $modifiedTimes );
422 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
424 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
425 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
431 foreach ( $modifiedTimes as $name => $value ) {
432 if ( $info !== '' ) {
435 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
438 # IE sends sizes after the date like this:
439 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
440 # this breaks strtotime().
441 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
443 wfSuppressWarnings(); // E_STRICT system time bitching
444 $clientHeaderTime = strtotime( $clientHeader );
446 if ( !$clientHeaderTime ) {
447 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
450 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
452 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
453 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
454 wfDebug( __METHOD__
. ": effective Last-Modified: " .
455 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
456 if( $clientHeaderTime < $maxModified ) {
457 wfDebug( __METHOD__
. ": STALE, $info\n", false );
462 # Give a 304 response code and disable body output
463 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
464 ini_set('zlib.output_compression', 0);
465 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
466 $this->sendCacheControl();
469 // Don't output a compressed blob when using ob_gzhandler;
470 // it's technically against HTTP spec and seems to confuse
471 // Firefox when the response gets split over two packets.
472 wfClearOutputBuffers();
477 function setPageTitleActionText( $text ) {
478 $this->mPageTitleActionText
= $text;
481 function getPageTitleActionText () {
482 if ( isset( $this->mPageTitleActionText
) ) {
483 return $this->mPageTitleActionText
;
488 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
490 * @param $policy string The literal string to output as the contents of
491 * the meta tag. Will be parsed according to the spec and output in
495 public function setRobotPolicy( $policy ) {
496 $policy = Article
::formatRobotPolicy( $policy );
498 if( isset( $policy['index'] ) ){
499 $this->setIndexPolicy( $policy['index'] );
501 if( isset( $policy['follow'] ) ){
502 $this->setFollowPolicy( $policy['follow'] );
507 * Set the index policy for the page, but leave the follow policy un-
510 * @param $policy string Either 'index' or 'noindex'.
513 public function setIndexPolicy( $policy ) {
514 $policy = trim( $policy );
515 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
516 $this->mIndexPolicy
= $policy;
521 * Set the follow policy for the page, but leave the index policy un-
524 * @param $policy string Either 'follow' or 'nofollow'.
527 public function setFollowPolicy( $policy ) {
528 $policy = trim( $policy );
529 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
530 $this->mFollowPolicy
= $policy;
535 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
537 public function setHTMLTitle( $name ) {
538 $this->mHTMLtitle
= $name;
542 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
543 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
544 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
545 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
547 public function setPageTitle( $name ) {
549 $name = $wgContLang->convert( $name, true );
550 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
551 # but leave "<i>foobar</i>" alone
552 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
553 $this->mPagetitle
= $nameWithTags;
555 $taction = $this->getPageTitleActionText();
556 if( !empty( $taction ) ) {
557 $name .= ' - '.$taction;
560 # change "<i>foo&bar</i>" to "foo&bar"
561 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
564 public function setTitle( $t ) {
568 public function getTitle() {
569 if ( $this->mTitle
instanceof Title
) {
570 return $this->mTitle
;
573 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
579 public function getHTMLTitle() { return $this->mHTMLtitle
; }
580 public function getPageTitle() { return $this->mPagetitle
; }
581 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
582 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
583 public function getSubtitle() { return $this->mSubtitle
; }
584 public function isArticle() { return $this->mIsarticle
; }
585 public function setPrintable() { $this->mPrintable
= true; }
586 public function isPrintable() { return $this->mPrintable
; }
587 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
588 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
589 public function getOnloadHandler() { return $this->mOnloadHandler
; }
590 public function disable() { $this->mDoNothing
= true; }
591 public function isDisabled() { return $this->mDoNothing
; }
593 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
595 public function setFeedAppendQuery( $val ) {
596 global $wgFeedClasses;
598 $this->mFeedLinks
= array();
600 foreach( $wgFeedClasses as $type => $class ) {
601 $query = "feed=$type&".$val;
602 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
606 public function addFeedLink( $format, $href ) {
607 $this->mFeedLinks
[$format] = $href;
610 public function isSyndicated() { return count($this->mFeedLinks
); }
612 public function setArticleRelated( $v ) {
613 $this->mIsArticleRelated
= $v;
615 $this->mIsarticle
= false;
618 public function setArticleFlag( $v ) {
619 $this->mIsarticle
= $v;
621 $this->mIsArticleRelated
= $v;
625 public function isArticleRelated() { return $this->mIsArticleRelated
; }
627 public function getLanguageLinks() { return $this->mLanguageLinks
; }
628 public function addLanguageLinks($newLinkArray) {
629 $this->mLanguageLinks +
= $newLinkArray;
631 public function setLanguageLinks($newLinkArray) {
632 $this->mLanguageLinks
= $newLinkArray;
635 public function getCategoryLinks() {
636 return $this->mCategoryLinks
;
640 * Add an array of categories, with names in the keys
642 public function addCategoryLinks( $categories ) {
643 global $wgUser, $wgContLang;
645 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
649 # Add the links to a LinkBatch
650 $arr = array( NS_CATEGORY
=> $categories );
652 $lb->setArray( $arr );
654 # Fetch existence plus the hiddencat property
655 $dbr = wfGetDB( DB_SLAVE
);
656 $pageTable = $dbr->tableName( 'page' );
657 $where = $lb->constructSet( 'page', $dbr );
658 $propsTable = $dbr->tableName( 'page_props' );
659 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
660 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
661 $res = $dbr->query( $sql, __METHOD__
);
663 # Add the results to the link cache
664 $lb->addResultToCache( LinkCache
::singleton(), $res );
666 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
667 $categories = array_combine( array_keys( $categories ),
668 array_fill( 0, count( $categories ), 'normal' ) );
670 # Mark hidden categories
671 foreach ( $res as $row ) {
672 if ( isset( $row->pp_value
) ) {
673 $categories[$row->page_title
] = 'hidden';
677 # Add the remaining categories to the skin
678 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
679 $sk = $wgUser->getSkin();
680 foreach ( $categories as $category => $type ) {
681 $origcategory = $category;
682 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
683 $wgContLang->findVariantLink( $category, $title, true );
684 if ( $category != $origcategory )
685 if ( array_key_exists( $category, $categories ) )
687 $text = $wgContLang->convertHtml( $title->getText() );
688 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
693 public function setCategoryLinks($categories) {
694 $this->mCategoryLinks
= array();
695 $this->addCategoryLinks($categories);
698 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
699 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
701 public function disallowUserJs() { $this->mAllowUserJs
= false; }
702 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
704 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
705 public function addHTML( $text ) { $this->mBodytext
.= $text; }
706 public function clearHTML() { $this->mBodytext
= ''; }
707 public function getHTML() { return $this->mBodytext
; }
708 public function debug( $text ) { $this->mDebugtext
.= $text; }
711 public function setParserOptions( $options ) {
712 wfDeprecated( __METHOD__
);
713 return $this->parserOptions( $options );
716 public function parserOptions( $options = null ) {
717 if ( !$this->mParserOptions
) {
718 $this->mParserOptions
= new ParserOptions
;
720 return wfSetVar( $this->mParserOptions
, $options );
724 * Set the revision ID which will be seen by the wiki text parser
725 * for things such as embedded {{REVISIONID}} variable use.
726 * @param mixed $revid an integer, or NULL
727 * @return mixed previous value
729 public function setRevisionId( $revid ) {
730 $val = is_null( $revid ) ?
null : intval( $revid );
731 return wfSetVar( $this->mRevisionId
, $val );
734 public function getRevisionId() {
735 return $this->mRevisionId
;
739 * Convert wikitext to HTML and add it to the buffer
740 * Default assumes that the current page title will
743 * @param string $text
744 * @param bool $linestart
746 public function addWikiText( $text, $linestart = true ) {
747 $title = $this->getTitle(); // Work arround E_STRICT
748 $this->addWikiTextTitle( $text, $title, $linestart );
751 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
752 $this->addWikiTextTitle($text, $title, $linestart);
755 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
756 $this->addWikiTextTitle( $text, $title, $linestart, true );
759 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
762 wfProfileIn( __METHOD__
);
764 wfIncrStats( 'pcache_not_possible' );
766 $popts = $this->parserOptions();
767 $oldTidy = $popts->setTidy( $tidy );
769 $parserOutput = $wgParser->parse( $text, $title, $popts,
770 $linestart, true, $this->mRevisionId
);
772 $popts->setTidy( $oldTidy );
774 $this->addParserOutput( $parserOutput );
776 wfProfileOut( __METHOD__
);
781 * @param ParserOutput object &$parserOutput
783 public function addParserOutputNoText( &$parserOutput ) {
784 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
786 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
787 $this->addCategoryLinks( $parserOutput->getCategories() );
788 $this->mNewSectionLink
= $parserOutput->getNewSection();
789 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
791 $this->mParseWarnings
= $parserOutput->getWarnings();
792 if ( $parserOutput->getCacheTime() == -1 ) {
793 $this->enableClientCache( false );
795 $this->mNoGallery
= $parserOutput->getNoGallery();
796 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
798 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
799 if ( isset( $this->mTemplateIds
[$ns] ) ) {
800 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
802 $this->mTemplateIds
[$ns] = $dbks;
806 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
807 $this->setPageTitle( $dt );
808 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
809 $this->setPageTitle( $title );
811 // Hooks registered in the object
812 global $wgParserOutputHooks;
813 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
814 list( $hookName, $data ) = $hookInfo;
815 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
816 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
820 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
825 * @param ParserOutput &$parserOutput
827 function addParserOutput( &$parserOutput ) {
828 $this->addParserOutputNoText( $parserOutput );
829 $text = $parserOutput->getText();
830 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
831 $this->addHTML( $text );
835 * Add wikitext to the buffer, assuming that this is the primary text for a page view
836 * Saves the text into the parser cache if possible.
838 * @param string $text
839 * @param Article $article
841 * @deprecated Use Article::outputWikitext
843 public function addPrimaryWikiText( $text, $article, $cache = true ) {
846 wfDeprecated( __METHOD__
);
848 $popts = $this->parserOptions();
849 $popts->setTidy(true);
850 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
851 $popts, true, true, $this->mRevisionId
);
852 $popts->setTidy(false);
853 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
854 $parserCache = ParserCache
::singleton();
855 $parserCache->save( $parserOutput, $article, $popts);
858 $this->addParserOutput( $parserOutput );
862 * @deprecated use addWikiTextTidy()
864 public function addSecondaryWikiText( $text, $linestart = true ) {
865 wfDeprecated( __METHOD__
);
866 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
870 * Add wikitext with tidy enabled
872 public function addWikiTextTidy( $text, $linestart = true ) {
873 $title = $this->getTitle();
874 $this->addWikiTextTitleTidy($text, $title, $linestart);
879 * Add the output of a QuickTemplate to the output buffer
881 * @param QuickTemplate $template
883 public function addTemplate( &$template ) {
885 $template->execute();
886 $this->addHTML( ob_get_contents() );
891 * Parse wikitext and return the HTML.
893 * @param string $text
894 * @param bool $linestart Is this the start of a line?
895 * @param bool $interface ??
897 public function parse( $text, $linestart = true, $interface = false ) {
899 if( is_null( $this->getTitle() ) ) {
900 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
902 $popts = $this->parserOptions();
903 if ( $interface) { $popts->setInterfaceMessage(true); }
904 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
905 $linestart, true, $this->mRevisionId
);
906 if ( $interface) { $popts->setInterfaceMessage(false); }
907 return $parserOutput->getText();
910 /** Parse wikitext, strip paragraphs, and return the HTML. */
911 public function parseInline( $text, $linestart = true, $interface = false ) {
912 $parsed = $this->parse( $text, $linestart, $interface );
915 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
923 * @param Article $article
928 * @return bool True if successful, else false.
930 public function tryParserCache( &$article ) {
931 wfDeprecated( __METHOD__
);
932 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
934 if ($parserOutput !== false) {
935 $this->addParserOutput( $parserOutput );
943 * @param int $maxage Maximum cache time on the Squid, in seconds.
945 public function setSquidMaxage( $maxage ) {
946 $this->mSquidMaxage
= $maxage;
950 * Use enableClientCache(false) to force it to send nocache headers
953 public function enableClientCache( $state ) {
954 return wfSetVar( $this->mEnableClientCache
, $state );
957 function getCacheVaryCookies() {
958 global $wgCookiePrefix, $wgCacheVaryCookies;
960 if ( $cookies === null ) {
961 $cookies = array_merge(
963 "{$wgCookiePrefix}Token",
964 "{$wgCookiePrefix}LoggedOut",
969 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
974 function uncacheableBecauseRequestVars() {
976 return $wgRequest->getText('useskin', false) === false
977 && $wgRequest->getText('uselang', false) === false;
981 * Check if the request has a cache-varying cookie header
982 * If it does, it's very important that we don't allow public caching
984 function haveCacheVaryCookies() {
986 $cookieHeader = $wgRequest->getHeader( 'cookie' );
987 if ( $cookieHeader === false ) {
990 $cvCookies = $this->getCacheVaryCookies();
991 foreach ( $cvCookies as $cookieName ) {
992 # Check for a simple string match, like the way squid does it
993 if ( strpos( $cookieHeader, $cookieName ) ) {
994 wfDebug( __METHOD__
.": found $cookieName\n" );
998 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
1002 /** Get a complete X-Vary-Options header */
1003 public function getXVO() {
1004 $cvCookies = $this->getCacheVaryCookies();
1005 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
1007 foreach ( $cvCookies as $cookieName ) {
1013 $xvo .= 'string-contains=' . $cookieName;
1018 public function sendCacheControl() {
1019 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1021 $response = $wgRequest->response();
1022 if ($wgUseETag && $this->mETag
)
1023 $response->header("ETag: $this->mETag");
1025 # don't serve compressed data to clients who can't handle it
1026 # maintain different caches for logged-in users and non-logged in ones
1027 $response->header( 'Vary: Accept-Encoding, Cookie' );
1030 # Add an X-Vary-Options header for Squid with Wikimedia patches
1031 $response->header( $this->getXVO() );
1034 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1035 if( $wgUseSquid && session_id() == '' &&
1036 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1039 # We'll purge the proxy cache explicitly, but require end user agents
1040 # to revalidate against the proxy on each visit.
1041 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1042 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1043 # start with a shorter timeout for initial testing
1044 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1045 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1046 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1048 # We'll purge the proxy cache for anons explicitly, but require end user agents
1049 # to revalidate against the proxy on each visit.
1050 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1051 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1052 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1053 # start with a shorter timeout for initial testing
1054 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1055 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1058 # We do want clients to cache if they can, but they *must* check for updates
1059 # on revisiting the page.
1060 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1061 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1062 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1064 if($this->mLastModified
) {
1065 $response->header( "Last-Modified: {$this->mLastModified}" );
1068 wfDebug( __METHOD__
. ": no caching **\n", false );
1070 # In general, the absence of a last modified header should be enough to prevent
1071 # the client from using its cache. We send a few other things just to make sure.
1072 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1073 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1074 $response->header( 'Pragma: no-cache' );
1079 * Finally, all the text has been munged and accumulated into
1080 * the object, let's actually output it:
1082 public function output() {
1083 global $wgUser, $wgOutputEncoding, $wgRequest;
1084 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1085 global $wgUseAjax, $wgAjaxWatch;
1086 global $wgEnableMWSuggest, $wgUniversalEditButton;
1089 if( $this->mDoNothing
){
1092 wfProfileIn( __METHOD__
);
1093 if ( '' != $this->mRedirect
) {
1094 # Standards require redirect URLs to be absolute
1095 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1096 if( $this->mRedirectCode
== '301') {
1097 if( !$wgDebugRedirects ) {
1098 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1100 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1102 $this->sendCacheControl();
1104 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1105 if( $wgDebugRedirects ) {
1106 $url = htmlspecialchars( $this->mRedirect
);
1107 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1108 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1109 print "</body>\n</html>\n";
1111 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1113 wfProfileOut( __METHOD__
);
1116 elseif ( $this->mStatusCode
)
1118 $statusMessage = array(
1120 101 => 'Switching Protocols',
1121 102 => 'Processing',
1125 203 => 'Non-Authoritative Information',
1126 204 => 'No Content',
1127 205 => 'Reset Content',
1128 206 => 'Partial Content',
1129 207 => 'Multi-Status',
1130 300 => 'Multiple Choices',
1131 301 => 'Moved Permanently',
1134 304 => 'Not Modified',
1136 307 => 'Temporary Redirect',
1137 400 => 'Bad Request',
1138 401 => 'Unauthorized',
1139 402 => 'Payment Required',
1142 405 => 'Method Not Allowed',
1143 406 => 'Not Acceptable',
1144 407 => 'Proxy Authentication Required',
1145 408 => 'Request Timeout',
1148 411 => 'Length Required',
1149 412 => 'Precondition Failed',
1150 413 => 'Request Entity Too Large',
1151 414 => 'Request-URI Too Large',
1152 415 => 'Unsupported Media Type',
1153 416 => 'Request Range Not Satisfiable',
1154 417 => 'Expectation Failed',
1155 422 => 'Unprocessable Entity',
1157 424 => 'Failed Dependency',
1158 500 => 'Internal Server Error',
1159 501 => 'Not Implemented',
1160 502 => 'Bad Gateway',
1161 503 => 'Service Unavailable',
1162 504 => 'Gateway Timeout',
1163 505 => 'HTTP Version Not Supported',
1164 507 => 'Insufficient Storage'
1167 if ( $statusMessage[$this->mStatusCode
] )
1168 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1171 $sk = $wgUser->getSkin();
1173 // Add our core scripts to output
1174 $this->addCoreScripts2Top();
1177 $this->addScriptFile( 'ajax.js' );
1179 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1181 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1182 $this->addScriptFile( 'ajaxwatch.js' );
1185 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1186 $this->addScriptFile( 'mwsuggest.js' );
1190 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1191 $this->addScriptFile( 'rightclickedit.js' );
1194 global $wgUseAJAXCategories, $wgEnableJS2system;
1195 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1196 global $wgAJAXCategoriesNamespaces;
1198 $title = $this->getTitle();
1200 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1201 $this->addScriptClass( 'ajaxCategories' );
1205 if( $wgUniversalEditButton ) {
1206 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1207 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1208 // Original UniversalEditButton
1209 $msg = wfMsg('edit');
1210 $this->addLink( array(
1211 'rel' => 'alternate',
1212 'type' => 'application/x-wiki',
1214 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1216 // Alternate edit link
1217 $this->addLink( array(
1220 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1225 # Buffer output; final headers may depend on later processing
1228 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1229 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1231 if ($this->mArticleBodyOnly
) {
1232 $this->out($this->mBodytext
);
1234 // Hook that allows last minute changes to the output page, e.g.
1235 // adding of CSS or Javascript by extensions.
1236 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1238 wfProfileIn( 'Output-skin' );
1239 $sk->outputPage( $this );
1240 wfProfileOut( 'Output-skin' );
1243 $this->sendCacheControl();
1245 wfProfileOut( __METHOD__
);
1249 * Actually output something with print(). Performs an iconv to the
1250 * output encoding, if needed.
1251 * @param string $ins The string to output
1253 public function out( $ins ) {
1254 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1255 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1258 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1259 if ( false === $outs ) { $outs = $ins; }
1267 public static function setEncodings() {
1268 global $wgInputEncoding, $wgOutputEncoding;
1271 $wgInputEncoding = strtolower( $wgInputEncoding );
1273 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1274 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1277 $wgOutputEncoding = $wgInputEncoding;
1281 * Deprecated, use wfReportTime() instead.
1285 public function reportTime() {
1286 wfDeprecated( __METHOD__
);
1287 $time = wfReportTime();
1292 * Produce a "user is blocked" page.
1294 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1297 function blockedPage( $return = true ) {
1298 global $wgUser, $wgContLang, $wgLang;
1300 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1301 $this->setRobotPolicy( 'noindex,nofollow' );
1302 $this->setArticleRelated( false );
1304 $name = User
::whoIs( $wgUser->blockedBy() );
1305 $reason = $wgUser->blockedFor();
1306 if( $reason == '' ) {
1307 $reason = wfMsg( 'blockednoreason' );
1309 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1312 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1314 $blockid = $wgUser->mBlock
->mId
;
1316 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1317 if ( $blockExpiry == 'infinity' ) {
1318 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1319 // Search for localization in 'ipboptions'
1320 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1321 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1322 if ( strpos( $option, ":" ) === false )
1324 list( $show, $value ) = explode( ":", $option );
1325 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1326 $blockExpiry = $show;
1331 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1334 if ( $wgUser->mBlock
->mAuto
) {
1335 $msg = 'autoblockedtext';
1337 $msg = 'blockedtext';
1340 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1341 * This could be a username, an ip range, or a single ip. */
1342 $intended = $wgUser->mBlock
->mAddress
;
1344 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1346 # Don't auto-return to special pages
1348 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1349 $this->returnToMain( null, $return );
1354 * Output a standard error page
1356 * @param string $title Message key for page title
1357 * @param string $msg Message key for page text
1358 * @param array $params Message parameters
1360 public function showErrorPage( $title, $msg, $params = array() ) {
1361 if ( $this->getTitle() ) {
1362 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1364 $this->setPageTitle( wfMsg( $title ) );
1365 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1366 $this->setRobotPolicy( 'noindex,nofollow' );
1367 $this->setArticleRelated( false );
1368 $this->enableClientCache( false );
1369 $this->mRedirect
= '';
1370 $this->mBodytext
= '';
1372 array_unshift( $params, 'parse' );
1373 array_unshift( $params, $msg );
1374 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1376 $this->returnToMain();
1380 * Output a standard permission error page
1382 * @param array $errors Error message keys
1384 public function showPermissionsErrorPage( $errors, $action = null )
1386 $this->mDebugtext
.= 'Original title: ' .
1387 $this->getTitle()->getPrefixedText() . "\n";
1388 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1389 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1390 $this->setRobotPolicy( 'noindex,nofollow' );
1391 $this->setArticleRelated( false );
1392 $this->enableClientCache( false );
1393 $this->mRedirect
= '';
1394 $this->mBodytext
= '';
1395 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1399 public function errorpage( $title, $msg ) {
1400 wfDeprecated( __METHOD__
);
1401 throw new ErrorPageError( $title, $msg );
1405 * Display an error page indicating that a given version of MediaWiki is
1406 * required to use it
1408 * @param mixed $version The version of MediaWiki needed to use the page
1410 public function versionRequired( $version ) {
1411 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1412 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1413 $this->setRobotPolicy( 'noindex,nofollow' );
1414 $this->setArticleRelated( false );
1415 $this->mBodytext
= '';
1417 $this->addWikiMsg( 'versionrequiredtext', $version );
1418 $this->returnToMain();
1422 * Display an error page noting that a given permission bit is required.
1424 * @param string $permission key required
1426 public function permissionRequired( $permission ) {
1429 $this->setPageTitle( wfMsg( 'badaccess' ) );
1430 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1431 $this->setRobotPolicy( 'noindex,nofollow' );
1432 $this->setArticleRelated( false );
1433 $this->mBodytext
= '';
1435 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1436 User
::getGroupsWithPermission( $permission ) );
1438 $this->addWikiMsg( 'badaccess-groups',
1439 $wgLang->commaList( $groups ),
1442 $this->addWikiMsg( 'badaccess-group0' );
1444 $this->returnToMain();
1448 * Use permissionRequired.
1451 public function sysopRequired() {
1452 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1456 * Use permissionRequired.
1459 public function developerRequired() {
1460 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1464 * Produce the stock "please login to use the wiki" page
1466 public function loginToUse() {
1467 global $wgUser, $wgContLang;
1469 if( $wgUser->isLoggedIn() ) {
1470 $this->permissionRequired( 'read' );
1474 $skin = $wgUser->getSkin();
1476 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1477 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1478 $this->setRobotPolicy( 'noindex,nofollow' );
1479 $this->setArticleFlag( false );
1481 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1482 $loginLink = $skin->link(
1484 wfMsgHtml( 'loginreqlink' ),
1486 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1487 array( 'known', 'noclasses' )
1489 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1490 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1492 # Don't return to the main page if the user can't read it
1493 # otherwise we'll end up in a pointless loop
1494 $mainPage = Title
::newMainPage();
1495 if( $mainPage->userCanRead() )
1496 $this->returnToMain( null, $mainPage );
1500 public function databaseError( $fname, $sql, $error, $errno ) {
1501 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1505 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1506 * @return string The wikitext error-messages, formatted into a list.
1508 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1509 if ($action == null) {
1510 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1513 $action_desc = wfMsgNoTrans( "action-$action" );
1514 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1517 if (count( $errors ) > 1) {
1518 $text .= '<ul class="permissions-errors">' . "\n";
1520 foreach( $errors as $error )
1523 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1528 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1535 * Display a page stating that the Wiki is in read-only mode,
1536 * and optionally show the source of the page that the user
1537 * was trying to edit. Should only be called (for this
1538 * purpose) after wfReadOnly() has returned true.
1540 * For historical reasons, this function is _also_ used to
1541 * show the error message when a user tries to edit a page
1542 * they are not allowed to edit. (Unless it's because they're
1543 * blocked, then we show blockedPage() instead.) In this
1544 * case, the second parameter should be set to true and a list
1545 * of reasons supplied as the third parameter.
1547 * @todo Needs to be split into multiple functions.
1549 * @param string $source Source code to show (or null).
1550 * @param bool $protected Is this a permissions error?
1551 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1553 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1555 $skin = $wgUser->getSkin();
1557 $this->setRobotPolicy( 'noindex,nofollow' );
1558 $this->setArticleRelated( false );
1560 // If no reason is given, just supply a default "I can't let you do
1561 // that, Dave" message. Should only occur if called by legacy code.
1562 if ( $protected && empty($reasons) ) {
1563 $reasons[] = array( 'badaccess-group0' );
1566 if ( !empty($reasons) ) {
1567 // Permissions error
1569 $this->setPageTitle( wfMsg( 'viewsource' ) );
1578 array( 'known', 'noclasses' )
1583 $this->setPageTitle( wfMsg( 'badaccess' ) );
1585 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1587 // Wiki is read only
1588 $this->setPageTitle( wfMsg( 'readonly' ) );
1589 $reason = wfReadOnlyReason();
1590 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1593 // Show source, if supplied
1594 if( is_string( $source ) ) {
1595 $this->addWikiMsg( 'viewsourcetext' );
1598 'id' => 'wpTextbox1',
1599 'name' => 'wpTextbox1',
1600 'cols' => $wgUser->getOption( 'cols' ),
1601 'rows' => $wgUser->getOption( 'rows' ),
1602 'readonly' => 'readonly'
1604 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1606 // Show templates used by this article
1607 $skin = $wgUser->getSkin();
1608 $article = new Article( $this->getTitle() );
1609 $this->addHTML( "<div class='templatesUsed'>
1610 {$skin->formatTemplates( $article->getUsedTemplates() )}
1615 # If the title doesn't exist, it's fairly pointless to print a return
1616 # link to it. After all, you just tried editing it and couldn't, so
1617 # what's there to do there?
1618 if( $this->getTitle()->exists() ) {
1619 $this->returnToMain( null, $this->getTitle() );
1624 public function fatalError( $message ) {
1625 wfDeprecated( __METHOD__
);
1626 throw new FatalError( $message );
1630 public function unexpectedValueError( $name, $val ) {
1631 wfDeprecated( __METHOD__
);
1632 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1636 public function fileCopyError( $old, $new ) {
1637 wfDeprecated( __METHOD__
);
1638 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1642 public function fileRenameError( $old, $new ) {
1643 wfDeprecated( __METHOD__
);
1644 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1648 public function fileDeleteError( $name ) {
1649 wfDeprecated( __METHOD__
);
1650 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1654 public function fileNotFoundError( $name ) {
1655 wfDeprecated( __METHOD__
);
1656 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1659 public function showFatalError( $message ) {
1660 $this->setPageTitle( wfMsg( "internalerror" ) );
1661 $this->setRobotPolicy( "noindex,nofollow" );
1662 $this->setArticleRelated( false );
1663 $this->enableClientCache( false );
1664 $this->mRedirect
= '';
1665 $this->mBodytext
= $message;
1668 public function showUnexpectedValueError( $name, $val ) {
1669 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1672 public function showFileCopyError( $old, $new ) {
1673 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1676 public function showFileRenameError( $old, $new ) {
1677 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1680 public function showFileDeleteError( $name ) {
1681 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1684 public function showFileNotFoundError( $name ) {
1685 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1689 * Add a "return to" link pointing to a specified title
1691 * @param Title $title Title to link
1692 * @param string $query Query string
1694 public function addReturnTo( $title, $query = array() ) {
1696 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1697 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1698 $title, null, array(), $query ) );
1699 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1703 * Add a "return to" link pointing to a specified title,
1704 * or the title indicated in the request, or else the main page
1706 * @param null $unused No longer used
1707 * @param Title $returnto Title to return to
1709 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1712 if ( $returnto == null ) {
1713 $returnto = $wgRequest->getText( 'returnto' );
1716 if ( $returntoquery == null ) {
1717 $returntoquery = $wgRequest->getText( 'returntoquery' );
1720 if ( '' === $returnto ) {
1721 $returnto = Title
::newMainPage();
1724 if ( is_object( $returnto ) ) {
1725 $titleObj = $returnto;
1727 $titleObj = Title
::newFromText( $returnto );
1729 if ( !is_object( $titleObj ) ) {
1730 $titleObj = Title
::newMainPage();
1733 $this->addReturnTo( $titleObj, $returntoquery );
1737 * @return string The doctype, opening <html>, and head element.
1739 * @param $sk Skin The given Skin
1741 public function headElement( Skin
$sk, $includeStyle = true ) {
1742 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1743 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1744 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1746 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1747 if ( $sk->commonPrintStylesheet() ) {
1748 $this->addStyle( 'common/wikiprintable.css', 'print' );
1750 $sk->setupUserCss( $this );
1754 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1755 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1758 if ( '' == $this->getHTMLTitle() ) {
1759 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1762 $dir = $wgContLang->getDir();
1765 $ret .= "<!doctype html>\n";
1766 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1768 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1769 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1770 foreach($wgXhtmlNamespaces as $tag => $ns) {
1771 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1773 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1777 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1778 $ret .= implode( "\n", array(
1779 $this->getHeadLinks(),
1780 $this->buildCssLinks(),
1781 $this->getHeadScripts( $sk ),
1782 $this->getHeadItems(),
1785 $ret .= Html
::inlineStyle( $sk->usercss
);
1788 if( $wgEnableScriptLoader )
1789 $ret .= $this->getScriptLoaderJs();
1791 if ($wgUseTrackbacks && $this->isArticleRelated())
1792 $ret .= $this->getTitle()->trackbackRDF();
1794 $ret .= "</head>\n";
1799 * gets the global variables and mScripts
1801 * also adds userjs to the end if enabled:
1803 function getHeadScripts( Skin
$sk ) {
1804 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1806 $vars = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1808 //add site JS if enabled:
1809 if( $wgUseSiteJs ) {
1810 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1811 $this->addScriptFile( Skin
::makeUrl( '-',
1812 "action=raw$jsCache&gen=js&useskin=" .
1813 urlencode( $sk->getSkinName() )
1818 //add user js if enabled:
1819 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1820 $action = $wgRequest->getVal( 'action', 'view' );
1821 if( $this->mTitle
&& $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1822 # XXX: additional security check/prompt?
1823 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1825 $userpage = $wgUser->getUserPage();
1826 $userjs = Skin
::makeUrl(
1827 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1828 'action=raw&ctype=' . $wgJsMimeType );
1829 $this->addScriptFile( $userjs );
1833 return $vars . "\n" . $this->mScripts
;
1836 protected function addDefaultMeta() {
1837 global $wgVersion, $wgHtml5;
1839 static $called = false;
1841 # Don't run this twice
1847 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1849 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1851 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1852 if( $p !== 'index,follow' ) {
1853 // http://www.robotstxt.org/wc/meta-user.html
1854 // Only show if it's different from the default robots policy
1855 $this->addMeta( 'robots', $p );
1858 if ( count( $this->mKeywords
) > 0 ) {
1860 "/<.*?" . ">/" => '',
1863 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1868 * @return string HTML tag links to be put in the header.
1870 public function getHeadLinks() {
1871 global $wgRequest, $wgFeed;
1873 // Ideally this should happen earlier, somewhere. :P
1874 $this->addDefaultMeta();
1878 foreach ( $this->mMetatags
as $tag ) {
1879 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1881 $tag[0] = substr( $tag[0], 5 );
1885 $tags[] = Html
::element( 'meta',
1888 'content' => $tag[1] ) );
1890 foreach ( $this->mLinktags
as $tag ) {
1891 $tags[] = Html
::element( 'link', $tag );
1895 foreach( $this->getSyndicationLinks() as $format => $link ) {
1896 # Use the page name for the title (accessed through $wgTitle since
1897 # there's no other way). In principle, this could lead to issues
1898 # with having the same name for different feeds corresponding to
1899 # the same page, but we can't avoid that at this low a level.
1901 $tags[] = $this->feedLink(
1904 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1907 # Recent changes feed should appear on every page (except recentchanges,
1908 # that would be redundant). Put it after the per-page feed to avoid
1909 # changing existing behavior. It's still available, probably via a
1910 # menu in your browser. Some sites might have a different feed they'd
1911 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1912 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1913 # If so, use it instead.
1915 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1916 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1918 if ( $wgOverrideSiteFeed ) {
1919 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1920 $tags[] = $this->feedLink (
1922 htmlspecialchars( $feedUrl ),
1923 wfMsg( "site-{$type}-feed", $wgSitename ) );
1926 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1927 foreach( $wgFeedClasses as $format => $class ) {
1928 $tags[] = $this->feedLink(
1930 $rctitle->getLocalURL( "feed={$format}" ),
1931 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1936 return implode( "\n", $tags );
1940 * Return URLs for each supported syndication format for this page.
1941 * @return array associating format keys with URLs
1943 public function getSyndicationLinks() {
1944 return $this->mFeedLinks
;
1948 * Generate a <link rel/> for an RSS feed.
1950 private function feedLink( $type, $url, $text ) {
1951 return Html
::element( 'link', array(
1952 'rel' => 'alternate',
1953 'type' => "application/$type+xml",
1959 * Add a local or specified stylesheet, with the given media options.
1960 * Meant primarily for internal use...
1962 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1963 * @param $conditional -- for IE conditional comments, specifying an IE version
1964 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1966 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1968 // Even though we expect the media type to be lowercase, but here we
1969 // force it to lowercase to be safe.
1971 $options['media'] = $media;
1973 $options['condition'] = $condition;
1975 $options['dir'] = $dir;
1976 $this->styles
[$style] = $options;
1980 * Adds inline CSS styles
1981 * @param $style_css Mixed: inline CSS
1983 public function addInlineStyle( $style_css ){
1984 $this->mScripts
.= Html
::inlineStyle( $style_css );
1988 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1989 * These will be applied to various media & IE conditionals.
1991 public function buildCssLinks() {
1993 foreach( $this->styles
as $file => $options ) {
1994 $link = $this->styleLink( $file, $options );
1999 return implode( "\n", $links );
2002 protected function styleLink( $style, $options ) {
2005 if( isset( $options['dir'] ) ) {
2007 $siteDir = $wgContLang->getDir();
2008 if( $siteDir != $options['dir'] )
2012 if( isset( $options['media'] ) ) {
2013 $media = $this->transformCssMedia( $options['media'] );
2014 if( is_null( $media ) ) {
2021 if( substr( $style, 0, 1 ) == '/' ||
2022 substr( $style, 0, 5 ) == 'http:' ||
2023 substr( $style, 0, 6 ) == 'https:' ) {
2026 global $wgStylePath, $wgStyleVersion;
2027 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2030 $link = Html
::linkedStyle( $url, $media );
2032 if( isset( $options['condition'] ) ) {
2033 $condition = htmlspecialchars( $options['condition'] );
2034 $link = "<!--[if $condition]>$link<![endif]-->";
2039 function transformCssMedia( $media ) {
2040 global $wgRequest, $wgHandheldForIPhone;
2042 // Switch in on-screen display for media testing
2044 'printable' => 'print',
2045 'handheld' => 'handheld',
2047 foreach( $switches as $switch => $targetMedia ) {
2048 if( $wgRequest->getBool( $switch ) ) {
2049 if( $media == $targetMedia ) {
2051 } elseif( $media == 'screen' ) {
2057 // Expand longer media queries as iPhone doesn't grok 'handheld'
2058 if( $wgHandheldForIPhone ) {
2059 $mediaAliases = array(
2060 'screen' => 'screen and (min-device-width: 481px)',
2061 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2064 if( isset( $mediaAliases[$media] ) ) {
2065 $media = $mediaAliases[$media];
2073 * Turn off regular page output and return an error reponse
2074 * for when rate limiting has triggered.
2076 public function rateLimited() {
2078 $this->setPageTitle(wfMsg('actionthrottled'));
2079 $this->setRobotPolicy( 'noindex,follow' );
2080 $this->setArticleRelated( false );
2081 $this->enableClientCache( false );
2082 $this->mRedirect
= '';
2084 $this->setStatusCode(503);
2085 $this->addWikiMsg( 'actionthrottledtext' );
2087 $this->returnToMain( null, $this->getTitle() );
2091 * Show an "add new section" link?
2095 public function showNewSectionLink() {
2096 return $this->mNewSectionLink
;
2100 * Forcibly hide the new section link?
2104 public function forceHideNewSectionLink() {
2105 return $this->mHideNewSectionLink
;
2109 * Show a warning about slave lag
2111 * If the lag is higher than $wgSlaveLagCritical seconds,
2112 * then the warning is a bit more obvious. If the lag is
2113 * lower than $wgSlaveLagWarning, then no warning is shown.
2115 * @param int $lag Slave lag
2117 public function showLagWarning( $lag ) {
2118 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2119 if( $lag >= $wgSlaveLagWarning ) {
2120 $message = $lag < $wgSlaveLagCritical
2123 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2124 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2129 * Add a wikitext-formatted message to the output.
2130 * This is equivalent to:
2132 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2134 public function addWikiMsg( /*...*/ ) {
2135 $args = func_get_args();
2136 $name = array_shift( $args );
2137 $this->addWikiMsgArray( $name, $args );
2141 * Add a wikitext-formatted message to the output.
2142 * Like addWikiMsg() except the parameters are taken as an array
2143 * instead of a variable argument list.
2145 * $options is passed through to wfMsgExt(), see that function for details.
2147 public function addWikiMsgArray( $name, $args, $options = array() ) {
2148 $options[] = 'parse';
2149 $text = wfMsgExt( $name, $options, $args );
2150 $this->addHTML( $text );
2154 * This function takes a number of message/argument specifications, wraps them in
2155 * some overall structure, and then parses the result and adds it to the output.
2157 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2158 * on. The subsequent arguments may either be strings, in which case they are the
2159 * message names, or arrays, in which case the first element is the message name,
2160 * and subsequent elements are the parameters to that message.
2162 * The special named parameter 'options' in a message specification array is passed
2163 * through to the $options parameter of wfMsgExt().
2165 * Don't use this for messages that are not in users interface language.
2169 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2173 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2175 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2176 $msgSpecs = func_get_args();
2177 array_shift( $msgSpecs );
2178 $msgSpecs = array_values( $msgSpecs );
2180 foreach ( $msgSpecs as $n => $spec ) {
2182 if ( is_array( $spec ) ) {
2184 $name = array_shift( $args );
2185 if ( isset( $args['options'] ) ) {
2186 $options = $args['options'];
2187 unset( $args['options'] );
2193 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2195 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );