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