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 // The most recent revision ID of any wikiPage script that is grouped in the script request
20 var $mLatestScriptRevID = 0;
22 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
23 var $mTemplateIds = array();
26 var $mSuppressQuickbar = false;
27 var $mOnloadHandler = '';
28 var $mDoNothing = false;
29 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
30 var $mIsArticleRelated = true;
31 protected $mParserOptions = null; // lazy initialised, use parserOptions()
32 var $mShowFeedLinks = false;
33 var $mFeedLinksAppendQuery = false;
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 $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgEnableScriptLoader, $wgScriptPath;
124 if( substr( $file, 0, 1 ) == '/' ) {
127 $path = "{$wgStylePath}/common/{$file}";
130 if( $wgEnableScriptLoader ) {
131 if( strpos( $path, $wgScript ) !== false ) {
132 $reqPath = str_replace( $wgScript . '?', '', $path );
133 $reqArgs = explode( '&', $reqPath );
136 foreach( $reqArgs as $arg ) {
137 list( $key, $var ) = explode( '=', $arg );
138 $reqSet[$key] = $var;
141 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
142 // Extract any extra parameters (for now just skin)
143 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
144 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
145 $this->mScriptLoaderClassList
[] = 'WT:' . $reqSet['title'] . $ext_param ;
146 // Add the title revision to the key.
147 // If there is no title, we will just use $wgStyleVersion,
148 // which should be updated on the relevant commits.
149 $t = Title
::newFromText( $reqSet['title'] );
150 if( $t && $t->exists() ) {
151 if( $t->getLatestRevID() > $this->mLatestScriptRevID
)
152 $this->mLatestScriptRevID
= $t->getLatestRevID();
158 // If the class can be determined, add it to the class list to be loaded later
159 $js_class = $this->getJsClassFromPath( $path );
161 $this->mScriptLoaderClassList
[] = $js_class;
166 // If the script loader could not be used, just add the script to the header
167 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
171 * Add the core scripts that are included on every page, for later output into the header
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgStylePath, $wgEnableJS2system;
175 // @todo We should deprecate wikibits in favor of mv_embed and jQuery
177 if( $wgEnableJS2system ){
178 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
180 $core_classes = array( 'wikibits' );
183 if( $wgEnableScriptLoader ){
184 $this->mScripts
= $this->getScriptLoaderJs( $core_classes ) . $this->mScripts
;
187 foreach( $core_classes as $s ){
188 if( isset( $wgJSAutoloadLocalClasses[$s] ) ){
189 $path = $wgJSAutoloadLocalClasses[$s];
190 // @fixme this is an awful hack
191 if( substr( $path, 0, 4 ) == "http" ||
substr( $path, 0, 1 ) == '/' ) {
192 // Assume a full or local path
193 } elseif( substr( $path, 0, 6 ) == "skins/" ) {
194 $path = $wgStylePath . substr( $path, 5 );
196 $path = $wgScriptPath . "/" . $path;
198 $so .= Html
::linkedScript( $path . "?" . $this->getURIDparam() );
201 $this->mScripts
= $so . $this->mScripts
;
206 * @param $js_class string Name of the JavaScript class
207 * @return boolean False if the class wasn't found, true on success
209 function addScriptClass( $js_class ){
210 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
211 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath;
213 if( isset( $wgJSAutoloadClasses[$js_class] )
214 ||
isset( $wgJSAutoloadLocalClasses[$js_class] ) )
216 if( $wgEnableScriptLoader ) {
217 // Register it with the script loader
218 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ) {
219 $this->mScriptLoaderClassList
[] = $js_class;
222 // Source the script directly
223 $path = $wgScriptPath . '/';
224 if( isset( $wgJSAutoloadClasses[$js_class] ) ) {
225 $path .= $wgJSAutoloadClasses[$js_class];
226 } elseif( isset( $wgJSAutoloadLocalClasses[$js_class] ) ) {
227 $path .= $wgJSAutoloadLocalClasses[$js_class];
229 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $wgStyleVersion;
230 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
234 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
235 return false; // could not find the class
239 * Get the <script> tag which will invoke the script loader
240 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
242 function getScriptLoaderJs( $classAry = array() ) {
243 global $wgRequest, $wgDebugJavaScript;
244 // If no class array was provided, use mScriptLoaderClassList
245 if( !count( $classAry ) ) {
246 $classAry = $this->mScriptLoaderClassList
;
248 $class_list = implode( ',', $classAry );
250 $debug_param = ( $wgDebugJavaScript ||
251 $wgRequest->getVal( 'debug' ) == 'true' ||
252 $wgRequest->getVal( 'debug' ) == '1' )
253 ?
'&debug=true' : '';
255 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
256 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) );
260 * Get the unique request ID parameter for the script-loader request
262 function getURIDparam( $classAry = array() ) {
263 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
264 if( $wgDebugJavaScript ) {
265 return 'urid=' . time();
268 if($wgScriptModifiedCheck) {
269 foreach( $classAry as $class ) {
270 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
272 $cur_ftime = filemtime ( $IP ."/". $js_path );
273 if( $cur_ftime > $ftime )
278 $urid = "urid={$wgStyleVersion}";
280 // Add the latest revision ID if we have it
281 if($this->mLatestScriptRevID
!= 0 )
282 $urid .= "_{$this->mLatestScriptRevID}";
284 // Add the file modification time
293 * Given a script path, get the JS class name, or false if no such path is registered.
294 * @param $path string
296 function getJsClassFromPath( $path ) {
297 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
299 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
300 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
301 $js_path = "{$wgScriptPath}/{$js_path}";
302 if( $path == $js_path )
309 * Add a self-contained script tag with the given contents
310 * @param string $script JavaScript text, no <script> tags
312 function addInlineScript( $script ) {
313 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
317 * Get all registered JS and CSS tags for the header.
319 function getScript() {
320 global $wgEnableScriptLoader;
321 if( $wgEnableScriptLoader ){
322 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
324 return $this->mScripts
. $this->getHeadItems();
328 function getHeadItems() {
330 foreach ( $this->mHeadItems
as $item ) {
336 function addHeadItem( $name, $value ) {
337 $this->mHeadItems
[$name] = $value;
340 function hasHeadItem( $name ) {
341 return isset( $this->mHeadItems
[$name] );
344 function setETag($tag) { $this->mETag
= $tag; }
345 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
346 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
348 function addLink( $linkarr ) {
349 # $linkarr should be an associative array of attributes. We'll escape on output.
350 array_push( $this->mLinktags
, $linkarr );
353 # Get all links added by extensions
354 function getExtStyle() {
355 return $this->mExtStyles
;
358 function addMetadataLink( $linkarr ) {
359 # note: buggy CC software only reads first "meta" link
360 static $haveMeta = false;
361 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
362 $this->addLink( $linkarr );
367 * checkLastModified tells the client to use the client-cached page if
368 * possible. If sucessful, the OutputPage is disabled so that
369 * any future call to OutputPage->output() have no effect.
371 * Side effect: sets mLastModified for Last-Modified header
373 * @return bool True iff cache-ok headers was sent.
375 function checkLastModified( $timestamp ) {
376 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
378 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
379 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
382 if( !$wgCachePages ) {
383 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
386 if( $wgUser->getOption( 'nocache' ) ) {
387 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
391 $timestamp = wfTimestamp( TS_MW
, $timestamp );
392 $modifiedTimes = array(
393 'page' => $timestamp,
394 'user' => $wgUser->getTouched(),
395 'epoch' => $wgCacheEpoch
397 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
399 $maxModified = max( $modifiedTimes );
400 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
402 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
403 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
409 foreach ( $modifiedTimes as $name => $value ) {
410 if ( $info !== '' ) {
413 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
416 # IE sends sizes after the date like this:
417 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
418 # this breaks strtotime().
419 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
421 wfSuppressWarnings(); // E_STRICT system time bitching
422 $clientHeaderTime = strtotime( $clientHeader );
424 if ( !$clientHeaderTime ) {
425 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
428 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
430 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
431 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
432 wfDebug( __METHOD__
. ": effective Last-Modified: " .
433 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
434 if( $clientHeaderTime < $maxModified ) {
435 wfDebug( __METHOD__
. ": STALE, $info\n", false );
440 # Give a 304 response code and disable body output
441 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
442 ini_set('zlib.output_compression', 0);
443 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
444 $this->sendCacheControl();
447 // Don't output a compressed blob when using ob_gzhandler;
448 // it's technically against HTTP spec and seems to confuse
449 // Firefox when the response gets split over two packets.
450 wfClearOutputBuffers();
455 function setPageTitleActionText( $text ) {
456 $this->mPageTitleActionText
= $text;
459 function getPageTitleActionText () {
460 if ( isset( $this->mPageTitleActionText
) ) {
461 return $this->mPageTitleActionText
;
466 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
468 * @param $policy string The literal string to output as the contents of
469 * the meta tag. Will be parsed according to the spec and output in
473 public function setRobotPolicy( $policy ) {
474 $policy = Article
::formatRobotPolicy( $policy );
476 if( isset( $policy['index'] ) ){
477 $this->setIndexPolicy( $policy['index'] );
479 if( isset( $policy['follow'] ) ){
480 $this->setFollowPolicy( $policy['follow'] );
485 * Set the index policy for the page, but leave the follow policy un-
488 * @param $policy string Either 'index' or 'noindex'.
491 public function setIndexPolicy( $policy ) {
492 $policy = trim( $policy );
493 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
494 $this->mIndexPolicy
= $policy;
499 * Set the follow policy for the page, but leave the index policy un-
502 * @param $policy string Either 'follow' or 'nofollow'.
505 public function setFollowPolicy( $policy ) {
506 $policy = trim( $policy );
507 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
508 $this->mFollowPolicy
= $policy;
513 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
515 public function setHTMLTitle( $name ) {
516 $this->mHTMLtitle
= $name;
520 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
521 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
522 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
523 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
525 public function setPageTitle( $name ) {
527 $name = $wgContLang->convert( $name, true );
528 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
529 # but leave "<i>foobar</i>" alone
530 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
531 $this->mPagetitle
= $nameWithTags;
533 $taction = $this->getPageTitleActionText();
534 if( !empty( $taction ) ) {
535 $name .= ' - '.$taction;
538 # change "<i>foo&bar</i>" to "foo&bar"
539 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
542 public function setTitle( $t ) {
546 public function getTitle() {
547 if ( $this->mTitle
instanceof Title
) {
548 return $this->mTitle
;
551 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
557 public function getHTMLTitle() { return $this->mHTMLtitle
; }
558 public function getPageTitle() { return $this->mPagetitle
; }
559 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
560 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
561 public function getSubtitle() { return $this->mSubtitle
; }
562 public function isArticle() { return $this->mIsarticle
; }
563 public function setPrintable() { $this->mPrintable
= true; }
564 public function isPrintable() { return $this->mPrintable
; }
565 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
566 public function isSyndicated() { return $this->mShowFeedLinks
; }
567 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
568 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
569 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
570 public function getOnloadHandler() { return $this->mOnloadHandler
; }
571 public function disable() { $this->mDoNothing
= true; }
572 public function isDisabled() { return $this->mDoNothing
; }
574 public function setArticleRelated( $v ) {
575 $this->mIsArticleRelated
= $v;
577 $this->mIsarticle
= false;
580 public function setArticleFlag( $v ) {
581 $this->mIsarticle
= $v;
583 $this->mIsArticleRelated
= $v;
587 public function isArticleRelated() { return $this->mIsArticleRelated
; }
589 public function getLanguageLinks() { return $this->mLanguageLinks
; }
590 public function addLanguageLinks($newLinkArray) {
591 $this->mLanguageLinks +
= $newLinkArray;
593 public function setLanguageLinks($newLinkArray) {
594 $this->mLanguageLinks
= $newLinkArray;
597 public function getCategoryLinks() {
598 return $this->mCategoryLinks
;
602 * Add an array of categories, with names in the keys
604 public function addCategoryLinks( $categories ) {
605 global $wgUser, $wgContLang;
607 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
611 # Add the links to a LinkBatch
612 $arr = array( NS_CATEGORY
=> $categories );
614 $lb->setArray( $arr );
616 # Fetch existence plus the hiddencat property
617 $dbr = wfGetDB( DB_SLAVE
);
618 $pageTable = $dbr->tableName( 'page' );
619 $where = $lb->constructSet( 'page', $dbr );
620 $propsTable = $dbr->tableName( 'page_props' );
621 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
622 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
623 $res = $dbr->query( $sql, __METHOD__
);
625 # Add the results to the link cache
626 $lb->addResultToCache( LinkCache
::singleton(), $res );
628 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
629 $categories = array_combine( array_keys( $categories ),
630 array_fill( 0, count( $categories ), 'normal' ) );
632 # Mark hidden categories
633 foreach ( $res as $row ) {
634 if ( isset( $row->pp_value
) ) {
635 $categories[$row->page_title
] = 'hidden';
639 # Add the remaining categories to the skin
640 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
641 $sk = $wgUser->getSkin();
642 foreach ( $categories as $category => $type ) {
643 $origcategory = $category;
644 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
645 $wgContLang->findVariantLink( $category, $title, true );
646 if ( $category != $origcategory )
647 if ( array_key_exists( $category, $categories ) )
649 $text = $wgContLang->convertHtml( $title->getText() );
650 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
655 public function setCategoryLinks($categories) {
656 $this->mCategoryLinks
= array();
657 $this->addCategoryLinks($categories);
660 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
661 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
663 public function disallowUserJs() { $this->mAllowUserJs
= false; }
664 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
666 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
667 public function addHTML( $text ) { $this->mBodytext
.= $text; }
668 public function clearHTML() { $this->mBodytext
= ''; }
669 public function getHTML() { return $this->mBodytext
; }
670 public function debug( $text ) { $this->mDebugtext
.= $text; }
673 public function setParserOptions( $options ) {
674 wfDeprecated( __METHOD__
);
675 return $this->parserOptions( $options );
678 public function parserOptions( $options = null ) {
679 if ( !$this->mParserOptions
) {
680 $this->mParserOptions
= new ParserOptions
;
682 return wfSetVar( $this->mParserOptions
, $options );
686 * Set the revision ID which will be seen by the wiki text parser
687 * for things such as embedded {{REVISIONID}} variable use.
688 * @param mixed $revid an integer, or NULL
689 * @return mixed previous value
691 public function setRevisionId( $revid ) {
692 $val = is_null( $revid ) ?
null : intval( $revid );
693 return wfSetVar( $this->mRevisionId
, $val );
696 public function getRevisionId() {
697 return $this->mRevisionId
;
701 * Convert wikitext to HTML and add it to the buffer
702 * Default assumes that the current page title will
705 * @param string $text
706 * @param bool $linestart
708 public function addWikiText( $text, $linestart = true ) {
709 $title = $this->getTitle(); // Work arround E_STRICT
710 $this->addWikiTextTitle( $text, $title, $linestart );
713 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
714 $this->addWikiTextTitle($text, $title, $linestart);
717 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
718 $this->addWikiTextTitle( $text, $title, $linestart, true );
721 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
724 wfProfileIn( __METHOD__
);
726 wfIncrStats( 'pcache_not_possible' );
728 $popts = $this->parserOptions();
729 $oldTidy = $popts->setTidy( $tidy );
731 $parserOutput = $wgParser->parse( $text, $title, $popts,
732 $linestart, true, $this->mRevisionId
);
734 $popts->setTidy( $oldTidy );
736 $this->addParserOutput( $parserOutput );
738 wfProfileOut( __METHOD__
);
743 * @param ParserOutput object &$parserOutput
745 public function addParserOutputNoText( &$parserOutput ) {
746 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
748 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
749 $this->addCategoryLinks( $parserOutput->getCategories() );
750 $this->mNewSectionLink
= $parserOutput->getNewSection();
751 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
753 $this->mParseWarnings
= $parserOutput->getWarnings();
754 if ( $parserOutput->getCacheTime() == -1 ) {
755 $this->enableClientCache( false );
757 $this->mNoGallery
= $parserOutput->getNoGallery();
758 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
760 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
761 if ( isset( $this->mTemplateIds
[$ns] ) ) {
762 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
764 $this->mTemplateIds
[$ns] = $dbks;
768 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
769 $this->setPageTitle( $dt );
770 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
771 $this->setPageTitle( $title );
773 // Hooks registered in the object
774 global $wgParserOutputHooks;
775 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
776 list( $hookName, $data ) = $hookInfo;
777 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
778 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
782 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
787 * @param ParserOutput &$parserOutput
789 function addParserOutput( &$parserOutput ) {
790 $this->addParserOutputNoText( $parserOutput );
791 $text = $parserOutput->getText();
792 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
793 $this->addHTML( $text );
797 * Add wikitext to the buffer, assuming that this is the primary text for a page view
798 * Saves the text into the parser cache if possible.
800 * @param string $text
801 * @param Article $article
803 * @deprecated Use Article::outputWikitext
805 public function addPrimaryWikiText( $text, $article, $cache = true ) {
808 wfDeprecated( __METHOD__
);
810 $popts = $this->parserOptions();
811 $popts->setTidy(true);
812 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
813 $popts, true, true, $this->mRevisionId
);
814 $popts->setTidy(false);
815 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
816 $parserCache = ParserCache
::singleton();
817 $parserCache->save( $parserOutput, $article, $popts);
820 $this->addParserOutput( $parserOutput );
824 * @deprecated use addWikiTextTidy()
826 public function addSecondaryWikiText( $text, $linestart = true ) {
827 wfDeprecated( __METHOD__
);
828 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
832 * Add wikitext with tidy enabled
834 public function addWikiTextTidy( $text, $linestart = true ) {
835 $title = $this->getTitle();
836 $this->addWikiTextTitleTidy($text, $title, $linestart);
841 * Add the output of a QuickTemplate to the output buffer
843 * @param QuickTemplate $template
845 public function addTemplate( &$template ) {
847 $template->execute();
848 $this->addHTML( ob_get_contents() );
853 * Parse wikitext and return the HTML.
855 * @param string $text
856 * @param bool $linestart Is this the start of a line?
857 * @param bool $interface ??
859 public function parse( $text, $linestart = true, $interface = false ) {
861 if( is_null( $this->getTitle() ) ) {
862 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
864 $popts = $this->parserOptions();
865 if ( $interface) { $popts->setInterfaceMessage(true); }
866 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
867 $linestart, true, $this->mRevisionId
);
868 if ( $interface) { $popts->setInterfaceMessage(false); }
869 return $parserOutput->getText();
872 /** Parse wikitext, strip paragraphs, and return the HTML. */
873 public function parseInline( $text, $linestart = true, $interface = false ) {
874 $parsed = $this->parse( $text, $linestart, $interface );
877 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
885 * @param Article $article
890 * @return bool True if successful, else false.
892 public function tryParserCache( &$article ) {
893 wfDeprecated( __METHOD__
);
894 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
896 if ($parserOutput !== false) {
897 $this->addParserOutput( $parserOutput );
905 * @param int $maxage Maximum cache time on the Squid, in seconds.
907 public function setSquidMaxage( $maxage ) {
908 $this->mSquidMaxage
= $maxage;
912 * Use enableClientCache(false) to force it to send nocache headers
915 public function enableClientCache( $state ) {
916 return wfSetVar( $this->mEnableClientCache
, $state );
919 function getCacheVaryCookies() {
920 global $wgCookiePrefix, $wgCacheVaryCookies;
922 if ( $cookies === null ) {
923 $cookies = array_merge(
925 "{$wgCookiePrefix}Token",
926 "{$wgCookiePrefix}LoggedOut",
931 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
936 function uncacheableBecauseRequestVars() {
938 return $wgRequest->getText('useskin', false) === false
939 && $wgRequest->getText('uselang', false) === false;
943 * Check if the request has a cache-varying cookie header
944 * If it does, it's very important that we don't allow public caching
946 function haveCacheVaryCookies() {
948 $cookieHeader = $wgRequest->getHeader( 'cookie' );
949 if ( $cookieHeader === false ) {
952 $cvCookies = $this->getCacheVaryCookies();
953 foreach ( $cvCookies as $cookieName ) {
954 # Check for a simple string match, like the way squid does it
955 if ( strpos( $cookieHeader, $cookieName ) ) {
956 wfDebug( __METHOD__
.": found $cookieName\n" );
960 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
964 /** Get a complete X-Vary-Options header */
965 public function getXVO() {
966 $cvCookies = $this->getCacheVaryCookies();
967 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
969 foreach ( $cvCookies as $cookieName ) {
975 $xvo .= 'string-contains=' . $cookieName;
980 public function sendCacheControl() {
981 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
983 $response = $wgRequest->response();
984 if ($wgUseETag && $this->mETag
)
985 $response->header("ETag: $this->mETag");
987 # don't serve compressed data to clients who can't handle it
988 # maintain different caches for logged-in users and non-logged in ones
989 $response->header( 'Vary: Accept-Encoding, Cookie' );
992 # Add an X-Vary-Options header for Squid with Wikimedia patches
993 $response->header( $this->getXVO() );
996 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
997 if( $wgUseSquid && session_id() == '' &&
998 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1001 # We'll purge the proxy cache explicitly, but require end user agents
1002 # to revalidate against the proxy on each visit.
1003 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1004 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1005 # start with a shorter timeout for initial testing
1006 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1007 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1008 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1010 # We'll purge the proxy cache for anons explicitly, but require end user agents
1011 # to revalidate against the proxy on each visit.
1012 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1013 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1014 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1015 # start with a shorter timeout for initial testing
1016 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1017 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1020 # We do want clients to cache if they can, but they *must* check for updates
1021 # on revisiting the page.
1022 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1023 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1024 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1026 if($this->mLastModified
) {
1027 $response->header( "Last-Modified: {$this->mLastModified}" );
1030 wfDebug( __METHOD__
. ": no caching **\n", false );
1032 # In general, the absence of a last modified header should be enough to prevent
1033 # the client from using its cache. We send a few other things just to make sure.
1034 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1035 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1036 $response->header( 'Pragma: no-cache' );
1041 * Finally, all the text has been munged and accumulated into
1042 * the object, let's actually output it:
1044 public function output() {
1045 global $wgUser, $wgOutputEncoding, $wgRequest;
1046 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1047 global $wgUseAjax, $wgAjaxWatch;
1048 global $wgEnableMWSuggest, $wgUniversalEditButton;
1051 if( $this->mDoNothing
){
1054 wfProfileIn( __METHOD__
);
1055 if ( '' != $this->mRedirect
) {
1056 # Standards require redirect URLs to be absolute
1057 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1058 if( $this->mRedirectCode
== '301') {
1059 if( !$wgDebugRedirects ) {
1060 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1062 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1064 $this->sendCacheControl();
1066 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1067 if( $wgDebugRedirects ) {
1068 $url = htmlspecialchars( $this->mRedirect
);
1069 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1070 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1071 print "</body>\n</html>\n";
1073 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1075 wfProfileOut( __METHOD__
);
1078 elseif ( $this->mStatusCode
)
1080 $statusMessage = array(
1082 101 => 'Switching Protocols',
1083 102 => 'Processing',
1087 203 => 'Non-Authoritative Information',
1088 204 => 'No Content',
1089 205 => 'Reset Content',
1090 206 => 'Partial Content',
1091 207 => 'Multi-Status',
1092 300 => 'Multiple Choices',
1093 301 => 'Moved Permanently',
1096 304 => 'Not Modified',
1098 307 => 'Temporary Redirect',
1099 400 => 'Bad Request',
1100 401 => 'Unauthorized',
1101 402 => 'Payment Required',
1104 405 => 'Method Not Allowed',
1105 406 => 'Not Acceptable',
1106 407 => 'Proxy Authentication Required',
1107 408 => 'Request Timeout',
1110 411 => 'Length Required',
1111 412 => 'Precondition Failed',
1112 413 => 'Request Entity Too Large',
1113 414 => 'Request-URI Too Large',
1114 415 => 'Unsupported Media Type',
1115 416 => 'Request Range Not Satisfiable',
1116 417 => 'Expectation Failed',
1117 422 => 'Unprocessable Entity',
1119 424 => 'Failed Dependency',
1120 500 => 'Internal Server Error',
1121 501 => 'Not Implemented',
1122 502 => 'Bad Gateway',
1123 503 => 'Service Unavailable',
1124 504 => 'Gateway Timeout',
1125 505 => 'HTTP Version Not Supported',
1126 507 => 'Insufficient Storage'
1129 if ( $statusMessage[$this->mStatusCode
] )
1130 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1133 $sk = $wgUser->getSkin();
1135 // Add our core scripts to output
1136 $this->addCoreScripts2Top();
1139 $this->addScriptFile( 'ajax.js' );
1141 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1143 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1144 $this->addScriptFile( 'ajaxwatch.js' );
1147 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1148 $this->addScriptFile( 'mwsuggest.js' );
1152 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1153 $this->addScriptFile( 'rightclickedit.js' );
1156 global $wgUseAJAXCategories;
1157 if ($wgUseAJAXCategories) {
1158 $this->addScriptClass( 'ajaxCategories' );
1161 if( $wgUniversalEditButton ) {
1162 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1163 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1164 // Original UniversalEditButton
1165 $msg = wfMsg('edit');
1166 $this->addLink( array(
1167 'rel' => 'alternate',
1168 'type' => 'application/x-wiki',
1170 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1172 // Alternate edit link
1173 $this->addLink( array(
1176 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1181 # Buffer output; final headers may depend on later processing
1184 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1185 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1187 if ($this->mArticleBodyOnly
) {
1188 $this->out($this->mBodytext
);
1190 // Hook that allows last minute changes to the output page, e.g.
1191 // adding of CSS or Javascript by extensions.
1192 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1194 wfProfileIn( 'Output-skin' );
1195 $sk->outputPage( $this );
1196 wfProfileOut( 'Output-skin' );
1199 $this->sendCacheControl();
1201 wfProfileOut( __METHOD__
);
1205 * Actually output something with print(). Performs an iconv to the
1206 * output encoding, if needed.
1207 * @param string $ins The string to output
1209 public function out( $ins ) {
1210 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1211 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1214 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1215 if ( false === $outs ) { $outs = $ins; }
1223 public static function setEncodings() {
1224 global $wgInputEncoding, $wgOutputEncoding;
1227 $wgInputEncoding = strtolower( $wgInputEncoding );
1229 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1230 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1233 $wgOutputEncoding = $wgInputEncoding;
1237 * Deprecated, use wfReportTime() instead.
1241 public function reportTime() {
1242 wfDeprecated( __METHOD__
);
1243 $time = wfReportTime();
1248 * Produce a "user is blocked" page.
1250 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1253 function blockedPage( $return = true ) {
1254 global $wgUser, $wgContLang, $wgLang;
1256 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1257 $this->setRobotPolicy( 'noindex,nofollow' );
1258 $this->setArticleRelated( false );
1260 $name = User
::whoIs( $wgUser->blockedBy() );
1261 $reason = $wgUser->blockedFor();
1262 if( $reason == '' ) {
1263 $reason = wfMsg( 'blockednoreason' );
1265 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1268 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1270 $blockid = $wgUser->mBlock
->mId
;
1272 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1273 if ( $blockExpiry == 'infinity' ) {
1274 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1275 // Search for localization in 'ipboptions'
1276 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1277 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1278 if ( strpos( $option, ":" ) === false )
1280 list( $show, $value ) = explode( ":", $option );
1281 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1282 $blockExpiry = $show;
1287 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1290 if ( $wgUser->mBlock
->mAuto
) {
1291 $msg = 'autoblockedtext';
1293 $msg = 'blockedtext';
1296 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1297 * This could be a username, an ip range, or a single ip. */
1298 $intended = $wgUser->mBlock
->mAddress
;
1300 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1302 # Don't auto-return to special pages
1304 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1305 $this->returnToMain( null, $return );
1310 * Output a standard error page
1312 * @param string $title Message key for page title
1313 * @param string $msg Message key for page text
1314 * @param array $params Message parameters
1316 public function showErrorPage( $title, $msg, $params = array() ) {
1317 if ( $this->getTitle() ) {
1318 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1320 $this->setPageTitle( wfMsg( $title ) );
1321 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1322 $this->setRobotPolicy( 'noindex,nofollow' );
1323 $this->setArticleRelated( false );
1324 $this->enableClientCache( false );
1325 $this->mRedirect
= '';
1326 $this->mBodytext
= '';
1328 array_unshift( $params, 'parse' );
1329 array_unshift( $params, $msg );
1330 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1332 $this->returnToMain();
1336 * Output a standard permission error page
1338 * @param array $errors Error message keys
1340 public function showPermissionsErrorPage( $errors, $action = null )
1342 $this->mDebugtext
.= 'Original title: ' .
1343 $this->getTitle()->getPrefixedText() . "\n";
1344 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1345 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1346 $this->setRobotPolicy( 'noindex,nofollow' );
1347 $this->setArticleRelated( false );
1348 $this->enableClientCache( false );
1349 $this->mRedirect
= '';
1350 $this->mBodytext
= '';
1351 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1355 public function errorpage( $title, $msg ) {
1356 wfDeprecated( __METHOD__
);
1357 throw new ErrorPageError( $title, $msg );
1361 * Display an error page indicating that a given version of MediaWiki is
1362 * required to use it
1364 * @param mixed $version The version of MediaWiki needed to use the page
1366 public function versionRequired( $version ) {
1367 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1368 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1369 $this->setRobotPolicy( 'noindex,nofollow' );
1370 $this->setArticleRelated( false );
1371 $this->mBodytext
= '';
1373 $this->addWikiMsg( 'versionrequiredtext', $version );
1374 $this->returnToMain();
1378 * Display an error page noting that a given permission bit is required.
1380 * @param string $permission key required
1382 public function permissionRequired( $permission ) {
1385 $this->setPageTitle( wfMsg( 'badaccess' ) );
1386 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1387 $this->setRobotPolicy( 'noindex,nofollow' );
1388 $this->setArticleRelated( false );
1389 $this->mBodytext
= '';
1391 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1392 User
::getGroupsWithPermission( $permission ) );
1394 $this->addWikiMsg( 'badaccess-groups',
1395 $wgLang->commaList( $groups ),
1398 $this->addWikiMsg( 'badaccess-group0' );
1400 $this->returnToMain();
1404 * Use permissionRequired.
1407 public function sysopRequired() {
1408 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1412 * Use permissionRequired.
1415 public function developerRequired() {
1416 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1420 * Produce the stock "please login to use the wiki" page
1422 public function loginToUse() {
1423 global $wgUser, $wgContLang;
1425 if( $wgUser->isLoggedIn() ) {
1426 $this->permissionRequired( 'read' );
1430 $skin = $wgUser->getSkin();
1432 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1433 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1434 $this->setRobotPolicy( 'noindex,nofollow' );
1435 $this->setArticleFlag( false );
1437 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1438 $loginLink = $skin->link(
1440 wfMsgHtml( 'loginreqlink' ),
1442 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1443 array( 'known', 'noclasses' )
1445 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1446 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1448 # Don't return to the main page if the user can't read it
1449 # otherwise we'll end up in a pointless loop
1450 $mainPage = Title
::newMainPage();
1451 if( $mainPage->userCanRead() )
1452 $this->returnToMain( null, $mainPage );
1456 public function databaseError( $fname, $sql, $error, $errno ) {
1457 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1461 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1462 * @return string The wikitext error-messages, formatted into a list.
1464 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1465 if ($action == null) {
1466 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1469 $action_desc = wfMsgNoTrans( "action-$action" );
1470 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1473 if (count( $errors ) > 1) {
1474 $text .= '<ul class="permissions-errors">' . "\n";
1476 foreach( $errors as $error )
1479 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1484 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1491 * Display a page stating that the Wiki is in read-only mode,
1492 * and optionally show the source of the page that the user
1493 * was trying to edit. Should only be called (for this
1494 * purpose) after wfReadOnly() has returned true.
1496 * For historical reasons, this function is _also_ used to
1497 * show the error message when a user tries to edit a page
1498 * they are not allowed to edit. (Unless it's because they're
1499 * blocked, then we show blockedPage() instead.) In this
1500 * case, the second parameter should be set to true and a list
1501 * of reasons supplied as the third parameter.
1503 * @todo Needs to be split into multiple functions.
1505 * @param string $source Source code to show (or null).
1506 * @param bool $protected Is this a permissions error?
1507 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1509 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1511 $skin = $wgUser->getSkin();
1513 $this->setRobotPolicy( 'noindex,nofollow' );
1514 $this->setArticleRelated( false );
1516 // If no reason is given, just supply a default "I can't let you do
1517 // that, Dave" message. Should only occur if called by legacy code.
1518 if ( $protected && empty($reasons) ) {
1519 $reasons[] = array( 'badaccess-group0' );
1522 if ( !empty($reasons) ) {
1523 // Permissions error
1525 $this->setPageTitle( wfMsg( 'viewsource' ) );
1534 array( 'known', 'noclasses' )
1539 $this->setPageTitle( wfMsg( 'badaccess' ) );
1541 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1543 // Wiki is read only
1544 $this->setPageTitle( wfMsg( 'readonly' ) );
1545 $reason = wfReadOnlyReason();
1546 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1549 // Show source, if supplied
1550 if( is_string( $source ) ) {
1551 $this->addWikiMsg( 'viewsourcetext' );
1552 $text = Xml
::openElement( 'textarea',
1553 array( 'id' => 'wpTextbox1',
1554 'name' => 'wpTextbox1',
1555 'cols' => $wgUser->getOption( 'cols' ),
1556 'rows' => $wgUser->getOption( 'rows' ),
1557 'readonly' => 'readonly' ) );
1558 $text .= htmlspecialchars( $source );
1559 $text .= Xml
::closeElement( 'textarea' );
1560 $this->addHTML( $text );
1562 // Show templates used by this article
1563 $skin = $wgUser->getSkin();
1564 $article = new Article( $this->getTitle() );
1565 $this->addHTML( "<div class='templatesUsed'>
1566 {$skin->formatTemplates( $article->getUsedTemplates() )}
1571 # If the title doesn't exist, it's fairly pointless to print a return
1572 # link to it. After all, you just tried editing it and couldn't, so
1573 # what's there to do there?
1574 if( $this->getTitle()->exists() ) {
1575 $this->returnToMain( null, $this->getTitle() );
1580 public function fatalError( $message ) {
1581 wfDeprecated( __METHOD__
);
1582 throw new FatalError( $message );
1586 public function unexpectedValueError( $name, $val ) {
1587 wfDeprecated( __METHOD__
);
1588 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1592 public function fileCopyError( $old, $new ) {
1593 wfDeprecated( __METHOD__
);
1594 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1598 public function fileRenameError( $old, $new ) {
1599 wfDeprecated( __METHOD__
);
1600 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1604 public function fileDeleteError( $name ) {
1605 wfDeprecated( __METHOD__
);
1606 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1610 public function fileNotFoundError( $name ) {
1611 wfDeprecated( __METHOD__
);
1612 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1615 public function showFatalError( $message ) {
1616 $this->setPageTitle( wfMsg( "internalerror" ) );
1617 $this->setRobotPolicy( "noindex,nofollow" );
1618 $this->setArticleRelated( false );
1619 $this->enableClientCache( false );
1620 $this->mRedirect
= '';
1621 $this->mBodytext
= $message;
1624 public function showUnexpectedValueError( $name, $val ) {
1625 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1628 public function showFileCopyError( $old, $new ) {
1629 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1632 public function showFileRenameError( $old, $new ) {
1633 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1636 public function showFileDeleteError( $name ) {
1637 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1640 public function showFileNotFoundError( $name ) {
1641 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1645 * Add a "return to" link pointing to a specified title
1647 * @param Title $title Title to link
1648 * @param string $query Query string
1650 public function addReturnTo( $title, $query = array() ) {
1652 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1653 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1654 $title, null, array(), $query ) );
1655 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1659 * Add a "return to" link pointing to a specified title,
1660 * or the title indicated in the request, or else the main page
1662 * @param null $unused No longer used
1663 * @param Title $returnto Title to return to
1665 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1668 if ( $returnto == null ) {
1669 $returnto = $wgRequest->getText( 'returnto' );
1672 if ( $returntoquery == null ) {
1673 $returntoquery = $wgRequest->getText( 'returntoquery' );
1676 if ( '' === $returnto ) {
1677 $returnto = Title
::newMainPage();
1680 if ( is_object( $returnto ) ) {
1681 $titleObj = $returnto;
1683 $titleObj = Title
::newFromText( $returnto );
1685 if ( !is_object( $titleObj ) ) {
1686 $titleObj = Title
::newMainPage();
1689 $this->addReturnTo( $titleObj, $returntoquery );
1693 * @return string The doctype, opening <html>, and head element.
1695 public function headElement( Skin
$sk ) {
1696 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1697 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1698 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1700 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1701 if ( $sk->commonPrintStylesheet() ) {
1702 $this->addStyle( 'common/wikiprintable.css', 'print' );
1704 $sk->setupUserCss( $this );
1708 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1709 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1712 if ( '' == $this->getHTMLTitle() ) {
1713 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1716 $dir = $wgContLang->getDir();
1719 $ret .= "<!doctype html>\n";
1720 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1722 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1723 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1724 foreach($wgXhtmlNamespaces as $tag => $ns) {
1725 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1727 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1731 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1732 $ret .= implode( "\n", array(
1733 $this->getHeadLinks(),
1734 $this->buildCssLinks(),
1735 $sk->getHeadScripts( $this ),
1736 $this->getHeadItems(),
1739 $ret .= Html
::inlineStyle( $sk->usercss
);
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", $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 // Even though we expect the media type to be lowercase, but here we
1899 // force it to lowercase to be safe.
1901 $options['media'] = $media;
1903 $options['condition'] = $condition;
1905 $options['dir'] = $dir;
1906 $this->styles
[$style] = $options;
1910 * Adds inline CSS styles
1911 * @param $style_css Mixed: inline CSS
1913 public function addInlineStyle( $style_css ){
1914 $this->mScripts
.= Html
::inlineStyle( $style_css );
1918 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1919 * These will be applied to various media & IE conditionals.
1921 public function buildCssLinks() {
1923 foreach( $this->styles
as $file => $options ) {
1924 $link = $this->styleLink( $file, $options );
1929 return implode( "\n", $links );
1932 protected function styleLink( $style, $options ) {
1935 if( isset( $options['dir'] ) ) {
1937 $siteDir = $wgContLang->getDir();
1938 if( $siteDir != $options['dir'] )
1942 if( isset( $options['media'] ) ) {
1943 $media = $this->transformCssMedia( $options['media'] );
1944 if( is_null( $media ) ) {
1951 if( substr( $style, 0, 1 ) == '/' ||
1952 substr( $style, 0, 5 ) == 'http:' ||
1953 substr( $style, 0, 6 ) == 'https:' ) {
1956 global $wgStylePath, $wgStyleVersion;
1957 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1960 $link = Html
::linkedStyle( $url, $media );
1962 if( isset( $options['condition'] ) ) {
1963 $condition = htmlspecialchars( $options['condition'] );
1964 $link = "<!--[if $condition]>$link<![endif]-->";
1969 function transformCssMedia( $media ) {
1970 global $wgRequest, $wgHandheldForIPhone;
1972 // Switch in on-screen display for media testing
1974 'printable' => 'print',
1975 'handheld' => 'handheld',
1977 foreach( $switches as $switch => $targetMedia ) {
1978 if( $wgRequest->getBool( $switch ) ) {
1979 if( $media == $targetMedia ) {
1981 } elseif( $media == 'screen' ) {
1987 // Expand longer media queries as iPhone doesn't grok 'handheld'
1988 if( $wgHandheldForIPhone ) {
1989 $mediaAliases = array(
1990 'screen' => 'screen and (min-device-width: 481px)',
1991 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1994 if( isset( $mediaAliases[$media] ) ) {
1995 $media = $mediaAliases[$media];
2003 * Turn off regular page output and return an error reponse
2004 * for when rate limiting has triggered.
2006 public function rateLimited() {
2008 $this->setPageTitle(wfMsg('actionthrottled'));
2009 $this->setRobotPolicy( 'noindex,follow' );
2010 $this->setArticleRelated( false );
2011 $this->enableClientCache( false );
2012 $this->mRedirect
= '';
2014 $this->setStatusCode(503);
2015 $this->addWikiMsg( 'actionthrottledtext' );
2017 $this->returnToMain( null, $this->getTitle() );
2021 * Show an "add new section" link?
2025 public function showNewSectionLink() {
2026 return $this->mNewSectionLink
;
2030 * Forcibly hide the new section link?
2034 public function forceHideNewSectionLink() {
2035 return $this->mHideNewSectionLink
;
2039 * Show a warning about slave lag
2041 * If the lag is higher than $wgSlaveLagCritical seconds,
2042 * then the warning is a bit more obvious. If the lag is
2043 * lower than $wgSlaveLagWarning, then no warning is shown.
2045 * @param int $lag Slave lag
2047 public function showLagWarning( $lag ) {
2048 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2049 if( $lag >= $wgSlaveLagWarning ) {
2050 $message = $lag < $wgSlaveLagCritical
2053 $warning = wfMsgExt( $message, 'parse', $lag );
2054 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
2059 * Add a wikitext-formatted message to the output.
2060 * This is equivalent to:
2062 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2064 public function addWikiMsg( /*...*/ ) {
2065 $args = func_get_args();
2066 $name = array_shift( $args );
2067 $this->addWikiMsgArray( $name, $args );
2071 * Add a wikitext-formatted message to the output.
2072 * Like addWikiMsg() except the parameters are taken as an array
2073 * instead of a variable argument list.
2075 * $options is passed through to wfMsgExt(), see that function for details.
2077 public function addWikiMsgArray( $name, $args, $options = array() ) {
2078 $options[] = 'parse';
2079 $text = wfMsgExt( $name, $options, $args );
2080 $this->addHTML( $text );
2084 * This function takes a number of message/argument specifications, wraps them in
2085 * some overall structure, and then parses the result and adds it to the output.
2087 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2088 * on. The subsequent arguments may either be strings, in which case they are the
2089 * message names, or arrays, in which case the first element is the message name,
2090 * and subsequent elements are the parameters to that message.
2092 * The special named parameter 'options' in a message specification array is passed
2093 * through to the $options parameter of wfMsgExt().
2095 * Don't use this for messages that are not in users interface language.
2099 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2103 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2105 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2106 $msgSpecs = func_get_args();
2107 array_shift( $msgSpecs );
2108 $msgSpecs = array_values( $msgSpecs );
2110 foreach ( $msgSpecs as $n => $spec ) {
2112 if ( is_array( $spec ) ) {
2114 $name = array_shift( $args );
2115 if ( isset( $args['options'] ) ) {
2116 $options = $args['options'];
2117 unset( $args['options'] );
2123 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2125 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );