1. Follow up on r49157, r50902 and r50938. According RFC 2616 section 14.4, language...
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( ! defined( 'MEDIAWIKI' ) )
3 die( 1 );
4
5 /**
6 * @todo document
7 */
8 class OutputPage {
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();
16 var $mScripts = '', $mLinkColours, $mPageLinkTitle = '', $mHeadItems = array();
17 var $mTemplateIds = array();
18
19 var $mAllowUserJs;
20 var $mSuppressQuickbar = false;
21 var $mOnloadHandler = '';
22 var $mDoNothing = false;
23 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
24 var $mIsArticleRelated = true;
25 protected $mParserOptions = null; // lazy initialised, use parserOptions()
26 var $mShowFeedLinks = false;
27 var $mFeedLinksAppendQuery = false;
28 var $mEnableClientCache = true;
29 var $mArticleBodyOnly = false;
30
31 var $mNewSectionLink = false;
32 var $mHideNewSectionLink = false;
33 var $mNoGallery = false;
34 var $mPageTitleActionText = '';
35 var $mParseWarnings = array();
36 var $mSquidMaxage = 0;
37 var $mRevisionId = null;
38 protected $mTitle = null;
39
40 /**
41 * An array of stylesheet filenames (relative from skins path), with options
42 * for CSS media, IE conditions, and RTL/LTR direction.
43 * For internal use; add settings in the skin via $this->addStyle()
44 */
45 var $styles = array();
46
47 private $mIndexPolicy = 'index';
48 private $mFollowPolicy = 'follow';
49
50 /**
51 * Constructor
52 * Initialise private variables
53 */
54 function __construct() {
55 global $wgAllowUserJs;
56 $this->mAllowUserJs = $wgAllowUserJs;
57 }
58
59 public function redirect( $url, $responsecode = '302' ) {
60 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
61 $this->mRedirect = str_replace( "\n", '', $url );
62 $this->mRedirectCode = $responsecode;
63 }
64
65 public function getRedirect() {
66 return $this->mRedirect;
67 }
68
69 /**
70 * Set the HTTP status code to send with the output.
71 *
72 * @param int $statusCode
73 * @return nothing
74 */
75 function setStatusCode( $statusCode ) { $this->mStatusCode = $statusCode; }
76
77 /**
78 * Add a new <meta> tag
79 * To add an http-equiv meta tag, precede the name with "http:"
80 *
81 * @param $name tag name
82 * @param $val tag value
83 */
84 function addMeta( $name, $val ) {
85 array_push( $this->mMetatags, array( $name, $val ) );
86 }
87
88 function addKeyword( $text ) {
89 if( is_array( $text )) {
90 $this->mKeywords = array_merge( $this->mKeywords, $text );
91 }
92 else {
93 array_push( $this->mKeywords, $text );
94 }
95 }
96 function addScript( $script ) { $this->mScripts .= "\t\t".$script; }
97
98 function addExtensionStyle( $url ) {
99 $linkarr = array( 'rel' => 'stylesheet', 'href' => $url, 'type' => 'text/css' );
100 array_push( $this->mExtStyles, $linkarr );
101 }
102
103 /**
104 * Add a JavaScript file out of skins/common, or a given relative path.
105 * @param string $file filename in skins/common or complete on-server path (/foo/bar.js)
106 */
107 function addScriptFile( $file ) {
108 global $wgStylePath, $wgStyleVersion, $wgJsMimeType;
109 if( substr( $file, 0, 1 ) == '/' ) {
110 $path = $file;
111 } else {
112 $path = "{$wgStylePath}/common/{$file}";
113 }
114 $this->addScript(
115 Xml::element( 'script',
116 array(
117 'type' => $wgJsMimeType,
118 'src' => "$path?$wgStyleVersion",
119 ),
120 '', false
121 )
122 );
123 }
124
125 /**
126 * Add a self-contained script tag with the given contents
127 * @param string $script JavaScript text, no <script> tags
128 */
129 function addInlineScript( $script ) {
130 global $wgJsMimeType;
131 $this->mScripts .= "<script type=\"$wgJsMimeType\">/*<![CDATA[*/\n$script\n/*]]>*/</script>";
132 }
133
134 function getScript() {
135 return $this->mScripts . $this->getHeadItems();
136 }
137
138 function getHeadItems() {
139 $s = '';
140 foreach ( $this->mHeadItems as $item ) {
141 $s .= $item;
142 }
143 return $s;
144 }
145
146 function addHeadItem( $name, $value ) {
147 $this->mHeadItems[$name] = $value;
148 }
149
150 function hasHeadItem( $name ) {
151 return isset( $this->mHeadItems[$name] );
152 }
153
154 function setETag($tag) { $this->mETag = $tag; }
155 function setArticleBodyOnly($only) { $this->mArticleBodyOnly = $only; }
156 function getArticleBodyOnly($only) { return $this->mArticleBodyOnly; }
157
158 function addLink( $linkarr ) {
159 # $linkarr should be an associative array of attributes. We'll escape on output.
160 array_push( $this->mLinktags, $linkarr );
161 }
162
163 # Get all links added by extensions
164 function getExtStyle() {
165 return $this->mExtStyles;
166 }
167
168 function addMetadataLink( $linkarr ) {
169 # note: buggy CC software only reads first "meta" link
170 static $haveMeta = false;
171 $linkarr['rel'] = ($haveMeta) ? 'alternate meta' : 'meta';
172 $this->addLink( $linkarr );
173 $haveMeta = true;
174 }
175
176 /**
177 * checkLastModified tells the client to use the client-cached page if
178 * possible. If sucessful, the OutputPage is disabled so that
179 * any future call to OutputPage->output() have no effect.
180 *
181 * Side effect: sets mLastModified for Last-Modified header
182 *
183 * @return bool True iff cache-ok headers was sent.
184 */
185 function checkLastModified( $timestamp ) {
186 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
187
188 if ( !$timestamp || $timestamp == '19700101000000' ) {
189 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
190 return false;
191 }
192 if( !$wgCachePages ) {
193 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
194 return false;
195 }
196 if( $wgUser->getOption( 'nocache' ) ) {
197 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
198 return false;
199 }
200
201 $timestamp = wfTimestamp( TS_MW, $timestamp );
202 $modifiedTimes = array(
203 'page' => $timestamp,
204 'user' => $wgUser->getTouched(),
205 'epoch' => $wgCacheEpoch
206 );
207 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
208
209 $maxModified = max( $modifiedTimes );
210 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
211
212 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
213 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
214 return false;
215 }
216
217 # Make debug info
218 $info = '';
219 foreach ( $modifiedTimes as $name => $value ) {
220 if ( $info !== '' ) {
221 $info .= ', ';
222 }
223 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
224 }
225
226 # IE sends sizes after the date like this:
227 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
228 # this breaks strtotime().
229 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
230
231 wfSuppressWarnings(); // E_STRICT system time bitching
232 $clientHeaderTime = strtotime( $clientHeader );
233 wfRestoreWarnings();
234 if ( !$clientHeaderTime ) {
235 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
236 return false;
237 }
238 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
239
240 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
241 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
242 wfDebug( __METHOD__ . ": effective Last-Modified: " .
243 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
244 if( $clientHeaderTime < $maxModified ) {
245 wfDebug( __METHOD__ . ": STALE, $info\n", false );
246 return false;
247 }
248
249 # Not modified
250 # Give a 304 response code and disable body output
251 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
252 ini_set('zlib.output_compression', 0);
253 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
254 $this->sendCacheControl();
255 $this->disable();
256
257 // Don't output a compressed blob when using ob_gzhandler;
258 // it's technically against HTTP spec and seems to confuse
259 // Firefox when the response gets split over two packets.
260 wfClearOutputBuffers();
261
262 return true;
263 }
264
265 function setPageTitleActionText( $text ) {
266 $this->mPageTitleActionText = $text;
267 }
268
269 function getPageTitleActionText () {
270 if ( isset( $this->mPageTitleActionText ) ) {
271 return $this->mPageTitleActionText;
272 }
273 }
274
275 /**
276 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
277 *
278 * @param $policy string The literal string to output as the contents of
279 * the meta tag. Will be parsed according to the spec and output in
280 * standardized form.
281 * @return null
282 */
283 public function setRobotPolicy( $policy ) {
284 $policy = explode( ',', $policy );
285 $policy = array_map( 'trim', $policy );
286
287 # The default policy is follow, so if nothing is said explicitly, we
288 # do that.
289 if( in_array( 'nofollow', $policy ) ) {
290 $this->mFollowPolicy = 'nofollow';
291 } else {
292 $this->mFollowPolicy = 'follow';
293 }
294
295 if( in_array( 'noindex', $policy ) ) {
296 $this->mIndexPolicy = 'noindex';
297 } else {
298 $this->mIndexPolicy = 'index';
299 }
300 }
301
302 /**
303 * Set the index policy for the page, but leave the follow policy un-
304 * touched.
305 *
306 * @param $policy string Either 'index' or 'noindex'.
307 * @return null
308 */
309 public function setIndexPolicy( $policy ) {
310 $policy = trim( $policy );
311 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
312 $this->mIndexPolicy = $policy;
313 }
314 }
315
316 /**
317 * Set the follow policy for the page, but leave the index policy un-
318 * touched.
319 *
320 * @param $policy string Either 'follow' or 'nofollow'.
321 * @return null
322 */
323 public function setFollowPolicy( $policy ) {
324 $policy = trim( $policy );
325 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
326 $this->mFollowPolicy = $policy;
327 }
328 }
329
330 /**
331 * "HTML title" means the contents of <title>. It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
332 */
333 public function setHTMLTitle( $name ) {
334 $this->mHTMLtitle = $name;
335 }
336
337 /**
338 * "Page title" means the contents of <h1>. It is stored as a valid HTML fragment.
339 * This function allows good tags like <sup> in the <h1> tag, but not bad tags like <script>.
340 * This function automatically sets <title> to the same content as <h1> but with all tags removed.
341 * Bad tags that were escaped in <h1> will still be escaped in <title>, and good tags like <i> will be dropped entirely.
342 */
343 public function setPageTitle( $name ) {
344 global $wgContLang;
345 $name = $wgContLang->convert( $name, true );
346 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
347 # but leave "<i>foobar</i>" alone
348 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
349 $this->mPagetitle = $nameWithTags;
350
351 $taction = $this->getPageTitleActionText();
352 if( !empty( $taction ) ) {
353 $name .= ' - '.$taction;
354 }
355
356 # change "<i>foo&amp;bar</i>" to "foo&bar"
357 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
358 }
359
360 public function setTitle( $t ) {
361 $this->mTitle = $t;
362 }
363
364 public function getTitle() {
365 if ( $this->mTitle instanceof Title ) {
366 return $this->mTitle;
367 }
368 else {
369 wfDebug( __METHOD__ . ' called and $mTitle is null. Return $wgTitle for sanity' );
370 global $wgTitle;
371 return $wgTitle;
372 }
373 }
374
375 public function getHTMLTitle() { return $this->mHTMLtitle; }
376 public function getPageTitle() { return $this->mPagetitle; }
377 public function setSubtitle( $str ) { $this->mSubtitle = /*$this->parse(*/$str/*)*/; } // @bug 2514
378 public function appendSubtitle( $str ) { $this->mSubtitle .= /*$this->parse(*/$str/*)*/; } // @bug 2514
379 public function getSubtitle() { return $this->mSubtitle; }
380 public function isArticle() { return $this->mIsarticle; }
381 public function setPrintable() { $this->mPrintable = true; }
382 public function isPrintable() { return $this->mPrintable; }
383 public function setSyndicated( $show = true ) { $this->mShowFeedLinks = $show; }
384 public function isSyndicated() { return $this->mShowFeedLinks; }
385 public function setFeedAppendQuery( $val ) { $this->mFeedLinksAppendQuery = $val; }
386 public function getFeedAppendQuery() { return $this->mFeedLinksAppendQuery; }
387 public function setOnloadHandler( $js ) { $this->mOnloadHandler = $js; }
388 public function getOnloadHandler() { return $this->mOnloadHandler; }
389 public function disable() { $this->mDoNothing = true; }
390 public function isDisabled() { return $this->mDoNothing; }
391
392 public function setArticleRelated( $v ) {
393 $this->mIsArticleRelated = $v;
394 if ( !$v ) {
395 $this->mIsarticle = false;
396 }
397 }
398 public function setArticleFlag( $v ) {
399 $this->mIsarticle = $v;
400 if ( $v ) {
401 $this->mIsArticleRelated = $v;
402 }
403 }
404
405 public function isArticleRelated() { return $this->mIsArticleRelated; }
406
407 public function getLanguageLinks() { return $this->mLanguageLinks; }
408 public function addLanguageLinks($newLinkArray) {
409 $this->mLanguageLinks += $newLinkArray;
410 }
411 public function setLanguageLinks($newLinkArray) {
412 $this->mLanguageLinks = $newLinkArray;
413 }
414
415 public function getCategoryLinks() {
416 return $this->mCategoryLinks;
417 }
418
419 /**
420 * Add an array of categories, with names in the keys
421 */
422 public function addCategoryLinks( $categories ) {
423 global $wgUser, $wgContLang;
424
425 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
426 return;
427 }
428
429 # Add the links to a LinkBatch
430 $arr = array( NS_CATEGORY => $categories );
431 $lb = new LinkBatch;
432 $lb->setArray( $arr );
433
434 # Fetch existence plus the hiddencat property
435 $dbr = wfGetDB( DB_SLAVE );
436 $pageTable = $dbr->tableName( 'page' );
437 $where = $lb->constructSet( 'page', $dbr );
438 $propsTable = $dbr->tableName( 'page_props' );
439 $sql = "SELECT page_id, page_namespace, page_title, page_len, page_is_redirect, pp_value
440 FROM $pageTable LEFT JOIN $propsTable ON pp_propname='hiddencat' AND pp_page=page_id WHERE $where";
441 $res = $dbr->query( $sql, __METHOD__ );
442
443 # Add the results to the link cache
444 $lb->addResultToCache( LinkCache::singleton(), $res );
445
446 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
447 $categories = array_combine( array_keys( $categories ),
448 array_fill( 0, count( $categories ), 'normal' ) );
449
450 # Mark hidden categories
451 foreach ( $res as $row ) {
452 if ( isset( $row->pp_value ) ) {
453 $categories[$row->page_title] = 'hidden';
454 }
455 }
456
457 # Add the remaining categories to the skin
458 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
459 $sk = $wgUser->getSkin();
460 foreach ( $categories as $category => $type ) {
461 $origcategory = $category;
462 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
463 $wgContLang->findVariantLink( $category, $title, true );
464 if ( $category != $origcategory )
465 if ( array_key_exists( $category, $categories ) )
466 continue;
467 $text = $wgContLang->convertHtml( $title->getText() );
468 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
469 }
470 }
471 }
472
473 public function setCategoryLinks($categories) {
474 $this->mCategoryLinks = array();
475 $this->addCategoryLinks($categories);
476 }
477
478 public function suppressQuickbar() { $this->mSuppressQuickbar = true; }
479 public function isQuickbarSuppressed() { return $this->mSuppressQuickbar; }
480
481 public function disallowUserJs() { $this->mAllowUserJs = false; }
482 public function isUserJsAllowed() { return $this->mAllowUserJs; }
483
484 public function prependHTML( $text ) { $this->mBodytext = $text . $this->mBodytext; }
485 public function addHTML( $text ) { $this->mBodytext .= $text; }
486 public function clearHTML() { $this->mBodytext = ''; }
487 public function getHTML() { return $this->mBodytext; }
488 public function debug( $text ) { $this->mDebugtext .= $text; }
489
490 /* @deprecated */
491 public function setParserOptions( $options ) {
492 wfDeprecated( __METHOD__ );
493 return $this->parserOptions( $options );
494 }
495
496 public function parserOptions( $options = null ) {
497 if ( !$this->mParserOptions ) {
498 $this->mParserOptions = new ParserOptions;
499 }
500 return wfSetVar( $this->mParserOptions, $options );
501 }
502
503 /**
504 * Set the revision ID which will be seen by the wiki text parser
505 * for things such as embedded {{REVISIONID}} variable use.
506 * @param mixed $revid an integer, or NULL
507 * @return mixed previous value
508 */
509 public function setRevisionId( $revid ) {
510 $val = is_null( $revid ) ? null : intval( $revid );
511 return wfSetVar( $this->mRevisionId, $val );
512 }
513
514 public function getRevisionId() {
515 return $this->mRevisionId;
516 }
517
518 /**
519 * Convert wikitext to HTML and add it to the buffer
520 * Default assumes that the current page title will
521 * be used.
522 *
523 * @param string $text
524 * @param bool $linestart
525 */
526 public function addWikiText( $text, $linestart = true ) {
527 $title = $this->getTitle(); // Work arround E_STRICT
528 $this->addWikiTextTitle( $text, $title, $linestart );
529 }
530
531 public function addWikiTextWithTitle($text, &$title, $linestart = true) {
532 $this->addWikiTextTitle($text, $title, $linestart);
533 }
534
535 function addWikiTextTitleTidy($text, &$title, $linestart = true) {
536 $this->addWikiTextTitle( $text, $title, $linestart, true );
537 }
538
539 public function addWikiTextTitle($text, &$title, $linestart, $tidy = false) {
540 global $wgParser;
541
542 wfProfileIn( __METHOD__ );
543
544 wfIncrStats( 'pcache_not_possible' );
545
546 $popts = $this->parserOptions();
547 $oldTidy = $popts->setTidy( $tidy );
548
549 $parserOutput = $wgParser->parse( $text, $title, $popts,
550 $linestart, true, $this->mRevisionId );
551
552 $popts->setTidy( $oldTidy );
553
554 $this->addParserOutput( $parserOutput );
555
556 wfProfileOut( __METHOD__ );
557 }
558
559 /**
560 * @todo document
561 * @param ParserOutput object &$parserOutput
562 */
563 public function addParserOutputNoText( &$parserOutput ) {
564 global $wgExemptFromUserRobotsControl, $wgContentNamespaces;
565
566 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
567 $this->addCategoryLinks( $parserOutput->getCategories() );
568 $this->mNewSectionLink = $parserOutput->getNewSection();
569 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
570
571 if( is_null( $wgExemptFromUserRobotsControl ) ) {
572 $bannedNamespaces = $wgContentNamespaces;
573 } else {
574 $bannedNamespaces = $wgExemptFromUserRobotsControl;
575 }
576 if( !in_array( $this->getTitle()->getNamespace(), $bannedNamespaces ) ) {
577 # FIXME (bug 14900): This overrides $wgArticleRobotPolicies, and it
578 # shouldn't
579 $this->setIndexPolicy( $parserOutput->getIndexPolicy() );
580 }
581
582 $this->addKeywords( $parserOutput );
583 $this->mParseWarnings = $parserOutput->getWarnings();
584 if ( $parserOutput->getCacheTime() == -1 ) {
585 $this->enableClientCache( false );
586 }
587 $this->mNoGallery = $parserOutput->getNoGallery();
588 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$parserOutput->mHeadItems );
589 // Versioning...
590 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
591 if ( isset( $this->mTemplateIds[$ns] ) ) {
592 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
593 } else {
594 $this->mTemplateIds[$ns] = $dbks;
595 }
596 }
597 // Page title
598 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false )
599 $this->setPageTitle( $dt );
600 else if ( ( $title = $parserOutput->getTitleText() ) != '' )
601 $this->setPageTitle( $title );
602
603 // Hooks registered in the object
604 global $wgParserOutputHooks;
605 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
606 list( $hookName, $data ) = $hookInfo;
607 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
608 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
609 }
610 }
611
612 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
613 }
614
615 /**
616 * @todo document
617 * @param ParserOutput &$parserOutput
618 */
619 function addParserOutput( &$parserOutput ) {
620 $this->addParserOutputNoText( $parserOutput );
621 $text = $parserOutput->getText();
622 wfRunHooks( 'OutputPageBeforeHTML',array( &$this, &$text ) );
623 $this->addHTML( $text );
624 }
625
626 /**
627 * Add wikitext to the buffer, assuming that this is the primary text for a page view
628 * Saves the text into the parser cache if possible.
629 *
630 * @param string $text
631 * @param Article $article
632 * @param bool $cache
633 * @deprecated Use Article::outputWikitext
634 */
635 public function addPrimaryWikiText( $text, $article, $cache = true ) {
636 global $wgParser;
637
638 wfDeprecated( __METHOD__ );
639
640 $popts = $this->parserOptions();
641 $popts->setTidy(true);
642 $parserOutput = $wgParser->parse( $text, $article->mTitle,
643 $popts, true, true, $this->mRevisionId );
644 $popts->setTidy(false);
645 if ( $cache && $article && $parserOutput->getCacheTime() != -1 ) {
646 $parserCache = ParserCache::singleton();
647 $parserCache->save( $parserOutput, $article, $popts);
648 }
649
650 $this->addParserOutput( $parserOutput );
651 }
652
653 /**
654 * @deprecated use addWikiTextTidy()
655 */
656 public function addSecondaryWikiText( $text, $linestart = true ) {
657 wfDeprecated( __METHOD__ );
658 $this->addWikiTextTitleTidy($text, $this->getTitle(), $linestart);
659 }
660
661 /**
662 * Add wikitext with tidy enabled
663 */
664 public function addWikiTextTidy( $text, $linestart = true ) {
665 $title = $this->getTitle();
666 $this->addWikiTextTitleTidy($text, $title, $linestart);
667 }
668
669
670 /**
671 * Add the output of a QuickTemplate to the output buffer
672 *
673 * @param QuickTemplate $template
674 */
675 public function addTemplate( &$template ) {
676 ob_start();
677 $template->execute();
678 $this->addHTML( ob_get_contents() );
679 ob_end_clean();
680 }
681
682 /**
683 * Parse wikitext and return the HTML.
684 *
685 * @param string $text
686 * @param bool $linestart Is this the start of a line?
687 * @param bool $interface ??
688 */
689 public function parse( $text, $linestart = true, $interface = false ) {
690 global $wgParser;
691 if( is_null( $this->getTitle() ) ) {
692 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
693 }
694 $popts = $this->parserOptions();
695 if ( $interface) { $popts->setInterfaceMessage(true); }
696 $parserOutput = $wgParser->parse( $text, $this->getTitle(), $popts,
697 $linestart, true, $this->mRevisionId );
698 if ( $interface) { $popts->setInterfaceMessage(false); }
699 return $parserOutput->getText();
700 }
701
702 /** Parse wikitext, strip paragraphs, and return the HTML. */
703 public function parseInline( $text, $linestart = true, $interface = false ) {
704 $parsed = $this->parse( $text, $linestart, $interface );
705
706 $m = array();
707 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
708 $parsed = $m[1];
709 }
710
711 return $parsed;
712 }
713
714 /**
715 * @param Article $article
716 * @param User $user
717 *
718 * @return bool True if successful, else false.
719 */
720 public function tryParserCache( &$article ) {
721 $parserCache = ParserCache::singleton();
722 $parserOutput = $parserCache->get( $article, $this->parserOptions() );
723 if ( $parserOutput !== false ) {
724 $this->addParserOutput( $parserOutput );
725 return true;
726 } else {
727 return false;
728 }
729 }
730
731 /**
732 * @param int $maxage Maximum cache time on the Squid, in seconds.
733 */
734 public function setSquidMaxage( $maxage ) {
735 $this->mSquidMaxage = $maxage;
736 }
737
738 /**
739 * Use enableClientCache(false) to force it to send nocache headers
740 * @param $state ??
741 */
742 public function enableClientCache( $state ) {
743 return wfSetVar( $this->mEnableClientCache, $state );
744 }
745
746 function getCacheVaryCookies() {
747 global $wgCookiePrefix, $wgCacheVaryCookies;
748 static $cookies;
749 if ( $cookies === null ) {
750 $cookies = array_merge(
751 array(
752 "{$wgCookiePrefix}Token",
753 "{$wgCookiePrefix}LoggedOut",
754 session_name()
755 ),
756 $wgCacheVaryCookies
757 );
758 wfRunHooks('GetCacheVaryCookies', array( $this, &$cookies ) );
759 }
760 return $cookies;
761 }
762
763 function uncacheableBecauseRequestVars() {
764 global $wgRequest;
765 return $wgRequest->getText('useskin', false) === false
766 && $wgRequest->getText('uselang', false) === false;
767 }
768
769 /**
770 * Check if the request has a cache-varying cookie header
771 * If it does, it's very important that we don't allow public caching
772 */
773 function haveCacheVaryCookies() {
774 global $wgRequest;
775 $cookieHeader = $wgRequest->getHeader( 'cookie' );
776 if ( $cookieHeader === false ) {
777 return false;
778 }
779 $cvCookies = $this->getCacheVaryCookies();
780 foreach ( $cvCookies as $cookieName ) {
781 # Check for a simple string match, like the way squid does it
782 if ( strpos( $cookieHeader, $cookieName ) ) {
783 wfDebug( __METHOD__.": found $cookieName\n" );
784 return true;
785 }
786 }
787 wfDebug( __METHOD__.": no cache-varying cookies found\n" );
788 return false;
789 }
790
791 /** Get a complete X-Vary-Options header */
792 public function getXVO() {
793 $cvCookies = $this->getCacheVaryCookies();
794 $xvo = 'X-Vary-Options: Accept-Encoding;list-contains=gzip,Cookie;';
795 $first = true;
796 foreach ( $cvCookies as $cookieName ) {
797 if ( $first ) {
798 $first = false;
799 } else {
800 $xvo .= ';';
801 }
802 $xvo .= 'string-contains=' . $cookieName;
803 }
804 return $xvo;
805 }
806
807 public function sendCacheControl() {
808 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest;
809
810 $response = $wgRequest->response();
811 if ($wgUseETag && $this->mETag)
812 $response->header("ETag: $this->mETag");
813
814 # don't serve compressed data to clients who can't handle it
815 # maintain different caches for logged-in users and non-logged in ones
816 $response->header( 'Vary: Accept-Encoding, Cookie' );
817
818 # Add an X-Vary-Options header for Squid with Wikimedia patches
819 $response->header( $this->getXVO() );
820
821 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
822 if( $wgUseSquid && session_id() == '' &&
823 ! $this->isPrintable() && $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies() )
824 {
825 if ( $wgUseESI ) {
826 # We'll purge the proxy cache explicitly, but require end user agents
827 # to revalidate against the proxy on each visit.
828 # Surrogate-Control controls our Squid, Cache-Control downstream caches
829 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
830 # start with a shorter timeout for initial testing
831 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
832 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
833 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
834 } else {
835 # We'll purge the proxy cache for anons explicitly, but require end user agents
836 # to revalidate against the proxy on each visit.
837 # IMPORTANT! The Squid needs to replace the Cache-Control header with
838 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
839 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
840 # start with a shorter timeout for initial testing
841 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
842 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
843 }
844 } else {
845 # We do want clients to cache if they can, but they *must* check for updates
846 # on revisiting the page.
847 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
848 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
849 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
850 }
851 if($this->mLastModified) {
852 $response->header( "Last-Modified: {$this->mLastModified}" );
853 }
854 } else {
855 wfDebug( __METHOD__ . ": no caching **\n", false );
856
857 # In general, the absence of a last modified header should be enough to prevent
858 # the client from using its cache. We send a few other things just to make sure.
859 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
860 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
861 $response->header( 'Pragma: no-cache' );
862 }
863 }
864
865 /**
866 * Finally, all the text has been munged and accumulated into
867 * the object, let's actually output it:
868 */
869 public function output() {
870 global $wgUser, $wgOutputEncoding, $wgRequest;
871 global $wgContLanguageCode, $wgDebugRedirects, $wgMimeType;
872 global $wgJsMimeType, $wgUseAjax, $wgAjaxWatch;
873 global $wgEnableMWSuggest, $wgUniversalEditButton;
874 global $wgArticle;
875
876 if( $this->mDoNothing ){
877 return;
878 }
879
880 wfProfileIn( __METHOD__ );
881
882 if ( '' != $this->mRedirect ) {
883 # Standards require redirect URLs to be absolute
884 $this->mRedirect = wfExpandUrl( $this->mRedirect );
885 if( $this->mRedirectCode == '301') {
886 if( !$wgDebugRedirects ) {
887 $wgRequest->response()->header("HTTP/1.1 {$this->mRedirectCode} Moved Permanently");
888 }
889 $this->mLastModified = wfTimestamp( TS_RFC2822 );
890 }
891
892 $this->sendCacheControl();
893
894 $wgRequest->response()->header("Content-Type: text/html; charset=utf-8");
895 if( $wgDebugRedirects ) {
896 $url = htmlspecialchars( $this->mRedirect );
897 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
898 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
899 print "</body>\n</html>\n";
900 } else {
901 $wgRequest->response()->header( 'Location: '.$this->mRedirect );
902 }
903 wfProfileOut( __METHOD__ );
904 return;
905 }
906 elseif ( $this->mStatusCode )
907 {
908 $statusMessage = array(
909 100 => 'Continue',
910 101 => 'Switching Protocols',
911 102 => 'Processing',
912 200 => 'OK',
913 201 => 'Created',
914 202 => 'Accepted',
915 203 => 'Non-Authoritative Information',
916 204 => 'No Content',
917 205 => 'Reset Content',
918 206 => 'Partial Content',
919 207 => 'Multi-Status',
920 300 => 'Multiple Choices',
921 301 => 'Moved Permanently',
922 302 => 'Found',
923 303 => 'See Other',
924 304 => 'Not Modified',
925 305 => 'Use Proxy',
926 307 => 'Temporary Redirect',
927 400 => 'Bad Request',
928 401 => 'Unauthorized',
929 402 => 'Payment Required',
930 403 => 'Forbidden',
931 404 => 'Not Found',
932 405 => 'Method Not Allowed',
933 406 => 'Not Acceptable',
934 407 => 'Proxy Authentication Required',
935 408 => 'Request Timeout',
936 409 => 'Conflict',
937 410 => 'Gone',
938 411 => 'Length Required',
939 412 => 'Precondition Failed',
940 413 => 'Request Entity Too Large',
941 414 => 'Request-URI Too Large',
942 415 => 'Unsupported Media Type',
943 416 => 'Request Range Not Satisfiable',
944 417 => 'Expectation Failed',
945 422 => 'Unprocessable Entity',
946 423 => 'Locked',
947 424 => 'Failed Dependency',
948 500 => 'Internal Server Error',
949 501 => 'Not Implemented',
950 502 => 'Bad Gateway',
951 503 => 'Service Unavailable',
952 504 => 'Gateway Timeout',
953 505 => 'HTTP Version Not Supported',
954 507 => 'Insufficient Storage'
955 );
956
957 if ( $statusMessage[$this->mStatusCode] )
958 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $statusMessage[$this->mStatusCode] );
959 }
960
961 $sk = $wgUser->getSkin();
962
963 if ( $wgUseAjax ) {
964 $this->addScriptFile( 'ajax.js' );
965
966 wfRunHooks( 'AjaxAddScript', array( &$this ) );
967
968 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
969 $this->addScriptFile( 'ajaxwatch.js' );
970 }
971
972 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ){
973 $this->addScriptFile( 'mwsuggest.js' );
974 }
975 }
976
977 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
978 $this->addScriptFile( 'rightclickedit.js' );
979 }
980
981 if( $wgUniversalEditButton ) {
982 if( isset( $wgArticle ) && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
983 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
984 // Original UniversalEditButton
985 $this->addLink( array(
986 'rel' => 'alternate',
987 'type' => 'application/x-wiki',
988 'title' => wfMsg( 'edit' ),
989 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
990 ) );
991 // Alternate edit link
992 $this->addLink( array(
993 'rel' => 'edit',
994 'title' => wfMsg( 'edit' ),
995 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
996 ) );
997 }
998 }
999
1000 # Buffer output; final headers may depend on later processing
1001 ob_start();
1002
1003 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1004 $wgRequest->response()->header( 'Content-language: '.$wgContLanguageCode );
1005
1006 if ($this->mArticleBodyOnly) {
1007 $this->out($this->mBodytext);
1008 } else {
1009 // Hook that allows last minute changes to the output page, e.g.
1010 // adding of CSS or Javascript by extensions.
1011 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1012
1013 wfProfileIn( 'Output-skin' );
1014 $sk->outputPage( $this );
1015 wfProfileOut( 'Output-skin' );
1016 }
1017
1018 $this->sendCacheControl();
1019 ob_end_flush();
1020 wfProfileOut( __METHOD__ );
1021 }
1022
1023 /**
1024 * Actually output something with print(). Performs an iconv to the
1025 * output encoding, if needed.
1026 * @param string $ins The string to output
1027 */
1028 public function out( $ins ) {
1029 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1030 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1031 $outs = $ins;
1032 } else {
1033 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1034 if ( false === $outs ) { $outs = $ins; }
1035 }
1036 print $outs;
1037 }
1038
1039 /**
1040 * @todo document
1041 */
1042 public static function setEncodings() {
1043 global $wgInputEncoding, $wgOutputEncoding;
1044 global $wgContLang;
1045
1046 $wgInputEncoding = strtolower( $wgInputEncoding );
1047
1048 if ( empty( $_SERVER['HTTP_ACCEPT_CHARSET'] ) ) {
1049 $wgOutputEncoding = strtolower( $wgOutputEncoding );
1050 return;
1051 }
1052 $wgOutputEncoding = $wgInputEncoding;
1053 }
1054
1055 /**
1056 * Deprecated, use wfReportTime() instead.
1057 * @return string
1058 * @deprecated
1059 */
1060 public function reportTime() {
1061 wfDeprecated( __METHOD__ );
1062 $time = wfReportTime();
1063 return $time;
1064 }
1065
1066 /**
1067 * Produce a "user is blocked" page.
1068 *
1069 * @param bool $return Whether to have a "return to $wgTitle" message or not.
1070 * @return nothing
1071 */
1072 function blockedPage( $return = true ) {
1073 global $wgUser, $wgContLang, $wgLang;
1074
1075 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1076 $this->setRobotPolicy( 'noindex,nofollow' );
1077 $this->setArticleRelated( false );
1078
1079 $name = User::whoIs( $wgUser->blockedBy() );
1080 $reason = $wgUser->blockedFor();
1081 if( $reason == '' ) {
1082 $reason = wfMsg( 'blockednoreason' );
1083 }
1084 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true );
1085 $ip = wfGetIP();
1086
1087 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1088
1089 $blockid = $wgUser->mBlock->mId;
1090
1091 $blockExpiry = $wgUser->mBlock->mExpiry;
1092 if ( $blockExpiry == 'infinity' ) {
1093 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1094 // Search for localization in 'ipboptions'
1095 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1096 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1097 if ( strpos( $option, ":" ) === false )
1098 continue;
1099 list( $show, $value ) = explode( ":", $option );
1100 if ( $value == 'infinite' || $value == 'indefinite' ) {
1101 $blockExpiry = $show;
1102 break;
1103 }
1104 }
1105 } else {
1106 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1107 }
1108
1109 if ( $wgUser->mBlock->mAuto ) {
1110 $msg = 'autoblockedtext';
1111 } else {
1112 $msg = 'blockedtext';
1113 }
1114
1115 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1116 * This could be a username, an ip range, or a single ip. */
1117 $intended = $wgUser->mBlock->mAddress;
1118
1119 $this->addWikiMsg( $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1120
1121 # Don't auto-return to special pages
1122 if( $return ) {
1123 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1124 $this->returnToMain( null, $return );
1125 }
1126 }
1127
1128 /**
1129 * Output a standard error page
1130 *
1131 * @param string $title Message key for page title
1132 * @param string $msg Message key for page text
1133 * @param array $params Message parameters
1134 */
1135 public function showErrorPage( $title, $msg, $params = array() ) {
1136 if ( $this->getTitle() ) {
1137 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1138 }
1139 $this->setPageTitle( wfMsg( $title ) );
1140 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1141 $this->setRobotPolicy( 'noindex,nofollow' );
1142 $this->setArticleRelated( false );
1143 $this->enableClientCache( false );
1144 $this->mRedirect = '';
1145 $this->mBodytext = '';
1146
1147 array_unshift( $params, 'parse' );
1148 array_unshift( $params, $msg );
1149 $this->addHTML( call_user_func_array( 'wfMsgExt', $params ) );
1150
1151 $this->returnToMain();
1152 }
1153
1154 /**
1155 * Output a standard permission error page
1156 *
1157 * @param array $errors Error message keys
1158 */
1159 public function showPermissionsErrorPage( $errors, $action = null )
1160 {
1161 $this->mDebugtext .= 'Original title: ' .
1162 $this->getTitle()->getPrefixedText() . "\n";
1163 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1164 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1165 $this->setRobotPolicy( 'noindex,nofollow' );
1166 $this->setArticleRelated( false );
1167 $this->enableClientCache( false );
1168 $this->mRedirect = '';
1169 $this->mBodytext = '';
1170 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1171 }
1172
1173 /** @deprecated */
1174 public function errorpage( $title, $msg ) {
1175 wfDeprecated( __METHOD__ );
1176 throw new ErrorPageError( $title, $msg );
1177 }
1178
1179 /**
1180 * Display an error page indicating that a given version of MediaWiki is
1181 * required to use it
1182 *
1183 * @param mixed $version The version of MediaWiki needed to use the page
1184 */
1185 public function versionRequired( $version ) {
1186 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1187 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1188 $this->setRobotPolicy( 'noindex,nofollow' );
1189 $this->setArticleRelated( false );
1190 $this->mBodytext = '';
1191
1192 $this->addWikiMsg( 'versionrequiredtext', $version );
1193 $this->returnToMain();
1194 }
1195
1196 /**
1197 * Display an error page noting that a given permission bit is required.
1198 *
1199 * @param string $permission key required
1200 */
1201 public function permissionRequired( $permission ) {
1202 global $wgLang;
1203
1204 $this->setPageTitle( wfMsg( 'badaccess' ) );
1205 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1206 $this->setRobotPolicy( 'noindex,nofollow' );
1207 $this->setArticleRelated( false );
1208 $this->mBodytext = '';
1209
1210 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1211 User::getGroupsWithPermission( $permission ) );
1212 if( $groups ) {
1213 $this->addWikiMsg( 'badaccess-groups',
1214 $wgLang->commaList( $groups ),
1215 count( $groups) );
1216 } else {
1217 $this->addWikiMsg( 'badaccess-group0' );
1218 }
1219 $this->returnToMain();
1220 }
1221
1222 /**
1223 * Use permissionRequired.
1224 * @deprecated
1225 */
1226 public function sysopRequired() {
1227 throw new MWException( "Call to deprecated OutputPage::sysopRequired() method\n" );
1228 }
1229
1230 /**
1231 * Use permissionRequired.
1232 * @deprecated
1233 */
1234 public function developerRequired() {
1235 throw new MWException( "Call to deprecated OutputPage::developerRequired() method\n" );
1236 }
1237
1238 /**
1239 * Produce the stock "please login to use the wiki" page
1240 */
1241 public function loginToUse() {
1242 global $wgUser, $wgContLang;
1243
1244 if( $wgUser->isLoggedIn() ) {
1245 $this->permissionRequired( 'read' );
1246 return;
1247 }
1248
1249 $skin = $wgUser->getSkin();
1250
1251 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1252 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1253 $this->setRobotPolicy( 'noindex,nofollow' );
1254 $this->setArticleFlag( false );
1255
1256 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1257 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->getTitle()->getPrefixedUrl() );
1258 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
1259 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . "-->" );
1260
1261 # Don't return to the main page if the user can't read it
1262 # otherwise we'll end up in a pointless loop
1263 $mainPage = Title::newMainPage();
1264 if( $mainPage->userCanRead() )
1265 $this->returnToMain( null, $mainPage );
1266 }
1267
1268 /** @deprecated */
1269 public function databaseError( $fname, $sql, $error, $errno ) {
1270 throw new MWException( "OutputPage::databaseError is obsolete\n" );
1271 }
1272
1273 /**
1274 * @param array $errors An array of arrays returned by Title::getUserPermissionsErrors
1275 * @return string The wikitext error-messages, formatted into a list.
1276 */
1277 public function formatPermissionsErrorMessage( $errors, $action = null ) {
1278 if ($action == null) {
1279 $text = wfMsgNoTrans( 'permissionserrorstext', count($errors)). "\n\n";
1280 } else {
1281 global $wgLang;
1282 $action_desc = wfMsgNoTrans( "action-$action" );
1283 $text = wfMsgNoTrans( 'permissionserrorstext-withaction', count($errors), $action_desc ) . "\n\n";
1284 }
1285
1286 if (count( $errors ) > 1) {
1287 $text .= '<ul class="permissions-errors">' . "\n";
1288
1289 foreach( $errors as $error )
1290 {
1291 $text .= '<li>';
1292 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
1293 $text .= "</li>\n";
1294 }
1295 $text .= '</ul>';
1296 } else {
1297 $text .= "<div class=\"permissions-errors\">\n" . call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) . "\n</div>";
1298 }
1299
1300 return $text;
1301 }
1302
1303 /**
1304 * Display a page stating that the Wiki is in read-only mode,
1305 * and optionally show the source of the page that the user
1306 * was trying to edit. Should only be called (for this
1307 * purpose) after wfReadOnly() has returned true.
1308 *
1309 * For historical reasons, this function is _also_ used to
1310 * show the error message when a user tries to edit a page
1311 * they are not allowed to edit. (Unless it's because they're
1312 * blocked, then we show blockedPage() instead.) In this
1313 * case, the second parameter should be set to true and a list
1314 * of reasons supplied as the third parameter.
1315 *
1316 * @todo Needs to be split into multiple functions.
1317 *
1318 * @param string $source Source code to show (or null).
1319 * @param bool $protected Is this a permissions error?
1320 * @param array $reasons List of reasons for this error, as returned by Title::getUserPermissionsErrors().
1321 */
1322 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
1323 global $wgUser;
1324 $skin = $wgUser->getSkin();
1325
1326 $this->setRobotPolicy( 'noindex,nofollow' );
1327 $this->setArticleRelated( false );
1328
1329 // If no reason is given, just supply a default "I can't let you do
1330 // that, Dave" message. Should only occur if called by legacy code.
1331 if ( $protected && empty($reasons) ) {
1332 $reasons[] = array( 'badaccess-group0' );
1333 }
1334
1335 if ( !empty($reasons) ) {
1336 // Permissions error
1337 if( $source ) {
1338 $this->setPageTitle( wfMsg( 'viewsource' ) );
1339 $this->setSubtitle( wfMsg( 'viewsourcefor', $skin->makeKnownLinkObj( $this->getTitle() ) ) );
1340 } else {
1341 $this->setPageTitle( wfMsg( 'badaccess' ) );
1342 }
1343 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
1344 } else {
1345 // Wiki is read only
1346 $this->setPageTitle( wfMsg( 'readonly' ) );
1347 $reason = wfReadOnlyReason();
1348 $this->wrapWikiMsg( '<div class="mw-readonly-error">$1</div>', array( 'readonlytext', $reason ) );
1349 }
1350
1351 // Show source, if supplied
1352 if( is_string( $source ) ) {
1353 $this->addWikiMsg( 'viewsourcetext' );
1354 $text = Xml::openElement( 'textarea',
1355 array( 'id' => 'wpTextbox1',
1356 'name' => 'wpTextbox1',
1357 'cols' => $wgUser->getOption( 'cols' ),
1358 'rows' => $wgUser->getOption( 'rows' ),
1359 'readonly' => 'readonly' ) );
1360 $text .= htmlspecialchars( $source );
1361 $text .= Xml::closeElement( 'textarea' );
1362 $this->addHTML( $text );
1363
1364 // Show templates used by this article
1365 $skin = $wgUser->getSkin();
1366 $article = new Article( $this->getTitle() );
1367 $this->addHTML( "<div class='templatesUsed'>
1368 {$skin->formatTemplates( $article->getUsedTemplates() )}
1369 </div>
1370 " );
1371 }
1372
1373 # If the title doesn't exist, it's fairly pointless to print a return
1374 # link to it. After all, you just tried editing it and couldn't, so
1375 # what's there to do there?
1376 if( $this->getTitle()->exists() ) {
1377 $this->returnToMain( null, $this->getTitle() );
1378 }
1379 }
1380
1381 /** @deprecated */
1382 public function fatalError( $message ) {
1383 wfDeprecated( __METHOD__ );
1384 throw new FatalError( $message );
1385 }
1386
1387 /** @deprecated */
1388 public function unexpectedValueError( $name, $val ) {
1389 wfDeprecated( __METHOD__ );
1390 throw new FatalError( wfMsg( 'unexpected', $name, $val ) );
1391 }
1392
1393 /** @deprecated */
1394 public function fileCopyError( $old, $new ) {
1395 wfDeprecated( __METHOD__ );
1396 throw new FatalError( wfMsg( 'filecopyerror', $old, $new ) );
1397 }
1398
1399 /** @deprecated */
1400 public function fileRenameError( $old, $new ) {
1401 wfDeprecated( __METHOD__ );
1402 throw new FatalError( wfMsg( 'filerenameerror', $old, $new ) );
1403 }
1404
1405 /** @deprecated */
1406 public function fileDeleteError( $name ) {
1407 wfDeprecated( __METHOD__ );
1408 throw new FatalError( wfMsg( 'filedeleteerror', $name ) );
1409 }
1410
1411 /** @deprecated */
1412 public function fileNotFoundError( $name ) {
1413 wfDeprecated( __METHOD__ );
1414 throw new FatalError( wfMsg( 'filenotfound', $name ) );
1415 }
1416
1417 public function showFatalError( $message ) {
1418 $this->setPageTitle( wfMsg( "internalerror" ) );
1419 $this->setRobotPolicy( "noindex,nofollow" );
1420 $this->setArticleRelated( false );
1421 $this->enableClientCache( false );
1422 $this->mRedirect = '';
1423 $this->mBodytext = $message;
1424 }
1425
1426 public function showUnexpectedValueError( $name, $val ) {
1427 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
1428 }
1429
1430 public function showFileCopyError( $old, $new ) {
1431 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
1432 }
1433
1434 public function showFileRenameError( $old, $new ) {
1435 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
1436 }
1437
1438 public function showFileDeleteError( $name ) {
1439 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
1440 }
1441
1442 public function showFileNotFoundError( $name ) {
1443 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
1444 }
1445
1446 /**
1447 * Add a "return to" link pointing to a specified title
1448 *
1449 * @param Title $title Title to link
1450 */
1451 public function addReturnTo( $title ) {
1452 global $wgUser;
1453 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullUrl() ) );
1454 $link = wfMsgHtml( 'returnto', $wgUser->getSkin()->link( $title ) );
1455 $this->addHTML( "<p>{$link}</p>\n" );
1456 }
1457
1458 /**
1459 * Add a "return to" link pointing to a specified title,
1460 * or the title indicated in the request, or else the main page
1461 *
1462 * @param null $unused No longer used
1463 * @param Title $returnto Title to return to
1464 */
1465 public function returnToMain( $unused = null, $returnto = NULL ) {
1466 global $wgRequest;
1467
1468 if ( $returnto == NULL ) {
1469 $returnto = $wgRequest->getText( 'returnto' );
1470 }
1471
1472 if ( '' === $returnto ) {
1473 $returnto = Title::newMainPage();
1474 }
1475
1476 if ( is_object( $returnto ) ) {
1477 $titleObj = $returnto;
1478 } else {
1479 $titleObj = Title::newFromText( $returnto );
1480 }
1481 if ( !is_object( $titleObj ) ) {
1482 $titleObj = Title::newMainPage();
1483 }
1484
1485 $this->addReturnTo( $titleObj );
1486 }
1487
1488 /**
1489 * This function takes the title (first item of mGoodLinks), categories,
1490 * existing and broken links for the page
1491 * and uses the first 10 of them for META keywords
1492 *
1493 * @param ParserOutput &$parserOutput
1494 */
1495 private function addKeywords( &$parserOutput ) {
1496 global $wgContLang;
1497 // Get an array of keywords if there are more than one
1498 // variant of the site language
1499 $text = $wgContLang->autoConvertToAllVariants( $this->getTitle()->getPrefixedText());
1500 // array_values: We needn't to merge variant's code name
1501 // into $this->mKeywords;
1502 // array_unique: We should insert a keyword just for once
1503 $text = array_unique( array_values( $text ));
1504 $this->addKeyword( $text );
1505 $count = 1;
1506 $links2d =& $parserOutput->getLinks();
1507 if ( !is_array( $links2d ) ) {
1508 return;
1509 }
1510 foreach ( $links2d as $dbkeys ) {
1511 foreach( $dbkeys as $dbkey => $unused ) {
1512 $dbkey = $wgContLang->autoConvertToAllVariants( $dbkey );
1513 $dbkey = array_unique( array_values( $dbkey ));
1514 $this->addKeyword( $dbkey );
1515 if ( ++$count > 10 ) {
1516 break 2;
1517 }
1518 }
1519 }
1520 }
1521
1522 /**
1523 * @return string The doctype, opening <html>, and head element.
1524 */
1525 public function headElement( Skin $sk ) {
1526 global $wgDocType, $wgDTD, $wgContLanguageCode, $wgOutputEncoding, $wgMimeType;
1527 global $wgXhtmlDefaultNamespace, $wgXhtmlNamespaces;
1528 global $wgContLang, $wgUseTrackbacks, $wgStyleVersion;
1529
1530 $this->addMeta( "http:Content-type", "$wgMimeType; charset={$wgOutputEncoding}" );
1531 $this->addStyle( 'common/wikiprintable.css', 'print' );
1532 $sk->setupUserCss( $this );
1533
1534 $ret = '';
1535
1536 if( $wgMimeType == 'text/xml' || $wgMimeType == 'application/xhtml+xml' || $wgMimeType == 'application/xml' ) {
1537 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
1538 }
1539
1540 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\"\n \"$wgDTD\">\n";
1541
1542 if ( '' == $this->getHTMLTitle() ) {
1543 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ));
1544 }
1545
1546 $rtl = $wgContLang->isRTL() ? " dir='RTL'" : '';
1547 $ret .= "<html xmlns=\"{$wgXhtmlDefaultNamespace}\" ";
1548 foreach($wgXhtmlNamespaces as $tag => $ns) {
1549 $ret .= "xmlns:{$tag}=\"{$ns}\" ";
1550 }
1551 $ret .= "xml:lang=\"$wgContLanguageCode\" lang=\"$wgContLanguageCode\" $rtl>\n";
1552 $ret .= "<head>\n<title>" . htmlspecialchars( $this->getHTMLTitle() ) . "</title>\n\t\t";
1553 $ret .= implode( "\t\t", array(
1554 $this->getHeadLinks(),
1555 $this->buildCssLinks(),
1556 $sk->getHeadScripts( $this->mAllowUserJs ),
1557 $this->mScripts,
1558 $this->getHeadItems(),
1559 ));
1560 if( $sk->usercss ){
1561 $ret .= "<style type='text/css'>{$sk->usercss}</style>";
1562 }
1563
1564 if ($wgUseTrackbacks && $this->isArticleRelated())
1565 $ret .= $this->getTitle()->trackbackRDF();
1566
1567 $ret .= "</head>\n";
1568 return $ret;
1569 }
1570
1571 protected function addDefaultMeta() {
1572 global $wgVersion;
1573 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); //bug 15835
1574 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
1575
1576 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
1577 if( $p !== 'index,follow' ) {
1578 // http://www.robotstxt.org/wc/meta-user.html
1579 // Only show if it's different from the default robots policy
1580 $this->addMeta( 'robots', $p );
1581 }
1582
1583 if ( count( $this->mKeywords ) > 0 ) {
1584 $strip = array(
1585 "/<.*?" . ">/" => '',
1586 "/_/" => ' '
1587 );
1588 $this->addMeta( 'keywords', preg_replace(array_keys($strip), array_values($strip),implode( ",", $this->mKeywords ) ) );
1589 }
1590 }
1591
1592 /**
1593 * @return string HTML tag links to be put in the header.
1594 */
1595 public function getHeadLinks() {
1596 global $wgRequest, $wgFeed;
1597
1598 // Ideally this should happen earlier, somewhere. :P
1599 $this->addDefaultMeta();
1600
1601 $tags = array();
1602
1603 foreach ( $this->mMetatags as $tag ) {
1604 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
1605 $a = 'http-equiv';
1606 $tag[0] = substr( $tag[0], 5 );
1607 } else {
1608 $a = 'name';
1609 }
1610 $tags[] = Xml::element( 'meta',
1611 array(
1612 $a => $tag[0],
1613 'content' => $tag[1] ) );
1614 }
1615 foreach ( $this->mLinktags as $tag ) {
1616 $tags[] = Xml::element( 'link', $tag );
1617 }
1618
1619 if( $wgFeed ) {
1620 foreach( $this->getSyndicationLinks() as $format => $link ) {
1621 # Use the page name for the title (accessed through $wgTitle since
1622 # there's no other way). In principle, this could lead to issues
1623 # with having the same name for different feeds corresponding to
1624 # the same page, but we can't avoid that at this low a level.
1625
1626 $tags[] = $this->feedLink(
1627 $format,
1628 $link,
1629 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() ) ); # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
1630 }
1631
1632 # Recent changes feed should appear on every page (except recentchanges,
1633 # that would be redundant). Put it after the per-page feed to avoid
1634 # changing existing behavior. It's still available, probably via a
1635 # menu in your browser. Some sites might have a different feed they'd
1636 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
1637 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
1638 # If so, use it instead.
1639
1640 global $wgOverrideSiteFeed, $wgSitename, $wgFeedClasses;
1641 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
1642
1643 if ( $wgOverrideSiteFeed ) {
1644 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
1645 $tags[] = $this->feedLink (
1646 $type,
1647 htmlspecialchars( $feedUrl ),
1648 wfMsg( "site-{$type}-feed", $wgSitename ) );
1649 }
1650 }
1651 else if ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
1652 foreach( $wgFeedClasses as $format => $class ) {
1653 $tags[] = $this->feedLink(
1654 $format,
1655 $rctitle->getLocalURL( "feed={$format}" ),
1656 wfMsg( "site-{$format}-feed", $wgSitename ) ); # For grep: 'site-rss-feed', 'site-atom-feed'.
1657 }
1658 }
1659 }
1660
1661 return implode( "\n\t\t", $tags ) . "\n";
1662 }
1663
1664 /**
1665 * Return URLs for each supported syndication format for this page.
1666 * @return array associating format keys with URLs
1667 */
1668 public function getSyndicationLinks() {
1669 global $wgFeedClasses;
1670 $links = array();
1671
1672 if( $this->isSyndicated() ) {
1673 if( is_string( $this->getFeedAppendQuery() ) ) {
1674 $appendQuery = "&" . $this->getFeedAppendQuery();
1675 } else {
1676 $appendQuery = "";
1677 }
1678
1679 foreach( $wgFeedClasses as $format => $class ) {
1680 $links[$format] = $this->getTitle()->getLocalUrl( "feed=$format{$appendQuery}" );
1681 }
1682 }
1683 return $links;
1684 }
1685
1686 /**
1687 * Generate a <link rel/> for an RSS feed.
1688 */
1689 private function feedLink( $type, $url, $text ) {
1690 return Xml::element( 'link', array(
1691 'rel' => 'alternate',
1692 'type' => "application/$type+xml",
1693 'title' => $text,
1694 'href' => $url ) );
1695 }
1696
1697 /**
1698 * Add a local or specified stylesheet, with the given media options.
1699 * Meant primarily for internal use...
1700 *
1701 * @param $media -- to specify a media type, 'screen', 'printable', 'handheld' or any.
1702 * @param $conditional -- for IE conditional comments, specifying an IE version
1703 * @param $dir -- set to 'rtl' or 'ltr' for direction-specific sheets
1704 */
1705 public function addStyle( $style, $media='', $condition='', $dir='' ) {
1706 $options = array();
1707 if( $media )
1708 $options['media'] = $media;
1709 if( $condition )
1710 $options['condition'] = $condition;
1711 if( $dir )
1712 $options['dir'] = $dir;
1713 $this->styles[$style] = $options;
1714 }
1715
1716 /**
1717 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
1718 * These will be applied to various media & IE conditionals.
1719 */
1720 public function buildCssLinks() {
1721 $links = array();
1722 foreach( $this->styles as $file => $options ) {
1723 $link = $this->styleLink( $file, $options );
1724 if( $link )
1725 $links[] = $link;
1726 }
1727
1728 return implode( "\n\t\t", $links );
1729 }
1730
1731 protected function styleLink( $style, $options ) {
1732 global $wgRequest;
1733
1734 if( isset( $options['dir'] ) ) {
1735 global $wgContLang;
1736 $siteDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
1737 if( $siteDir != $options['dir'] )
1738 return '';
1739 }
1740
1741 if( isset( $options['media'] ) ) {
1742 $media = $this->transformCssMedia( $options['media'] );
1743 if( is_null( $media ) ) {
1744 return '';
1745 }
1746 } else {
1747 $media = '';
1748 }
1749
1750 if( substr( $style, 0, 1 ) == '/' ||
1751 substr( $style, 0, 5 ) == 'http:' ||
1752 substr( $style, 0, 6 ) == 'https:' ) {
1753 $url = $style;
1754 } else {
1755 global $wgStylePath, $wgStyleVersion;
1756 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
1757 }
1758
1759 $attribs = array(
1760 'rel' => 'stylesheet',
1761 'href' => $url,
1762 'type' => 'text/css' );
1763 if( $media ) {
1764 $attribs['media'] = $media;
1765 }
1766
1767 $link = Xml::element( 'link', $attribs );
1768
1769 if( isset( $options['condition'] ) ) {
1770 $condition = htmlspecialchars( $options['condition'] );
1771 $link = "<!--[if $condition]>$link<![endif]-->";
1772 }
1773 return $link;
1774 }
1775
1776 function transformCssMedia( $media ) {
1777 global $wgRequest, $wgHandheldForIPhone;
1778
1779 // Switch in on-screen display for media testing
1780 $switches = array(
1781 'printable' => 'print',
1782 'handheld' => 'handheld',
1783 );
1784 foreach( $switches as $switch => $targetMedia ) {
1785 if( $wgRequest->getBool( $switch ) ) {
1786 if( $media == $targetMedia ) {
1787 $media = '';
1788 } elseif( $media == 'screen' ) {
1789 return null;
1790 }
1791 }
1792 }
1793
1794 // Expand longer media queries as iPhone doesn't grok 'handheld'
1795 if( $wgHandheldForIPhone ) {
1796 $mediaAliases = array(
1797 'screen' => 'screen and (min-device-width: 481px)',
1798 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
1799 );
1800
1801 if( isset( $mediaAliases[$media] ) ) {
1802 $media = $mediaAliases[$media];
1803 }
1804 }
1805
1806 return $media;
1807 }
1808
1809 /**
1810 * Turn off regular page output and return an error reponse
1811 * for when rate limiting has triggered.
1812 */
1813 public function rateLimited() {
1814
1815 $this->setPageTitle(wfMsg('actionthrottled'));
1816 $this->setRobotPolicy( 'noindex,follow' );
1817 $this->setArticleRelated( false );
1818 $this->enableClientCache( false );
1819 $this->mRedirect = '';
1820 $this->clearHTML();
1821 $this->setStatusCode(503);
1822 $this->addWikiMsg( 'actionthrottledtext' );
1823
1824 $this->returnToMain( null, $this->getTitle() );
1825 }
1826
1827 /**
1828 * Show an "add new section" link?
1829 *
1830 * @return bool
1831 */
1832 public function showNewSectionLink() {
1833 return $this->mNewSectionLink;
1834 }
1835
1836 /**
1837 * Forcibly hide the new section link?
1838 *
1839 * @return bool
1840 */
1841 public function forceHideNewSectionLink() {
1842 return $this->mHideNewSectionLink;
1843 }
1844
1845 /**
1846 * Show a warning about slave lag
1847 *
1848 * If the lag is higher than $wgSlaveLagCritical seconds,
1849 * then the warning is a bit more obvious. If the lag is
1850 * lower than $wgSlaveLagWarning, then no warning is shown.
1851 *
1852 * @param int $lag Slave lag
1853 */
1854 public function showLagWarning( $lag ) {
1855 global $wgSlaveLagWarning, $wgSlaveLagCritical;
1856 if( $lag >= $wgSlaveLagWarning ) {
1857 $message = $lag < $wgSlaveLagCritical
1858 ? 'lag-warn-normal'
1859 : 'lag-warn-high';
1860 $warning = wfMsgExt( $message, 'parse', $lag );
1861 $this->addHTML( "<div class=\"mw-{$message}\">\n{$warning}\n</div>\n" );
1862 }
1863 }
1864
1865 /**
1866 * Add a wikitext-formatted message to the output.
1867 * This is equivalent to:
1868 *
1869 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
1870 */
1871 public function addWikiMsg( /*...*/ ) {
1872 $args = func_get_args();
1873 $name = array_shift( $args );
1874 $this->addWikiMsgArray( $name, $args );
1875 }
1876
1877 /**
1878 * Add a wikitext-formatted message to the output.
1879 * Like addWikiMsg() except the parameters are taken as an array
1880 * instead of a variable argument list.
1881 *
1882 * $options is passed through to wfMsgExt(), see that function for details.
1883 */
1884 public function addWikiMsgArray( $name, $args, $options = array() ) {
1885 $options[] = 'parse';
1886 $text = wfMsgExt( $name, $options, $args );
1887 $this->addHTML( $text );
1888 }
1889
1890 /**
1891 * This function takes a number of message/argument specifications, wraps them in
1892 * some overall structure, and then parses the result and adds it to the output.
1893 *
1894 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
1895 * on. The subsequent arguments may either be strings, in which case they are the
1896 * message names, or arrays, in which case the first element is the message name,
1897 * and subsequent elements are the parameters to that message.
1898 *
1899 * The special named parameter 'options' in a message specification array is passed
1900 * through to the $options parameter of wfMsgExt().
1901 *
1902 * Don't use this for messages that are not in users interface language.
1903 *
1904 * For example:
1905 *
1906 * $wgOut->wrapWikiMsg( '<div class="error">$1</div>', 'some-error' );
1907 *
1908 * Is equivalent to:
1909 *
1910 * $wgOut->addWikiText( '<div class="error">' . wfMsgNoTrans( 'some-error' ) . '</div>' );
1911 */
1912 public function wrapWikiMsg( $wrap /*, ...*/ ) {
1913 $msgSpecs = func_get_args();
1914 array_shift( $msgSpecs );
1915 $msgSpecs = array_values( $msgSpecs );
1916 $s = $wrap;
1917 foreach ( $msgSpecs as $n => $spec ) {
1918 $options = array();
1919 if ( is_array( $spec ) ) {
1920 $args = $spec;
1921 $name = array_shift( $args );
1922 if ( isset( $args['options'] ) ) {
1923 $options = $args['options'];
1924 unset( $args['options'] );
1925 }
1926 } else {
1927 $args = array();
1928 $name = $spec;
1929 }
1930 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
1931 }
1932 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
1933 }
1934 }