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()
31 var $mShowFeedLinks = false;
32 var $mFeedLinksAppendQuery = false;
33 var $mEnableClientCache = true;
34 var $mArticleBodyOnly = false;
36 var $mNewSectionLink = false;
37 var $mHideNewSectionLink = false;
38 var $mNoGallery = false;
39 var $mPageTitleActionText = '';
40 var $mParseWarnings = array();
41 var $mSquidMaxage = 0;
42 var $mRevisionId = null;
43 protected $mTitle = null;
46 * An array of stylesheet filenames (relative from skins path), with options
47 * for CSS media, IE conditions, and RTL/LTR direction.
48 * For internal use; add settings in the skin via $this->addStyle()
50 var $styles = array();
52 private $mIndexPolicy = 'index';
53 private $mFollowPolicy = 'follow';
57 * Initialise private variables
59 function __construct() {
60 global $wgAllowUserJs;
61 $this->mAllowUserJs
= $wgAllowUserJs;
64 public function redirect( $url, $responsecode = '302' ) {
65 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
66 $this->mRedirect
= str_replace( "\n", '', $url );
67 $this->mRedirectCode
= $responsecode;
70 public function getRedirect() {
71 return $this->mRedirect
;
75 * Set the HTTP status code to send with the output.
77 * @param int $statusCode
80 function setStatusCode( $statusCode ) { $this->mStatusCode
= $statusCode; }
83 * Add a new <meta> tag
84 * To add an http-equiv meta tag, precede the name with "http:"
86 * @param $name tag name
87 * @param $val tag value
89 function addMeta( $name, $val ) {
90 array_push( $this->mMetatags
, array( $name, $val ) );
93 function addKeyword( $text ) {
94 if( is_array( $text )) {
95 $this->mKeywords
= array_merge( $this->mKeywords
, $text );
97 array_push( $this->mKeywords
, $text );
100 function addScript( $script ) {
101 $this->mScripts
.= $script . "\n";
105 * Register and add a stylesheet from an extension directory.
106 * @param $url String path to sheet. Provide either a full url (beginning
107 * with 'http', etc) or a relative path from the document root
108 * (beginning with '/'). Otherwise it behaves identically to
109 * addStyle() and draws from the /skins folder.
111 public function addExtensionStyle( $url ) {
112 array_push( $this->mExtStyles
, $url );
116 * Add a JavaScript file out of skins/common, or a given relative path.
117 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
119 function addScriptFile( $file ) {
120 global $wgStylePath, $wgScript, $wgUser;
121 global $wgEnableScriptLoader, $wgScriptPath;
123 if( substr( $file, 0, 1 ) == '/' ) {
126 $path = "{$wgStylePath}/common/{$file}";
129 // If the class can be determined, use the addScriptClass method
130 $js_class = $this->getJsClassFromPath( $path );
132 $this->addScriptClass( $js_class );
136 //do checks for wiki-titles
137 if( strpos( $path, $wgScript ) !== false ) {
138 $reqPath = str_replace( $wgScript . '?', '', $path );
139 $reqArgs = explode( '&', $reqPath );
142 foreach( $reqArgs as $arg ) {
143 list( $key, $var ) = explode( '=', $arg );
144 $reqSet[$key] = $var;
147 if( isset( $reqSet['title'] ) && $reqSet != '' ) {
148 $jsTitleClass = 'WT:' . $reqSet['title'];
149 if( $wgEnableScriptLoader ) {
150 // Extract any extra parameters (for now just skin)
151 $ext_param = ( isset( $reqSet['useskin'] ) && $reqSet['useskin'] != '' )
152 ?
'|useskin=' . ucfirst( $reqSet['useskin'] ) : '';
153 $this->mScriptLoaderClassList
[] = $jsTitleClass . $ext_param ;
156 $this->addScript( Html
::linkedScript(
157 wfAppendQuery( $path, $this->getURIDparam( $jsTitleClass ) )
164 // If the script loader could not be used, just add the script to the header
165 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $this->getURIDparam() ) ) );
169 * Add the core scripts that are included on every page, for later output into the header
171 * this includes the conditional sitejs
173 function addCoreScripts2Top(){
174 global $wgEnableScriptLoader, $wgJSAutoloadLocalClasses, $wgScriptPath, $wgEnableJS2system;
175 global $wgUser, $wgJsMimeType;
176 // @todo We should deprecate wikibits in favor of some mv_embed pieces and jQuery
178 if( $wgEnableJS2system ){
179 $core_classes = array( 'window.jQuery', 'mv_embed', 'wikibits' );
181 $core_classes = array( 'wikibits' );
184 //make sure scripts are on top:
185 $postScripts = $this->mScripts
;
186 $this->mScripts
= '';
188 if( $wgEnableScriptLoader ){
189 //directly add script_loader call
190 //(separate from other scriptloader calls that may include extensions with conditional js)
191 $this->mScripts
= $this->getScriptLoaderJs( $core_classes );
194 foreach( $core_classes as $js_class ){
195 $this->addScriptClass( $js_class );
198 //now re-append any scripts that got added prior to the addCoreScripts2Top call
199 $this->mScripts
= $this->mScripts
. $postScripts;
203 * @param string $js_class Name of the JavaScript class
204 * @return boolean False if the class wasn't found, true on success
206 function addScriptClass( $js_class ){
207 global $wgDebugJavaScript, $wgJSAutoloadLocalClasses, $wgJSAutoloadClasses,
208 $wgEnableScriptLoader, $wgStyleVersion, $wgScriptPath, $wgEnableJS2system;
210 $path = jsScriptLoader
::getJsPathFromClass( $js_class );
211 if( $path !== false ){
212 if( $wgEnableScriptLoader ) {
213 // Register it with the script loader
214 if( !in_array( $js_class, $this->mScriptLoaderClassList
) ) {
215 $this->mScriptLoaderClassList
[] = $js_class;
218 // Source the script directly
219 $path = $wgScriptPath . '/' . $path;
220 $urlAppend = ( $wgDebugJavaScript ) ?
time() : $this->getURIDparam( $js_class );
221 $this->addScript( Html
::linkedScript( "$path?$urlAppend" ) );
223 //merge in language text (if js2 is on and we have loadGM function)
224 if( $wgEnableJS2system ){
225 $inlineMsg = jsScriptLoader
::getLocalizedMsgsFromClass( $js_class );
226 if( $inlineMsg != '' )
227 $this->addScript( Html
::inlineScript( $inlineMsg ));
232 print "could not find: $js_class\n";
233 wfDebug( __METHOD__
. ' could not find js_class: ' . $js_class );
234 return false; // could not find the class
238 * Get the <script> tag which will invoke the script loader
239 * @param $classAry A class array which, if given, overrides $this->mScriptLoaderClassList
241 function getScriptLoaderJs( $classAry = array() ) {
242 global $wgRequest, $wgDebugJavaScript;
243 // If no class array was provided, use mScriptLoaderClassList
244 if( !count( $classAry ) ) {
245 $classAry = $this->mScriptLoaderClassList
;
247 $class_list = implode( ',', $classAry );
249 $debug_param = ( $wgDebugJavaScript ||
250 $wgRequest->getVal( 'debug' ) == 'true' ||
251 $wgRequest->getVal( 'debug' ) == '1' )
252 ?
'&debug=true' : '';
254 return Html
::linkedScript( wfScript( 'mwScriptLoader' ) .
255 "?class={$class_list}{$debug_param}&" . $this->getURIDparam( $classAry) ) . "\n";
259 * Get the unique request ID parameter for the script-loader request
261 function getURIDparam( $classAry = array() ) {
262 global $wgDebugJavaScript, $wgStyleVersion, $IP, $wgScriptModifiedCheck;
263 if( $wgDebugJavaScript ) {
264 return 'urid=' . time();
266 //support single class_name attr
267 if( gettype( $classAry) == 'string' ){
268 $classAry = array( $classAry );
271 foreach( $classAry as $class ) {
272 if( $wgScriptModifiedCheck ) {
273 $js_path = jsScriptLoader
::getJsPathFromClass( $class );
275 $cur_ftime = filemtime ( $IP ."/". $js_path );
276 if( $cur_ftime > $ftime )
280 // Add the latest revision ID if the class set includes a WT (wiki title)
281 if( substr($class, 0, 3) == 'WT:'){
282 $title_str = substr($class, 3);
283 $t = Title
::newFromText( $title_str );
284 if( $t && $t->exists() ) {
285 if( $t->getLatestRevID() > $frev )
286 $frev = $t->getLatestRevID();
290 //build the actual unique request id:
291 $urid = "urid={$wgStyleVersion}";
293 // Add the file modification time if set
295 $urid .= "_" . $ftime;
297 //add the wiki rev id if set
306 * Given a script path, get the JS class name, or false if no such path is registered.
307 * @param $path string
309 function getJsClassFromPath( $path ) {
310 global $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses, $wgScriptPath;
312 $scriptLoaderPaths = array_merge( $wgJSAutoloadClasses, $wgJSAutoloadLocalClasses );
313 foreach( $scriptLoaderPaths as $js_class => $js_path ) {
314 $js_path = "{$wgScriptPath}/{$js_path}";
315 if( $path == $js_path )
322 * Add a self-contained script tag with the given contents
323 * @param string $script JavaScript text, no <script> tags
325 function addInlineScript( $script ) {
326 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
330 * Get all registered JS and CSS tags for the header.
332 function getScript() {
333 global $wgEnableScriptLoader;
334 if( $wgEnableScriptLoader ){
335 return $this->mScripts
. "\n" . $this->getScriptLoaderJs() . $this->getHeadItems();
337 return $this->mScripts
. $this->getHeadItems();
341 function getHeadItems() {
343 foreach ( $this->mHeadItems
as $item ) {
349 function addHeadItem( $name, $value ) {
350 $this->mHeadItems
[$name] = $value;
353 function hasHeadItem( $name ) {
354 return isset( $this->mHeadItems
[$name] );
357 function setETag($tag) { $this->mETag
= $tag; }
358 function setArticleBodyOnly($only) { $this->mArticleBodyOnly
= $only; }
359 function getArticleBodyOnly() { return $this->mArticleBodyOnly
; }
361 function addLink( $linkarr ) {
362 # $linkarr should be an associative array of attributes. We'll escape on output.
363 array_push( $this->mLinktags
, $linkarr );
366 # Get all links added by extensions
367 function getExtStyle() {
368 return $this->mExtStyles
;
371 function addMetadataLink( $linkarr ) {
372 # note: buggy CC software only reads first "meta" link
373 static $haveMeta = false;
374 $linkarr['rel'] = ($haveMeta) ?
'alternate meta' : 'meta';
375 $this->addLink( $linkarr );
380 * checkLastModified tells the client to use the client-cached page if
381 * possible. If sucessful, the OutputPage is disabled so that
382 * any future call to OutputPage->output() have no effect.
384 * Side effect: sets mLastModified for Last-Modified header
386 * @return bool True iff cache-ok headers was sent.
388 function checkLastModified( $timestamp ) {
389 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
391 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
392 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
395 if( !$wgCachePages ) {
396 wfDebug( __METHOD__
. ": CACHE DISABLED\n", false );
399 if( $wgUser->getOption( 'nocache' ) ) {
400 wfDebug( __METHOD__
. ": USER DISABLED CACHE\n", false );
404 $timestamp = wfTimestamp( TS_MW
, $timestamp );
405 $modifiedTimes = array(
406 'page' => $timestamp,
407 'user' => $wgUser->getTouched(),
408 'epoch' => $wgCacheEpoch
410 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
412 $maxModified = max( $modifiedTimes );
413 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
415 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
416 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", false );
422 foreach ( $modifiedTimes as $name => $value ) {
423 if ( $info !== '' ) {
426 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
429 # IE sends sizes after the date like this:
430 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
431 # this breaks strtotime().
432 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
434 wfSuppressWarnings(); // E_STRICT system time bitching
435 $clientHeaderTime = strtotime( $clientHeader );
437 if ( !$clientHeaderTime ) {
438 wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
441 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
443 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
444 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", false );
445 wfDebug( __METHOD__
. ": effective Last-Modified: " .
446 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", false );
447 if( $clientHeaderTime < $maxModified ) {
448 wfDebug( __METHOD__
. ": STALE, $info\n", false );
453 # Give a 304 response code and disable body output
454 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", false );
455 ini_set('zlib.output_compression', 0);
456 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
457 $this->sendCacheControl();
460 // Don't output a compressed blob when using ob_gzhandler;
461 // it's technically against HTTP spec and seems to confuse
462 // Firefox when the response gets split over two packets.
463 wfClearOutputBuffers();
468 function setPageTitleActionText( $text ) {
469 $this->mPageTitleActionText
= $text;
472 function getPageTitleActionText () {
473 if ( isset( $this->mPageTitleActionText
) ) {
474 return $this->mPageTitleActionText
;
479 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
481 * @param $policy string The literal string to output as the contents of
482 * the meta tag. Will be parsed according to the spec and output in
486 public function setRobotPolicy( $policy ) {
487 $policy = Article
::formatRobotPolicy( $policy );
489 if( isset( $policy['index'] ) ){
490 $this->setIndexPolicy( $policy['index'] );
492 if( isset( $policy['follow'] ) ){
493 $this->setFollowPolicy( $policy['follow'] );
498 * Set the index policy for the page, but leave the follow policy un-
501 * @param $policy string Either 'index' or 'noindex'.
504 public function setIndexPolicy( $policy ) {
505 $policy = trim( $policy );
506 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
507 $this->mIndexPolicy
= $policy;
512 * Set the follow policy for the page, but leave the index policy un-
515 * @param $policy string Either 'follow' or 'nofollow'.
518 public function setFollowPolicy( $policy ) {
519 $policy = trim( $policy );
520 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
521 $this->mFollowPolicy
= $policy;
526 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
528 public function setHTMLTitle( $name ) {
529 $this->mHTMLtitle
= $name;
533 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
534 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
535 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
536 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
538 public function setPageTitle( $name ) {
540 $name = $wgContLang->convert( $name, true );
541 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
542 # but leave "<i>foobar</i>" alone
543 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
544 $this->mPagetitle
= $nameWithTags;
546 $taction = $this->getPageTitleActionText();
547 if( !empty( $taction ) ) {
548 $name .= ' - '.$taction;
551 # change "<i>foo&bar</i>" to "foo&bar"
552 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer
::stripAllTags( $nameWithTags ) ) );
555 public function setTitle( $t ) {
559 public function getTitle() {
560 if ( $this->mTitle
instanceof Title
) {
561 return $this->mTitle
;
564 wfDebug( __METHOD__
. ' called and $mTitle is null. Return $wgTitle for sanity' );
570 public function getHTMLTitle() { return $this->mHTMLtitle
; }
571 public function getPageTitle() { return $this->mPagetitle
; }
572 public function setSubtitle( $str ) { $this->mSubtitle
= /*$this->parse(*/$str/*)*/; } // @bug 2514
573 public function appendSubtitle( $str ) { $this->mSubtitle
.= /*$this->parse(*/$str/*)*/; } // @bug 2514
574 public function getSubtitle() { return $this->mSubtitle
; }
575 public function isArticle() { return $this->mIsarticle
; }
576 public function setPrintable() { $this->mPrintable
= true; }
577 public function isPrintable() { return $this->mPrintable
; }
578 public function setSyndicated( $show = true ) { $this->mShowFeedLinks
= $show; }
579 public function isSyndicated() { return $this->mShowFeedLinks
; }
580 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery
= $val; }
581 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery
; }
582 public function setOnloadHandler( $js ) { $this->mOnloadHandler
= $js; }
583 public function getOnloadHandler() { return $this->mOnloadHandler
; }
584 public function disable() { $this->mDoNothing
= true; }
585 public function isDisabled() { return $this->mDoNothing
; }
587 public function setArticleRelated( $v ) {
588 $this->mIsArticleRelated
= $v;
590 $this->mIsarticle
= false;
593 public function setArticleFlag( $v ) {
594 $this->mIsarticle
= $v;
596 $this->mIsArticleRelated
= $v;
600 public function isArticleRelated() { return $this->mIsArticleRelated
; }
602 public function getLanguageLinks() { return $this->mLanguageLinks
; }
603 public function addLanguageLinks($newLinkArray) {
604 $this->mLanguageLinks +
= $newLinkArray;
606 public function setLanguageLinks($newLinkArray) {
607 $this->mLanguageLinks
= $newLinkArray;
610 public function getCategoryLinks() {
611 return $this->mCategoryLinks
;
615 * Add an array of categories, with names in the keys
617 public function addCategoryLinks( $categories ) {
618 global $wgUser, $wgContLang;
620 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
624 # Add the links to a LinkBatch
625 $arr = array( NS_CATEGORY
=> $categories );
627 $lb->setArray( $arr );
629 # Fetch existence plus the hiddencat property
630 $dbr = wfGetDB( DB_SLAVE
);
631 $pageTable = $dbr->tableName( 'page' );
632 $where = $lb->constructSet( 'page', $dbr );
633 $propsTable = $dbr->tableName( 'page_props' );
634 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
635 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
636 $res = $dbr->query( $sql, __METHOD__
);
638 # Add the results to the link cache
639 $lb->addResultToCache( LinkCache
::singleton(), $res );
641 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
642 $categories = array_combine( array_keys( $categories ),
643 array_fill( 0, count( $categories ), 'normal' ) );
645 # Mark hidden categories
646 foreach ( $res as $row ) {
647 if ( isset( $row->pp_value
) ) {
648 $categories[$row->page_title
] = 'hidden';
652 # Add the remaining categories to the skin
653 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks
) ) ) {
654 $sk = $wgUser->getSkin();
655 foreach ( $categories as $category => $type ) {
656 $origcategory = $category;
657 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
658 $wgContLang->findVariantLink( $category, $title, true );
659 if ( $category != $origcategory )
660 if ( array_key_exists( $category, $categories ) )
662 $text = $wgContLang->convertHtml( $title->getText() );
663 $this->mCategoryLinks
[$type][] = $sk->link( $title, $text );
668 public function setCategoryLinks($categories) {
669 $this->mCategoryLinks
= array();
670 $this->addCategoryLinks($categories);
673 public function suppressQuickbar() { $this->mSuppressQuickbar
= true; }
674 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar
; }
676 public function disallowUserJs() { $this->mAllowUserJs
= false; }
677 public function isUserJsAllowed() { return $this->mAllowUserJs
; }
679 public function prependHTML( $text ) { $this->mBodytext
= $text . $this->mBodytext
; }
680 public function addHTML( $text ) { $this->mBodytext
.= $text; }
681 public function clearHTML() { $this->mBodytext
= ''; }
682 public function getHTML() { return $this->mBodytext
; }
683 public function debug( $text ) { $this->mDebugtext
.= $text; }
686 public function setParserOptions( $options ) {
687 wfDeprecated( __METHOD__
);
688 return $this->parserOptions( $options );
691 public function parserOptions( $options = null ) {
692 if ( !$this->mParserOptions
) {
693 $this->mParserOptions
= new ParserOptions
;
695 return wfSetVar( $this->mParserOptions
, $options );
699 * Set the revision ID which will be seen by the wiki text parser
700 * for things such as embedded {{REVISIONID}} variable use.
701 * @param mixed $revid an integer, or NULL
702 * @return mixed previous value
704 public function setRevisionId( $revid ) {
705 $val = is_null( $revid ) ?
null : intval( $revid );
706 return wfSetVar( $this->mRevisionId
, $val );
709 public function getRevisionId() {
710 return $this->mRevisionId
;
714 * Convert wikitext to HTML and add it to the buffer
715 * Default assumes that the current page title will
718 * @param string $text
719 * @param bool $linestart
721 public function addWikiText( $text, $linestart = true ) {
722 $title = $this->getTitle(); // Work arround E_STRICT
723 $this->addWikiTextTitle( $text, $title, $linestart );
726 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
727 $this->addWikiTextTitle($text, $title, $linestart);
730 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
731 $this->addWikiTextTitle( $text, $title, $linestart, true );
734 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
737 wfProfileIn( __METHOD__
);
739 wfIncrStats( 'pcache_not_possible' );
741 $popts = $this->parserOptions();
742 $oldTidy = $popts->setTidy( $tidy );
744 $parserOutput = $wgParser->parse( $text, $title, $popts,
745 $linestart, true, $this->mRevisionId
);
747 $popts->setTidy( $oldTidy );
749 $this->addParserOutput( $parserOutput );
751 wfProfileOut( __METHOD__
);
756 * @param ParserOutput object &$parserOutput
758 public function addParserOutputNoText( &$parserOutput ) {
759 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
761 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
762 $this->addCategoryLinks( $parserOutput->getCategories() );
763 $this->mNewSectionLink
= $parserOutput->getNewSection();
764 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
766 $this->mParseWarnings
= $parserOutput->getWarnings();
767 if ( $parserOutput->getCacheTime() == -1 ) {
768 $this->enableClientCache( false );
770 $this->mNoGallery
= $parserOutput->getNoGallery();
771 $this->mHeadItems
= array_merge( $this->mHeadItems
, (array)$parserOutput->mHeadItems
);
773 foreach ( (array)$parserOutput->mTemplateIds
as $ns => $dbks ) {
774 if ( isset( $this->mTemplateIds
[$ns] ) ) {
775 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
777 $this->mTemplateIds
[$ns] = $dbks;
781 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
782 $this->setPageTitle( $dt );
783 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
784 $this->setPageTitle( $title );
786 // Hooks registered in the object
787 global $wgParserOutputHooks;
788 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
789 list( $hookName, $data ) = $hookInfo;
790 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
791 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
795 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
800 * @param ParserOutput &$parserOutput
802 function addParserOutput( &$parserOutput ) {
803 $this->addParserOutputNoText( $parserOutput );
804 $text = $parserOutput->getText();
805 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
806 $this->addHTML( $text );
810 * Add wikitext to the buffer, assuming that this is the primary text for a page view
811 * Saves the text into the parser cache if possible.
813 * @param string $text
814 * @param Article $article
816 * @deprecated Use Article::outputWikitext
818 public function addPrimaryWikiText( $text, $article, $cache = true ) {
821 wfDeprecated( __METHOD__
);
823 $popts = $this->parserOptions();
824 $popts->setTidy(true);
825 $parserOutput = $wgParser->parse( $text, $article->mTitle
,
826 $popts, true, true, $this->mRevisionId
);
827 $popts->setTidy(false);
828 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
829 $parserCache = ParserCache
::singleton();
830 $parserCache->save( $parserOutput, $article, $popts);
833 $this->addParserOutput( $parserOutput );
837 * @deprecated use addWikiTextTidy()
839 public function addSecondaryWikiText( $text, $linestart = true ) {
840 wfDeprecated( __METHOD__
);
841 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
845 * Add wikitext with tidy enabled
847 public function addWikiTextTidy( $text, $linestart = true ) {
848 $title = $this->getTitle();
849 $this->addWikiTextTitleTidy($text, $title, $linestart);
854 * Add the output of a QuickTemplate to the output buffer
856 * @param QuickTemplate $template
858 public function addTemplate( &$template ) {
860 $template->execute();
861 $this->addHTML( ob_get_contents() );
866 * Parse wikitext and return the HTML.
868 * @param string $text
869 * @param bool $linestart Is this the start of a line?
870 * @param bool $interface ??
872 public function parse( $text, $linestart = true, $interface = false ) {
874 if( is_null( $this->getTitle() ) ) {
875 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
877 $popts = $this->parserOptions();
878 if ( $interface) { $popts->setInterfaceMessage(true); }
879 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
880 $linestart, true, $this->mRevisionId
);
881 if ( $interface) { $popts->setInterfaceMessage(false); }
882 return $parserOutput->getText();
885 /** Parse wikitext, strip paragraphs, and return the HTML. */
886 public function parseInline( $text, $linestart = true, $interface = false ) {
887 $parsed = $this->parse( $text, $linestart, $interface );
890 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
898 * @param Article $article
903 * @return bool True if successful, else false.
905 public function tryParserCache( &$article ) {
906 wfDeprecated( __METHOD__
);
907 $parserOutput = ParserCache
::singleton()->get( $article, $article->getParserOptions() );
909 if ($parserOutput !== false) {
910 $this->addParserOutput( $parserOutput );
918 * @param int $maxage Maximum cache time on the Squid, in seconds.
920 public function setSquidMaxage( $maxage ) {
921 $this->mSquidMaxage
= $maxage;
925 * Use enableClientCache(false) to force it to send nocache headers
928 public function enableClientCache( $state ) {
929 return wfSetVar( $this->mEnableClientCache
, $state );
932 function getCacheVaryCookies() {
933 global $wgCookiePrefix, $wgCacheVaryCookies;
935 if ( $cookies === null ) {
936 $cookies = array_merge(
938 "{$wgCookiePrefix}Token",
939 "{$wgCookiePrefix}LoggedOut",
944 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
949 function uncacheableBecauseRequestVars() {
951 return $wgRequest->getText('useskin', false) === false
952 && $wgRequest->getText('uselang', false) === false;
956 * Check if the request has a cache-varying cookie header
957 * If it does, it's very important that we don't allow public caching
959 function haveCacheVaryCookies() {
961 $cookieHeader = $wgRequest->getHeader( 'cookie' );
962 if ( $cookieHeader === false ) {
965 $cvCookies = $this->getCacheVaryCookies();
966 foreach ( $cvCookies as $cookieName ) {
967 # Check for a simple string match, like the way squid does it
968 if ( strpos( $cookieHeader, $cookieName ) ) {
969 wfDebug( __METHOD__
.": found $cookieName\n" );
973 wfDebug( __METHOD__
.": no cache-varying cookies found\n" );
977 /** Get a complete X-Vary-Options header */
978 public function getXVO() {
979 $cvCookies = $this->getCacheVaryCookies();
980 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
982 foreach ( $cvCookies as $cookieName ) {
988 $xvo .= 'string-contains=' . $cookieName;
993 public function sendCacheControl() {
994 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
996 $response = $wgRequest->response();
997 if ($wgUseETag && $this->mETag
)
998 $response->header("ETag: $this->mETag");
1000 # don't serve compressed data to clients who can't handle it
1001 # maintain different caches for logged-in users and non-logged in ones
1002 $response->header( 'Vary: Accept-Encoding, Cookie' );
1005 # Add an X-Vary-Options header for Squid with Wikimedia patches
1006 $response->header( $this->getXVO() );
1009 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache
) {
1010 if( $wgUseSquid && session_id() == '' &&
1011 ! $this->isPrintable() && $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies() )
1014 # We'll purge the proxy cache explicitly, but require end user agents
1015 # to revalidate against the proxy on each visit.
1016 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1017 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1018 # start with a shorter timeout for initial testing
1019 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1020 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage
.', content="ESI/1.0"');
1021 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1023 # We'll purge the proxy cache for anons explicitly, but require end user agents
1024 # to revalidate against the proxy on each visit.
1025 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1026 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1027 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", false );
1028 # start with a shorter timeout for initial testing
1029 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1030 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage
.', must-revalidate, max-age=0' );
1033 # We do want clients to cache if they can, but they *must* check for updates
1034 # on revisiting the page.
1035 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", false );
1036 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1037 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1039 if($this->mLastModified
) {
1040 $response->header( "Last-Modified: {$this->mLastModified}" );
1043 wfDebug( __METHOD__
. ": no caching **\n", false );
1045 # In general, the absence of a last modified header should be enough to prevent
1046 # the client from using its cache. We send a few other things just to make sure.
1047 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1048 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1049 $response->header( 'Pragma: no-cache' );
1054 * Finally, all the text has been munged and accumulated into
1055 * the object, let's actually output it:
1057 public function output() {
1058 global $wgUser, $wgOutputEncoding, $wgRequest;
1059 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
1060 global $wgUseAjax, $wgAjaxWatch;
1061 global $wgEnableMWSuggest, $wgUniversalEditButton;
1064 if( $this->mDoNothing
){
1067 wfProfileIn( __METHOD__
);
1068 if ( '' != $this->mRedirect
) {
1069 # Standards require redirect URLs to be absolute
1070 $this->mRedirect
= wfExpandUrl( $this->mRedirect
);
1071 if( $this->mRedirectCode
== '301') {
1072 if( !$wgDebugRedirects ) {
1073 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
1075 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
1077 $this->sendCacheControl();
1079 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
1080 if( $wgDebugRedirects ) {
1081 $url = htmlspecialchars( $this->mRedirect
);
1082 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1083 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1084 print "</body>\n</html>\n";
1086 $wgRequest->response()->header( 'Location: '.$this->mRedirect
);
1088 wfProfileOut( __METHOD__
);
1091 elseif ( $this->mStatusCode
)
1093 $statusMessage = array(
1095 101 => 'Switching Protocols',
1096 102 => 'Processing',
1100 203 => 'Non-Authoritative Information',
1101 204 => 'No Content',
1102 205 => 'Reset Content',
1103 206 => 'Partial Content',
1104 207 => 'Multi-Status',
1105 300 => 'Multiple Choices',
1106 301 => 'Moved Permanently',
1109 304 => 'Not Modified',
1111 307 => 'Temporary Redirect',
1112 400 => 'Bad Request',
1113 401 => 'Unauthorized',
1114 402 => 'Payment Required',
1117 405 => 'Method Not Allowed',
1118 406 => 'Not Acceptable',
1119 407 => 'Proxy Authentication Required',
1120 408 => 'Request Timeout',
1123 411 => 'Length Required',
1124 412 => 'Precondition Failed',
1125 413 => 'Request Entity Too Large',
1126 414 => 'Request-URI Too Large',
1127 415 => 'Unsupported Media Type',
1128 416 => 'Request Range Not Satisfiable',
1129 417 => 'Expectation Failed',
1130 422 => 'Unprocessable Entity',
1132 424 => 'Failed Dependency',
1133 500 => 'Internal Server Error',
1134 501 => 'Not Implemented',
1135 502 => 'Bad Gateway',
1136 503 => 'Service Unavailable',
1137 504 => 'Gateway Timeout',
1138 505 => 'HTTP Version Not Supported',
1139 507 => 'Insufficient Storage'
1142 if ( $statusMessage[$this->mStatusCode
] )
1143 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $statusMessage[$this->mStatusCode
] );
1146 $sk = $wgUser->getSkin();
1148 // Add our core scripts to output
1149 $this->addCoreScripts2Top();
1152 $this->addScriptFile( 'ajax.js' );
1154 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1156 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1157 $this->addScriptFile( 'ajaxwatch.js' );
1160 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
1161 $this->addScriptFile( 'mwsuggest.js' );
1165 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1166 $this->addScriptFile( 'rightclickedit.js' );
1169 global $wgUseAJAXCategories, $wgEnableJS2system;
1170 if ($wgUseAJAXCategories && $wgEnableJS2system) {
1171 global $wgAJAXCategoriesNamespaces;
1173 $title = $this->getTitle();
1175 if( empty( $wgAJAXCategoriesNamespaces ) ||
in_array( $title->getNamespace(), $wgAJAXCategoriesNamespaces ) ) {
1176 $this->addScriptClass( 'ajaxCategories' );
1180 if( $wgUniversalEditButton ) {
1181 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1182 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create' ) ) ) {
1183 // Original UniversalEditButton
1184 $msg = wfMsg('edit');
1185 $this->addLink( array(
1186 'rel' => 'alternate',
1187 'type' => 'application/x-wiki',
1189 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1191 // Alternate edit link
1192 $this->addLink( array(
1195 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1200 # Buffer output; final headers may depend on later processing
1203 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1204 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1206 if ($this->mArticleBodyOnly
) {
1207 $this->out($this->mBodytext
);
1209 // Hook that allows last minute changes to the output page, e.g.
1210 // adding of CSS or Javascript by extensions.
1211 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1213 wfProfileIn( 'Output-skin' );
1214 $sk->outputPage( $this );
1215 wfProfileOut( 'Output-skin' );
1218 $this->sendCacheControl();
1220 wfProfileOut( __METHOD__
);
1224 * Actually output something with print(). Performs an iconv to the
1225 * output encoding, if needed.
1226 * @param string $ins The string to output
1228 public function out( $ins ) {
1229 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1230 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1233 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1234 if ( false === $outs ) { $outs = $ins; }
1242 public static function setEncodings() {
1243 global $wgInputEncoding, $wgOutputEncoding;
1246 $wgInputEncoding = strtolower( $wgInputEncoding );
1248 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1249 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1252 $wgOutputEncoding = $wgInputEncoding;
1256 * Deprecated, use wfReportTime() instead.
1260 public function reportTime() {
1261 wfDeprecated( __METHOD__
);
1262 $time = wfReportTime();
1267 * Produce a "user is blocked" page.
1269 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1272 function blockedPage( $return = true ) {
1273 global $wgUser, $wgContLang, $wgLang;
1275 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1276 $this->setRobotPolicy( 'noindex,nofollow' );
1277 $this->setArticleRelated( false );
1279 $name = User
::whoIs( $wgUser->blockedBy() );
1280 $reason = $wgUser->blockedFor();
1281 if( $reason == '' ) {
1282 $reason = wfMsg( 'blockednoreason' );
1284 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $wgUser->mBlock
->mTimestamp
), true );
1287 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1289 $blockid = $wgUser->mBlock
->mId
;
1291 $blockExpiry = $wgUser->mBlock
->mExpiry
;
1292 if ( $blockExpiry == 'infinity' ) {
1293 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1294 // Search for localization in 'ipboptions'
1295 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1296 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1297 if ( strpos( $option, ":" ) === false )
1299 list( $show, $value ) = explode( ":", $option );
1300 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1301 $blockExpiry = $show;
1306 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1309 if ( $wgUser->mBlock
->mAuto
) {
1310 $msg = 'autoblockedtext';
1312 $msg = 'blockedtext';
1315 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1316 * This could be a username, an ip range, or a single ip. */
1317 $intended = $wgUser->mBlock
->mAddress
;
1319 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1321 # Don't auto-return to special pages
1323 $return = $this->getTitle()->getNamespace() > -1 ?
$this->getTitle() : null;
1324 $this->returnToMain( null, $return );
1329 * Output a standard error page
1331 * @param string $title Message key for page title
1332 * @param string $msg Message key for page text
1333 * @param array $params Message parameters
1335 public function showErrorPage( $title, $msg, $params = array() ) {
1336 if ( $this->getTitle() ) {
1337 $this->mDebugtext
.= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1339 $this->setPageTitle( wfMsg( $title ) );
1340 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1341 $this->setRobotPolicy( 'noindex,nofollow' );
1342 $this->setArticleRelated( false );
1343 $this->enableClientCache( false );
1344 $this->mRedirect
= '';
1345 $this->mBodytext
= '';
1347 array_unshift( $params, 'parse' );
1348 array_unshift( $params, $msg );
1349 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1351 $this->returnToMain();
1355 * Output a standard permission error page
1357 * @param array $errors Error message keys
1359 public function showPermissionsErrorPage( $errors, $action = null )
1361 $this->mDebugtext
.= 'Original title: ' .
1362 $this->getTitle()->getPrefixedText() . "\n";
1363 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1364 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1365 $this->setRobotPolicy( 'noindex,nofollow' );
1366 $this->setArticleRelated( false );
1367 $this->enableClientCache( false );
1368 $this->mRedirect
= '';
1369 $this->mBodytext
= '';
1370 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1374 public function errorpage( $title, $msg ) {
1375 wfDeprecated( __METHOD__
);
1376 throw new ErrorPageError( $title, $msg );
1380 * Display an error page indicating that a given version of MediaWiki is
1381 * required to use it
1383 * @param mixed $version The version of MediaWiki needed to use the page
1385 public function versionRequired( $version ) {
1386 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1387 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1388 $this->setRobotPolicy( 'noindex,nofollow' );
1389 $this->setArticleRelated( false );
1390 $this->mBodytext
= '';
1392 $this->addWikiMsg( 'versionrequiredtext', $version );
1393 $this->returnToMain();
1397 * Display an error page noting that a given permission bit is required.
1399 * @param string $permission key required
1401 public function permissionRequired( $permission ) {
1404 $this->setPageTitle( wfMsg( 'badaccess' ) );
1405 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1406 $this->setRobotPolicy( 'noindex,nofollow' );
1407 $this->setArticleRelated( false );
1408 $this->mBodytext
= '';
1410 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1411 User
::getGroupsWithPermission( $permission ) );
1413 $this->addWikiMsg( 'badaccess-groups',
1414 $wgLang->commaList( $groups ),
1417 $this->addWikiMsg( 'badaccess-group0' );
1419 $this->returnToMain();
1423 * Use permissionRequired.
1426 public function sysopRequired() {
1427 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1431 * Use permissionRequired.
1434 public function developerRequired() {
1435 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1439 * Produce the stock "please login to use the wiki" page
1441 public function loginToUse() {
1442 global $wgUser, $wgContLang;
1444 if( $wgUser->isLoggedIn() ) {
1445 $this->permissionRequired( 'read' );
1449 $skin = $wgUser->getSkin();
1451 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1452 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1453 $this->setRobotPolicy( 'noindex,nofollow' );
1454 $this->setArticleFlag( false );
1456 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1457 $loginLink = $skin->link(
1459 wfMsgHtml( 'loginreqlink' ),
1461 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
1462 array( 'known', 'noclasses' )
1464 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1465 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1467 # Don't return to the main page if the user can't read it
1468 # otherwise we'll end up in a pointless loop
1469 $mainPage = Title
::newMainPage();
1470 if( $mainPage->userCanRead() )
1471 $this->returnToMain( null, $mainPage );
1475 public function databaseError( $fname, $sql, $error, $errno ) {
1476 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1480 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1481 * @return string The wikitext error-messages, formatted into a list.
1483 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1484 if ($action == null) {
1485 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1488 $action_desc = wfMsgNoTrans( "action-$action" );
1489 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1492 if (count( $errors ) > 1) {
1493 $text .= '<ul class="permissions-errors">' . "\n";
1495 foreach( $errors as $error )
1498 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1503 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1510 * Display a page stating that the Wiki is in read-only mode,
1511 * and optionally show the source of the page that the user
1512 * was trying to edit. Should only be called (for this
1513 * purpose) after wfReadOnly() has returned true.
1515 * For historical reasons, this function is _also_ used to
1516 * show the error message when a user tries to edit a page
1517 * they are not allowed to edit. (Unless it's because they're
1518 * blocked, then we show blockedPage() instead.) In this
1519 * case, the second parameter should be set to true and a list
1520 * of reasons supplied as the third parameter.
1522 * @todo Needs to be split into multiple functions.
1524 * @param string $source Source code to show (or null).
1525 * @param bool $protected Is this a permissions error?
1526 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1528 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1530 $skin = $wgUser->getSkin();
1532 $this->setRobotPolicy( 'noindex,nofollow' );
1533 $this->setArticleRelated( false );
1535 // If no reason is given, just supply a default "I can't let you do
1536 // that, Dave" message. Should only occur if called by legacy code.
1537 if ( $protected && empty($reasons) ) {
1538 $reasons[] = array( 'badaccess-group0' );
1541 if ( !empty($reasons) ) {
1542 // Permissions error
1544 $this->setPageTitle( wfMsg( 'viewsource' ) );
1553 array( 'known', 'noclasses' )
1558 $this->setPageTitle( wfMsg( 'badaccess' ) );
1560 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1562 // Wiki is read only
1563 $this->setPageTitle( wfMsg( 'readonly' ) );
1564 $reason = wfReadOnlyReason();
1565 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1568 // Show source, if supplied
1569 if( is_string( $source ) ) {
1570 $this->addWikiMsg( 'viewsourcetext' );
1573 'id' => 'wpTextbox1',
1574 'name' => 'wpTextbox1',
1575 'cols' => $wgUser->getOption( 'cols' ),
1576 'rows' => $wgUser->getOption( 'rows' ),
1577 'readonly' => 'readonly'
1579 $this->addHTML( Html
::element( 'textarea', $params, $source ) );
1581 // Show templates used by this article
1582 $skin = $wgUser->getSkin();
1583 $article = new Article( $this->getTitle() );
1584 $this->addHTML( "<div class='templatesUsed'>
1585 {$skin->formatTemplates( $article->getUsedTemplates() )}
1590 # If the title doesn't exist, it's fairly pointless to print a return
1591 # link to it. After all, you just tried editing it and couldn't, so
1592 # what's there to do there?
1593 if( $this->getTitle()->exists() ) {
1594 $this->returnToMain( null, $this->getTitle() );
1599 public function fatalError( $message ) {
1600 wfDeprecated( __METHOD__
);
1601 throw new FatalError( $message );
1605 public function unexpectedValueError( $name, $val ) {
1606 wfDeprecated( __METHOD__
);
1607 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1611 public function fileCopyError( $old, $new ) {
1612 wfDeprecated( __METHOD__
);
1613 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1617 public function fileRenameError( $old, $new ) {
1618 wfDeprecated( __METHOD__
);
1619 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1623 public function fileDeleteError( $name ) {
1624 wfDeprecated( __METHOD__
);
1625 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1629 public function fileNotFoundError( $name ) {
1630 wfDeprecated( __METHOD__
);
1631 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1634 public function showFatalError( $message ) {
1635 $this->setPageTitle( wfMsg( "internalerror" ) );
1636 $this->setRobotPolicy( "noindex,nofollow" );
1637 $this->setArticleRelated( false );
1638 $this->enableClientCache( false );
1639 $this->mRedirect
= '';
1640 $this->mBodytext
= $message;
1643 public function showUnexpectedValueError( $name, $val ) {
1644 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1647 public function showFileCopyError( $old, $new ) {
1648 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1651 public function showFileRenameError( $old, $new ) {
1652 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1655 public function showFileDeleteError( $name ) {
1656 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1659 public function showFileNotFoundError( $name ) {
1660 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1664 * Add a "return to" link pointing to a specified title
1666 * @param Title $title Title to link
1667 * @param string $query Query string
1669 public function addReturnTo( $title, $query = array() ) {
1671 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1672 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link(
1673 $title, null, array(), $query ) );
1674 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
1678 * Add a "return to" link pointing to a specified title,
1679 * or the title indicated in the request, or else the main page
1681 * @param null $unused No longer used
1682 * @param Title $returnto Title to return to
1684 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
1687 if ( $returnto == null ) {
1688 $returnto = $wgRequest->getText( 'returnto' );
1691 if ( $returntoquery == null ) {
1692 $returntoquery = $wgRequest->getText( 'returntoquery' );
1695 if ( '' === $returnto ) {
1696 $returnto = Title
::newMainPage();
1699 if ( is_object( $returnto ) ) {
1700 $titleObj = $returnto;
1702 $titleObj = Title
::newFromText( $returnto );
1704 if ( !is_object( $titleObj ) ) {
1705 $titleObj = Title
::newMainPage();
1708 $this->addReturnTo( $titleObj, $returntoquery );
1712 * @return string The doctype, opening <html>, and head element.
1714 * @param $sk Skin The given Skin
1716 public function headElement( Skin
$sk, $includeStyle = true ) {
1717 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1718 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1719 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion, $wgEnableScriptLoader, $wgHtml5;
1721 $this->addMeta( "http:Content-Type", "$wgMimeType; charset={$wgOutputEncoding}" );
1722 if ( $sk->commonPrintStylesheet() ) {
1723 $this->addStyle( 'common/wikiprintable.css', 'print' );
1725 $sk->setupUserCss( $this );
1729 if( $wgMimeType == 'text/xml' ||
$wgMimeType == 'application/xhtml+xml' ||
$wgMimeType == 'application/xml' ) {
1730 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1733 if ( '' == $this->getHTMLTitle() ) {
1734 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1737 $dir = $wgContLang->getDir();
1740 $ret .= "<!doctype html>\n";
1741 $ret .= "<html lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1743 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
1744 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1745 foreach($wgXhtmlNamespaces as $tag => $ns) {
1746 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1748 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" dir=\"$dir\">\n";
1752 $ret .= "<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n";
1753 $ret .= implode( "\n", array(
1754 $this->getHeadLinks(),
1755 $this->buildCssLinks(),
1756 $this->getHeadScripts( $sk ),
1757 $this->getHeadItems(),
1760 $ret .= Html
::inlineStyle( $sk->usercss
);
1763 if( $wgEnableScriptLoader )
1764 $ret .= $this->getScriptLoaderJs();
1766 if ($wgUseTrackbacks && $this->isArticleRelated())
1767 $ret .= $this->getTitle()->trackbackRDF();
1769 $ret .= "</head>\n";
1774 * gets the global variables and mScripts
1776 * also adds userjs to the end if enabled:
1778 function getHeadScripts( Skin
$sk ) {
1779 global $wgUser, $wgRequest, $wgJsMimeType, $wgUseSiteJs;
1781 $vars = Skin
::makeGlobalVariablesScript( $sk->getSkinName() );
1783 //add site JS if enabled:
1784 if( $wgUseSiteJs ) {
1785 $sk = $wgUser->getSkin();
1786 $jsCache = $wgUser->isLoggedIn() ?
'&smaxage=0' : '';
1787 $this->addScriptFile( Skin
::makeUrl( '-',
1788 "action=raw$jsCache&gen=js&useskin=" .
1789 urlencode( $sk->getSkinName() )
1794 //add user js if enabled:
1795 if( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
1796 $action = $wgRequest->getVal( 'action', 'view' );
1797 if( $this->mTitle
->isJsSubpage() and $sk->userCanPreview( $action ) ) {
1798 # XXX: additional security check/prompt?
1799 $this->addInlineScript( $wgRequest->getText( 'wpTextbox1' ) );
1801 $userpage = $wgUser->getUserPage();
1802 $userjs = Skin
::makeUrl(
1803 $userpage->getPrefixedText() . '/' . $sk->getSkinName() . '.js',
1804 'action=raw&ctype=' . $wgJsMimeType );
1805 $this->addScriptFile( $userjs );
1809 return $vars . "\n" . $this->mScripts
;
1812 protected function addDefaultMeta() {
1813 global $wgVersion, $wgHtml5;
1815 static $called = false;
1817 # Don't run this twice
1823 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1825 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1827 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1828 if( $p !== 'index,follow' ) {
1829 // http://www.robotstxt.org/wc/meta-user.html
1830 // Only show if it's different from the default robots policy
1831 $this->addMeta( 'robots', $p );
1834 if ( count( $this->mKeywords
) > 0 ) {
1836 "/<.*?" . ">/" => '',
1839 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords
) ) );
1844 * @return string HTML tag links to be put in the header.
1846 public function getHeadLinks() {
1847 global $wgRequest, $wgFeed;
1849 // Ideally this should happen earlier, somewhere. :P
1850 $this->addDefaultMeta();
1854 foreach ( $this->mMetatags
as $tag ) {
1855 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1857 $tag[0] = substr( $tag[0], 5 );
1861 $tags[] = Html
::element( 'meta',
1864 'content' => $tag[1] ) );
1866 foreach ( $this->mLinktags
as $tag ) {
1867 $tags[] = Html
::element( 'link', $tag );
1871 foreach( $this->getSyndicationLinks() as $format => $link ) {
1872 # Use the page name for the title (accessed through $wgTitle since
1873 # there's no other way). In principle, this could lead to issues
1874 # with having the same name for different feeds corresponding to
1875 # the same page, but we can't avoid that at this low a level.
1877 $tags[] = $this->feedLink(
1880 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1883 # Recent changes feed should appear on every page (except recentchanges,
1884 # that would be redundant). Put it after the per-page feed to avoid
1885 # changing existing behavior. It's still available, probably via a
1886 # menu in your browser. Some sites might have a different feed they'd
1887 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1888 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1889 # If so, use it instead.
1891 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1892 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1894 if ( $wgOverrideSiteFeed ) {
1895 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1896 $tags[] = $this->feedLink (
1898 htmlspecialchars( $feedUrl ),
1899 wfMsg( "site-{$type}-feed", $wgSitename ) );
1902 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1903 foreach( $wgFeedClasses as $format => $class ) {
1904 $tags[] = $this->feedLink(
1906 $rctitle->getLocalURL( "feed={$format}" ),
1907 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1912 return implode( "\n", $tags );
1916 * Return URLs for each supported syndication format for this page.
1917 * @return array associating format keys with URLs
1919 public function getSyndicationLinks() {
1920 global $wgFeedClasses;
1923 if( $this->isSyndicated() ) {
1924 if( is_string( $this->getFeedAppendQuery() ) ) {
1925 $appendQuery = "&" . $this->getFeedAppendQuery();
1930 foreach( $wgFeedClasses as $format => $class ) {
1931 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1938 * Generate a <link rel/> for an RSS feed.
1940 private function feedLink( $type, $url, $text ) {
1941 return Html
::element( 'link', array(
1942 'rel' => 'alternate',
1943 'type' => "application/$type+xml",
1949 * Add a local or specified stylesheet, with the given media options.
1950 * Meant primarily for internal use...
1952 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1953 * @param $conditional -- for IE conditional comments, specifying an IE version
1954 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1956 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1958 // Even though we expect the media type to be lowercase, but here we
1959 // force it to lowercase to be safe.
1961 $options['media'] = $media;
1963 $options['condition'] = $condition;
1965 $options['dir'] = $dir;
1966 $this->styles
[$style] = $options;
1970 * Adds inline CSS styles
1971 * @param $style_css Mixed: inline CSS
1973 public function addInlineStyle( $style_css ){
1974 $this->mScripts
.= Html
::inlineStyle( $style_css );
1978 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1979 * These will be applied to various media & IE conditionals.
1981 public function buildCssLinks() {
1983 foreach( $this->styles
as $file => $options ) {
1984 $link = $this->styleLink( $file, $options );
1989 return implode( "\n", $links );
1992 protected function styleLink( $style, $options ) {
1995 if( isset( $options['dir'] ) ) {
1997 $siteDir = $wgContLang->getDir();
1998 if( $siteDir != $options['dir'] )
2002 if( isset( $options['media'] ) ) {
2003 $media = $this->transformCssMedia( $options['media'] );
2004 if( is_null( $media ) ) {
2011 if( substr( $style, 0, 1 ) == '/' ||
2012 substr( $style, 0, 5 ) == 'http:' ||
2013 substr( $style, 0, 6 ) == 'https:' ) {
2016 global $wgStylePath, $wgStyleVersion;
2017 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2020 $link = Html
::linkedStyle( $url, $media );
2022 if( isset( $options['condition'] ) ) {
2023 $condition = htmlspecialchars( $options['condition'] );
2024 $link = "<!--[if $condition]>$link<![endif]-->";
2029 function transformCssMedia( $media ) {
2030 global $wgRequest, $wgHandheldForIPhone;
2032 // Switch in on-screen display for media testing
2034 'printable' => 'print',
2035 'handheld' => 'handheld',
2037 foreach( $switches as $switch => $targetMedia ) {
2038 if( $wgRequest->getBool( $switch ) ) {
2039 if( $media == $targetMedia ) {
2041 } elseif( $media == 'screen' ) {
2047 // Expand longer media queries as iPhone doesn't grok 'handheld'
2048 if( $wgHandheldForIPhone ) {
2049 $mediaAliases = array(
2050 'screen' => 'screen and (min-device-width: 481px)',
2051 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2054 if( isset( $mediaAliases[$media] ) ) {
2055 $media = $mediaAliases[$media];
2063 * Turn off regular page output and return an error reponse
2064 * for when rate limiting has triggered.
2066 public function rateLimited() {
2068 $this->setPageTitle(wfMsg('actionthrottled'));
2069 $this->setRobotPolicy( 'noindex,follow' );
2070 $this->setArticleRelated( false );
2071 $this->enableClientCache( false );
2072 $this->mRedirect
= '';
2074 $this->setStatusCode(503);
2075 $this->addWikiMsg( 'actionthrottledtext' );
2077 $this->returnToMain( null, $this->getTitle() );
2081 * Show an "add new section" link?
2085 public function showNewSectionLink() {
2086 return $this->mNewSectionLink
;
2090 * Forcibly hide the new section link?
2094 public function forceHideNewSectionLink() {
2095 return $this->mHideNewSectionLink
;
2099 * Show a warning about slave lag
2101 * If the lag is higher than $wgSlaveLagCritical seconds,
2102 * then the warning is a bit more obvious. If the lag is
2103 * lower than $wgSlaveLagWarning, then no warning is shown.
2105 * @param int $lag Slave lag
2107 public function showLagWarning( $lag ) {
2108 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2109 if( $lag >= $wgSlaveLagWarning ) {
2110 $message = $lag < $wgSlaveLagCritical
2113 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2114 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2119 * Add a wikitext-formatted message to the output.
2120 * This is equivalent to:
2122 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2124 public function addWikiMsg( /*...*/ ) {
2125 $args = func_get_args();
2126 $name = array_shift( $args );
2127 $this->addWikiMsgArray( $name, $args );
2131 * Add a wikitext-formatted message to the output.
2132 * Like addWikiMsg() except the parameters are taken as an array
2133 * instead of a variable argument list.
2135 * $options is passed through to wfMsgExt(), see that function for details.
2137 public function addWikiMsgArray( $name, $args, $options = array() ) {
2138 $options[] = 'parse';
2139 $text = wfMsgExt( $name, $options, $args );
2140 $this->addHTML( $text );
2144 * This function takes a number of message/argument specifications, wraps them in
2145 * some overall structure, and then parses the result and adds it to the output.
2147 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2148 * on. The subsequent arguments may either be strings, in which case they are the
2149 * message names, or arrays, in which case the first element is the message name,
2150 * and subsequent elements are the parameters to that message.
2152 * The special named parameter 'options' in a message specification array is passed
2153 * through to the $options parameter of wfMsgExt().
2155 * Don't use this for messages that are not in users interface language.
2159 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
2163 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
2165 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2166 $msgSpecs = func_get_args();
2167 array_shift( $msgSpecs );
2168 $msgSpecs = array_values( $msgSpecs );
2170 foreach ( $msgSpecs as $n => $spec ) {
2172 if ( is_array( $spec ) ) {
2174 $name = array_shift( $args );
2175 if ( isset( $args['options'] ) ) {
2176 $options = $args['options'];
2177 unset( $args['options'] );
2183 $s = str_replace( '$' . ( $n +
1 ), wfMsgExt( $name, $options, $args ), $s );
2185 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );