Completely remove support for legacy style skins. All legacy skinning options are...
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 if ( !defined( 'MEDIAWIKI' ) ) {
3 die( 1 );
4 }
5
6 /**
7 * This class should be covered by a general architecture document which does
8 * not exist as of january 2011. This is one of the Core class and should
9 * be read at least once by any new developers.
10 *
11 * This class is used to prepare the final rendering. A skin is then
12 * applied to the output parameters (links, javascript, html, categories ...).
13 *
14 * Another class (fixme) handle sending the whole page to the client.
15 *
16 * Some comments comes from a pairing session between Zak Greant and Ashar Voultoiz
17 * in november 2010.
18 *
19 * @todo document
20 */
21 class OutputPage {
22 /// Should be private. Used with addMeta() which adds <meta>
23 var $mMetatags = array();
24
25 /// <meta keyworkds="stuff"> most of the time the first 10 links to an article
26 var $mKeywords = array();
27
28 var $mLinktags = array();
29
30 /// Additional stylesheets. Looks like this is for extensions. Might be replaced by resource loader.
31 var $mExtStyles = array();
32
33 /// Should be private - has getter and setter. Contains the HTML title
34 var $mPagetitle = '';
35
36 /// Contains all of the <body> content. Should be private we got set/get accessors and the append() method.
37 var $mBodytext = '';
38
39 /**
40 * Holds the debug lines that will be outputted as comments in page source if
41 * $wgDebugComments is enabled. See also $wgShowDebug.
42 * TODO: make a getter method for this
43 */
44 public $mDebugtext = ''; // TODO: we might want to replace it by wfDebug() wfDebugLog()
45
46 /// Should be private. Stores contents of <title> tag
47 var $mHTMLtitle = '';
48
49 /// Should be private. Is the displayed content related to the source of the corresponding wiki article.
50 var $mIsarticle = true;
51
52 /**
53 * Should be private. We have to set isPrintable(). Some pages should
54 * never be printed (ex: redirections).
55 */
56 var $mPrintable = false;
57
58 /**
59 * Should be private. We have set/get/append methods.
60 *
61 * Contains the page subtitle. Special pages usually have some links here.
62 * Don't confuse with site subtitle added by skins.
63 */
64 var $mSubtitle = '';
65
66 var $mRedirect = '';
67 var $mStatusCode;
68
69 /**
70 * mLastModified and mEtag are used for sending cache control.
71 * The whole caching system should probably be moved in its own class.
72 */
73 var $mLastModified = '';
74
75 /**
76 * Should be private. No getter but used in sendCacheControl();
77 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
78 * as a unique identifier for the content. It is later used by the client
79 * to compare its cache version with the server version. Client sends
80 * headers If-Match and If-None-Match containing its local cache ETAG value.
81 *
82 * To get more information, you will have to look at HTTP1/1 protocols which
83 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
84 */
85 var $mETag = false;
86
87 var $mCategoryLinks = array();
88 var $mCategories = array();
89
90 /// Should be private. Associative array mapping language code to the page name
91 var $mLanguageLinks = array();
92
93 /**
94 * Should be private. Used for JavaScript (pre resource loader)
95 * We should split js / css.
96 * mScripts content is inserted as is in <head> by Skin. This might contains
97 * either a link to a stylesheet or inline css.
98 */
99 var $mScripts = '';
100
101 /**
102 * Inline CSS styles. Use addInlineStyle() sparsingly
103 */
104 var $mInlineStyles = '';
105
106 //
107 var $mLinkColours;
108
109 /**
110 * Used by skin template.
111 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
112 */
113 var $mPageLinkTitle = '';
114
115 /// Array of elements in <head>. Parser might add its own headers!
116 var $mHeadItems = array();
117
118 // Next variables probably comes from the resource loader @todo FIXME
119 var $mModules = array(), $mModuleScripts = array(), $mModuleStyles = array(), $mModuleMessages = array();
120 var $mResourceLoader;
121
122 /** @fixme is this still used ?*/
123 var $mInlineMsg = array();
124
125 var $mTemplateIds = array();
126
127 /** Initialized with a global value. Let us override it.
128 * Should probably get deleted / rewritten ... */
129 var $mAllowUserJs;
130
131 /**
132 * @EasterEgg I just love the name for this self documenting variable.
133 * @todo document
134 */
135 var $mDoNothing = false;
136
137 // Parser related.
138 var $mContainsOldMagic = 0, $mContainsNewMagic = 0;
139
140 /**
141 * Should be private. Has get/set methods properly documented.
142 * Stores "article flag" toggle.
143 */
144 var $mIsArticleRelated = true;
145
146 /// lazy initialised, use parserOptions()
147 protected $mParserOptions = null;
148
149 /**
150 * Handles the atom / rss links.
151 * We probably only support atom in 2011.
152 * Looks like a private variable.
153 * @see $wgAdvertisedFeedTypes
154 */
155 var $mFeedLinks = array();
156
157 // Gwicke work on squid caching? Roughly from 2003.
158 var $mEnableClientCache = true;
159
160 /**
161 * Flag if output should only contain the body of the article.
162 * Should be private.
163 */
164 var $mArticleBodyOnly = false;
165
166 var $mNewSectionLink = false;
167 var $mHideNewSectionLink = false;
168
169 /**
170 * Comes from the parser. This was probably made to load CSS/JS only
171 * if we had <gallery>. Used directly in CategoryPage.php
172 * Looks like resource loader can replace this.
173 */
174 var $mNoGallery = false;
175
176 // should be private.
177 var $mPageTitleActionText = '';
178 var $mParseWarnings = array();
179
180 // Cache stuff. Looks like mEnableClientCache
181 var $mSquidMaxage = 0;
182
183 // @todo document
184 var $mPreventClickjacking = true;
185
186 /// should be private. To include the variable {{REVISIONID}}
187 var $mRevisionId = null;
188
189 /// Stores a Title object (of the current page).
190 protected $mTitle = null;
191
192 /**
193 * An array of stylesheet filenames (relative from skins path), with options
194 * for CSS media, IE conditions, and RTL/LTR direction.
195 * For internal use; add settings in the skin via $this->addStyle()
196 *
197 * Style again! This seems like a code duplication since we already have
198 * mStyles. This is what makes OpenSource amazing.
199 */
200 var $styles = array();
201
202 /**
203 * Whether jQuery is already handled.
204 */
205 protected $mJQueryDone = false;
206
207 private $mIndexPolicy = 'index';
208 private $mFollowPolicy = 'follow';
209 private $mVaryHeader = array(
210 'Accept-Encoding' => array( 'list-contains=gzip' ),
211 'Cookie' => null
212 );
213
214 /**
215 * Constructor
216 * Initialise private variables
217 */
218 function __construct() {
219 global $wgAllowUserJs;
220 $this->mAllowUserJs = $wgAllowUserJs;
221 }
222
223 /**
224 * Redirect to $url rather than displaying the normal page
225 *
226 * @param $url String: URL
227 * @param $responsecode String: HTTP status code
228 */
229 public function redirect( $url, $responsecode = '302' ) {
230 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
231 $this->mRedirect = str_replace( "\n", '', $url );
232 $this->mRedirectCode = $responsecode;
233 }
234
235 /**
236 * Get the URL to redirect to, or an empty string if not redirect URL set
237 *
238 * @return String
239 */
240 public function getRedirect() {
241 return $this->mRedirect;
242 }
243
244 /**
245 * Set the HTTP status code to send with the output.
246 *
247 * @param $statusCode Integer
248 */
249 public function setStatusCode( $statusCode ) {
250 $this->mStatusCode = $statusCode;
251 }
252
253 /**
254 * Add a new <meta> tag
255 * To add an http-equiv meta tag, precede the name with "http:"
256 *
257 * @param $name String tag name
258 * @param $val String tag value
259 */
260 function addMeta( $name, $val ) {
261 array_push( $this->mMetatags, array( $name, $val ) );
262 }
263
264 /**
265 * Add a keyword or a list of keywords in the page header
266 *
267 * @param $text String or array of strings
268 */
269 function addKeyword( $text ) {
270 if( is_array( $text ) ) {
271 $this->mKeywords = array_merge( $this->mKeywords, $text );
272 } else {
273 array_push( $this->mKeywords, $text );
274 }
275 }
276
277 /**
278 * Add a new \<link\> tag to the page header
279 *
280 * @param $linkarr Array: associative array of attributes.
281 */
282 function addLink( $linkarr ) {
283 array_push( $this->mLinktags, $linkarr );
284 }
285
286 /**
287 * Add a new \<link\> with "rel" attribute set to "meta"
288 *
289 * @param $linkarr Array: associative array mapping attribute names to their
290 * values, both keys and values will be escaped, and the
291 * "rel" attribute will be automatically added
292 */
293 function addMetadataLink( $linkarr ) {
294 # note: buggy CC software only reads first "meta" link
295 static $haveMeta = false;
296 $linkarr['rel'] = $haveMeta ? 'alternate meta' : 'meta';
297 $this->addLink( $linkarr );
298 $haveMeta = true;
299 }
300
301 /**
302 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
303 *
304 * @param $script String: raw HTML
305 */
306 function addScript( $script ) {
307 $this->mScripts .= $script . "\n";
308 }
309
310 /**
311 * Register and add a stylesheet from an extension directory.
312 *
313 * @param $url String path to sheet. Provide either a full url (beginning
314 * with 'http', etc) or a relative path from the document root
315 * (beginning with '/'). Otherwise it behaves identically to
316 * addStyle() and draws from the /skins folder.
317 */
318 public function addExtensionStyle( $url ) {
319 array_push( $this->mExtStyles, $url );
320 }
321
322 /**
323 * Get all styles added by extensions
324 *
325 * @return Array
326 */
327 function getExtStyle() {
328 return $this->mExtStyles;
329 }
330
331 /**
332 * Add a JavaScript file out of skins/common, or a given relative path.
333 *
334 * @param $file String: filename in skins/common or complete on-server path
335 * (/foo/bar.js)
336 * @param $version String: style version of the file. Defaults to $wgStyleVersion
337 */
338 public function addScriptFile( $file, $version = null ) {
339 global $wgStylePath, $wgStyleVersion;
340 // See if $file parameter is an absolute URL or begins with a slash
341 if( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
342 $path = $file;
343 } else {
344 $path = "{$wgStylePath}/common/{$file}";
345 }
346 if ( is_null( $version ) )
347 $version = $wgStyleVersion;
348 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
349 }
350
351 /**
352 * Add a self-contained script tag with the given contents
353 *
354 * @param $script String: JavaScript text, no <script> tags
355 */
356 public function addInlineScript( $script ) {
357 $this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
358 }
359
360 /**
361 * Get all registered JS and CSS tags for the header.
362 *
363 * @return String
364 */
365 function getScript() {
366 return $this->mScripts . $this->getHeadItems();
367 }
368
369 /**
370 * Get the list of modules to include on this page
371 *
372 * @return Array of module names
373 */
374 public function getModules() {
375 return array_values( array_unique( $this->mModules ) );
376 }
377
378 /**
379 * Add one or more modules recognized by the resource loader. Modules added
380 * through this function will be loaded by the resource loader when the
381 * page loads.
382 *
383 * @param $modules Mixed: module name (string) or array of module names
384 */
385 public function addModules( $modules ) {
386 $this->mModules = array_merge( $this->mModules, (array)$modules );
387 }
388
389 /**
390 * Get the list of module JS to include on this page
391 * @return array of module names
392 */
393 public function getModuleScripts() {
394 return array_values( array_unique( $this->mModuleScripts ) );
395 }
396
397 /**
398 * Add only JS of one or more modules recognized by the resource loader. Module
399 * scripts added through this function will be loaded by the resource loader when
400 * the page loads.
401 *
402 * @param $modules Mixed: module name (string) or array of module names
403 */
404 public function addModuleScripts( $modules ) {
405 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
406 }
407
408 /**
409 * Get the list of module CSS to include on this page
410 *
411 * @return Array of module names
412 */
413 public function getModuleStyles() {
414 return array_values( array_unique( $this->mModuleStyles ) );
415 }
416
417 /**
418 * Add only CSS of one or more modules recognized by the resource loader. Module
419 * styles added through this function will be loaded by the resource loader when
420 * the page loads.
421 *
422 * @param $modules Mixed: module name (string) or array of module names
423 */
424 public function addModuleStyles( $modules ) {
425 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
426 }
427
428 /**
429 * Get the list of module messages to include on this page
430 *
431 * @return Array of module names
432 */
433 public function getModuleMessages() {
434 return array_values( array_unique( $this->mModuleMessages ) );
435 }
436
437 /**
438 * Add only messages of one or more modules recognized by the resource loader.
439 * Module messages added through this function will be loaded by the resource
440 * loader when the page loads.
441 *
442 * @param $modules Mixed: module name (string) or array of module names
443 */
444 public function addModuleMessages( $modules ) {
445 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
446 }
447
448 /**
449 * Get all header items in a string
450 *
451 * @return String
452 */
453 function getHeadItems() {
454 $s = '';
455 foreach ( $this->mHeadItems as $item ) {
456 $s .= $item;
457 }
458 return $s;
459 }
460
461 /**
462 * Add or replace an header item to the output
463 *
464 * @param $name String: item name
465 * @param $value String: raw HTML
466 */
467 public function addHeadItem( $name, $value ) {
468 $this->mHeadItems[$name] = $value;
469 }
470
471 /**
472 * Check if the header item $name is already set
473 *
474 * @param $name String: item name
475 * @return Boolean
476 */
477 public function hasHeadItem( $name ) {
478 return isset( $this->mHeadItems[$name] );
479 }
480
481 /**
482 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
483 *
484 * @param $tag String: value of "ETag" header
485 */
486 function setETag( $tag ) {
487 $this->mETag = $tag;
488 }
489
490 /**
491 * Set whether the output should only contain the body of the article,
492 * without any skin, sidebar, etc.
493 * Used e.g. when calling with "action=render".
494 *
495 * @param $only Boolean: whether to output only the body of the article
496 */
497 public function setArticleBodyOnly( $only ) {
498 $this->mArticleBodyOnly = $only;
499 }
500
501 /**
502 * Return whether the output will contain only the body of the article
503 *
504 * @return Boolean
505 */
506 public function getArticleBodyOnly() {
507 return $this->mArticleBodyOnly;
508 }
509
510 /**
511 * checkLastModified tells the client to use the client-cached page if
512 * possible. If sucessful, the OutputPage is disabled so that
513 * any future call to OutputPage->output() have no effect.
514 *
515 * Side effect: sets mLastModified for Last-Modified header
516 *
517 * @return Boolean: true iff cache-ok headers was sent.
518 */
519 public function checkLastModified( $timestamp ) {
520 global $wgCachePages, $wgCacheEpoch, $wgUser, $wgRequest;
521
522 if ( !$timestamp || $timestamp == '19700101000000' ) {
523 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
524 return false;
525 }
526 if( !$wgCachePages ) {
527 wfDebug( __METHOD__ . ": CACHE DISABLED\n", false );
528 return false;
529 }
530 if( $wgUser->getOption( 'nocache' ) ) {
531 wfDebug( __METHOD__ . ": USER DISABLED CACHE\n", false );
532 return false;
533 }
534
535 $timestamp = wfTimestamp( TS_MW, $timestamp );
536 $modifiedTimes = array(
537 'page' => $timestamp,
538 'user' => $wgUser->getTouched(),
539 'epoch' => $wgCacheEpoch
540 );
541 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
542
543 $maxModified = max( $modifiedTimes );
544 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
545
546 if( empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {
547 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header\n", false );
548 return false;
549 }
550
551 # Make debug info
552 $info = '';
553 foreach ( $modifiedTimes as $name => $value ) {
554 if ( $info !== '' ) {
555 $info .= ', ';
556 }
557 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
558 }
559
560 # IE sends sizes after the date like this:
561 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
562 # this breaks strtotime().
563 $clientHeader = preg_replace( '/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"] );
564
565 wfSuppressWarnings(); // E_STRICT system time bitching
566 $clientHeaderTime = strtotime( $clientHeader );
567 wfRestoreWarnings();
568 if ( !$clientHeaderTime ) {
569 wfDebug( __METHOD__ . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
570 return false;
571 }
572 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
573
574 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
575 wfTimestamp( TS_ISO_8601, $clientHeaderTime ) . "\n", false );
576 wfDebug( __METHOD__ . ": effective Last-Modified: " .
577 wfTimestamp( TS_ISO_8601, $maxModified ) . "\n", false );
578 if( $clientHeaderTime < $maxModified ) {
579 wfDebug( __METHOD__ . ": STALE, $info\n", false );
580 return false;
581 }
582
583 # Not modified
584 # Give a 304 response code and disable body output
585 wfDebug( __METHOD__ . ": NOT MODIFIED, $info\n", false );
586 ini_set( 'zlib.output_compression', 0 );
587 $wgRequest->response()->header( "HTTP/1.1 304 Not Modified" );
588 $this->sendCacheControl();
589 $this->disable();
590
591 // Don't output a compressed blob when using ob_gzhandler;
592 // it's technically against HTTP spec and seems to confuse
593 // Firefox when the response gets split over two packets.
594 wfClearOutputBuffers();
595
596 return true;
597 }
598
599 /**
600 * Override the last modified timestamp
601 *
602 * @param $timestamp String: new timestamp, in a format readable by
603 * wfTimestamp()
604 */
605 public function setLastModified( $timestamp ) {
606 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
607 }
608
609 /**
610 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
611 *
612 * @param $policy String: the literal string to output as the contents of
613 * the meta tag. Will be parsed according to the spec and output in
614 * standardized form.
615 * @return null
616 */
617 public function setRobotPolicy( $policy ) {
618 $policy = Article::formatRobotPolicy( $policy );
619
620 if( isset( $policy['index'] ) ) {
621 $this->setIndexPolicy( $policy['index'] );
622 }
623 if( isset( $policy['follow'] ) ) {
624 $this->setFollowPolicy( $policy['follow'] );
625 }
626 }
627
628 /**
629 * Set the index policy for the page, but leave the follow policy un-
630 * touched.
631 *
632 * @param $policy string Either 'index' or 'noindex'.
633 * @return null
634 */
635 public function setIndexPolicy( $policy ) {
636 $policy = trim( $policy );
637 if( in_array( $policy, array( 'index', 'noindex' ) ) ) {
638 $this->mIndexPolicy = $policy;
639 }
640 }
641
642 /**
643 * Set the follow policy for the page, but leave the index policy un-
644 * touched.
645 *
646 * @param $policy String: either 'follow' or 'nofollow'.
647 * @return null
648 */
649 public function setFollowPolicy( $policy ) {
650 $policy = trim( $policy );
651 if( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
652 $this->mFollowPolicy = $policy;
653 }
654 }
655
656 /**
657 * Set the new value of the "action text", this will be added to the
658 * "HTML title", separated from it with " - ".
659 *
660 * @param $text String: new value of the "action text"
661 */
662 public function setPageTitleActionText( $text ) {
663 $this->mPageTitleActionText = $text;
664 }
665
666 /**
667 * Get the value of the "action text"
668 *
669 * @return String
670 */
671 public function getPageTitleActionText() {
672 if ( isset( $this->mPageTitleActionText ) ) {
673 return $this->mPageTitleActionText;
674 }
675 }
676
677 /**
678 * "HTML title" means the contents of <title>.
679 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
680 */
681 public function setHTMLTitle( $name ) {
682 $this->mHTMLtitle = $name;
683 }
684
685 /**
686 * Return the "HTML title", i.e. the content of the <title> tag.
687 *
688 * @return String
689 */
690 public function getHTMLTitle() {
691 return $this->mHTMLtitle;
692 }
693
694 /**
695 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML fragment.
696 * This function allows good tags like \<sup\> in the \<h1\> tag, but not bad tags like \<script\>.
697 * This function automatically sets \<title\> to the same content as \<h1\> but with all tags removed.
698 * Bad tags that were escaped in \<h1\> will still be escaped in \<title\>, and good tags like \<i\> will be dropped entirely.
699 */
700 public function setPageTitle( $name ) {
701 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
702 # but leave "<i>foobar</i>" alone
703 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
704 $this->mPagetitle = $nameWithTags;
705
706 # change "<i>foo&amp;bar</i>" to "foo&bar"
707 $this->setHTMLTitle( wfMsg( 'pagetitle', Sanitizer::stripAllTags( $nameWithTags ) ) );
708 }
709
710 /**
711 * Return the "page title", i.e. the content of the \<h1\> tag.
712 *
713 * @return String
714 */
715 public function getPageTitle() {
716 return $this->mPagetitle;
717 }
718
719 /**
720 * Set the Title object to use
721 *
722 * @param $t Title object
723 */
724 public function setTitle( $t ) {
725 $this->mTitle = $t;
726 }
727
728 /**
729 * Get the Title object used in this instance
730 *
731 * @return Title
732 */
733 public function getTitle() {
734 if ( $this->mTitle instanceof Title ) {
735 return $this->mTitle;
736 } else {
737 wfDebug( __METHOD__ . " called and \$mTitle is null. Return \$wgTitle for sanity\n" );
738 global $wgTitle;
739 return $wgTitle;
740 }
741 }
742
743 /**
744 * Replace the subtile with $str
745 *
746 * @param $str String: new value of the subtitle
747 */
748 public function setSubtitle( $str ) {
749 $this->mSubtitle = /*$this->parse(*/ $str /*)*/; // @bug 2514
750 }
751
752 /**
753 * Add $str to the subtitle
754 *
755 * @param $str String to add to the subtitle
756 */
757 public function appendSubtitle( $str ) {
758 $this->mSubtitle .= /*$this->parse(*/ $str /*)*/; // @bug 2514
759 }
760
761 /**
762 * Get the subtitle
763 *
764 * @return String
765 */
766 public function getSubtitle() {
767 return $this->mSubtitle;
768 }
769
770 /**
771 * Set the page as printable, i.e. it'll be displayed with with all
772 * print styles included
773 */
774 public function setPrintable() {
775 $this->mPrintable = true;
776 }
777
778 /**
779 * Return whether the page is "printable"
780 *
781 * @return Boolean
782 */
783 public function isPrintable() {
784 return $this->mPrintable;
785 }
786
787 /**
788 * Disable output completely, i.e. calling output() will have no effect
789 */
790 public function disable() {
791 $this->mDoNothing = true;
792 }
793
794 /**
795 * Return whether the output will be completely disabled
796 *
797 * @return Boolean
798 */
799 public function isDisabled() {
800 return $this->mDoNothing;
801 }
802
803 /**
804 * Show an "add new section" link?
805 *
806 * @return Boolean
807 */
808 public function showNewSectionLink() {
809 return $this->mNewSectionLink;
810 }
811
812 /**
813 * Forcibly hide the new section link?
814 *
815 * @return Boolean
816 */
817 public function forceHideNewSectionLink() {
818 return $this->mHideNewSectionLink;
819 }
820
821 /**
822 * Add or remove feed links in the page header
823 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
824 * for the new version
825 * @see addFeedLink()
826 *
827 * @param $show Boolean: true: add default feeds, false: remove all feeds
828 */
829 public function setSyndicated( $show = true ) {
830 if ( $show ) {
831 $this->setFeedAppendQuery( false );
832 } else {
833 $this->mFeedLinks = array();
834 }
835 }
836
837 /**
838 * Add default feeds to the page header
839 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
840 * for the new version
841 * @see addFeedLink()
842 *
843 * @param $val String: query to append to feed links or false to output
844 * default links
845 */
846 public function setFeedAppendQuery( $val ) {
847 global $wgAdvertisedFeedTypes;
848
849 $this->mFeedLinks = array();
850
851 foreach ( $wgAdvertisedFeedTypes as $type ) {
852 $query = "feed=$type";
853 if ( is_string( $val ) ) {
854 $query .= '&' . $val;
855 }
856 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
857 }
858 }
859
860 /**
861 * Add a feed link to the page header
862 *
863 * @param $format String: feed type, should be a key of $wgFeedClasses
864 * @param $href String: URL
865 */
866 public function addFeedLink( $format, $href ) {
867 global $wgAdvertisedFeedTypes;
868
869 if ( in_array( $format, $wgAdvertisedFeedTypes ) ) {
870 $this->mFeedLinks[$format] = $href;
871 }
872 }
873
874 /**
875 * Should we output feed links for this page?
876 * @return Boolean
877 */
878 public function isSyndicated() {
879 return count( $this->mFeedLinks ) > 0;
880 }
881
882 /**
883 * Return URLs for each supported syndication format for this page.
884 * @return array associating format keys with URLs
885 */
886 public function getSyndicationLinks() {
887 return $this->mFeedLinks;
888 }
889
890 /**
891 * Will currently always return null
892 *
893 * @return null
894 */
895 public function getFeedAppendQuery() {
896 return $this->mFeedLinksAppendQuery;
897 }
898
899 /**
900 * Set whether the displayed content is related to the source of the
901 * corresponding article on the wiki
902 * Setting true will cause the change "article related" toggle to true
903 *
904 * @param $v Boolean
905 */
906 public function setArticleFlag( $v ) {
907 $this->mIsarticle = $v;
908 if ( $v ) {
909 $this->mIsArticleRelated = $v;
910 }
911 }
912
913 /**
914 * Return whether the content displayed page is related to the source of
915 * the corresponding article on the wiki
916 *
917 * @return Boolean
918 */
919 public function isArticle() {
920 return $this->mIsarticle;
921 }
922
923 /**
924 * Set whether this page is related an article on the wiki
925 * Setting false will cause the change of "article flag" toggle to false
926 *
927 * @param $v Boolean
928 */
929 public function setArticleRelated( $v ) {
930 $this->mIsArticleRelated = $v;
931 if ( !$v ) {
932 $this->mIsarticle = false;
933 }
934 }
935
936 /**
937 * Return whether this page is related an article on the wiki
938 *
939 * @return Boolean
940 */
941 public function isArticleRelated() {
942 return $this->mIsArticleRelated;
943 }
944
945 /**
946 * Add new language links
947 *
948 * @param $newLinkArray Associative array mapping language code to the page
949 * name
950 */
951 public function addLanguageLinks( $newLinkArray ) {
952 $this->mLanguageLinks += $newLinkArray;
953 }
954
955 /**
956 * Reset the language links and add new language links
957 *
958 * @param $newLinkArray Associative array mapping language code to the page
959 * name
960 */
961 public function setLanguageLinks( $newLinkArray ) {
962 $this->mLanguageLinks = $newLinkArray;
963 }
964
965 /**
966 * Get the list of language links
967 *
968 * @return Associative array mapping language code to the page name
969 */
970 public function getLanguageLinks() {
971 return $this->mLanguageLinks;
972 }
973
974 /**
975 * Add an array of categories, with names in the keys
976 *
977 * @param $categories Array mapping category name => sort key
978 */
979 public function addCategoryLinks( $categories ) {
980 global $wgUser, $wgContLang;
981
982 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
983 return;
984 }
985
986 # Add the links to a LinkBatch
987 $arr = array( NS_CATEGORY => $categories );
988 $lb = new LinkBatch;
989 $lb->setArray( $arr );
990
991 # Fetch existence plus the hiddencat property
992 $dbr = wfGetDB( DB_SLAVE );
993 $res = $dbr->select( array( 'page', 'page_props' ),
994 array( 'page_id', 'page_namespace', 'page_title', 'page_len', 'page_is_redirect', 'page_latest', 'pp_value' ),
995 $lb->constructSet( 'page', $dbr ),
996 __METHOD__,
997 array(),
998 array( 'page_props' => array( 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' ) ) )
999 );
1000
1001 # Add the results to the link cache
1002 $lb->addResultToCache( LinkCache::singleton(), $res );
1003
1004 # Set all the values to 'normal'. This can be done with array_fill_keys in PHP 5.2.0+
1005 $categories = array_combine(
1006 array_keys( $categories ),
1007 array_fill( 0, count( $categories ), 'normal' )
1008 );
1009
1010 # Mark hidden categories
1011 foreach ( $res as $row ) {
1012 if ( isset( $row->pp_value ) ) {
1013 $categories[$row->page_title] = 'hidden';
1014 }
1015 }
1016
1017 # Add the remaining categories to the skin
1018 if ( wfRunHooks( 'OutputPageMakeCategoryLinks', array( &$this, $categories, &$this->mCategoryLinks ) ) ) {
1019 $sk = $wgUser->getSkin();
1020 foreach ( $categories as $category => $type ) {
1021 $origcategory = $category;
1022 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1023 $wgContLang->findVariantLink( $category, $title, true );
1024 if ( $category != $origcategory ) {
1025 if ( array_key_exists( $category, $categories ) ) {
1026 continue;
1027 }
1028 }
1029 $text = $wgContLang->convertHtml( $title->getText() );
1030 $this->mCategories[] = $title->getText();
1031 $this->mCategoryLinks[$type][] = $sk->link( $title, $text );
1032 }
1033 }
1034 }
1035
1036 /**
1037 * Reset the category links (but not the category list) and add $categories
1038 *
1039 * @param $categories Array mapping category name => sort key
1040 */
1041 public function setCategoryLinks( $categories ) {
1042 $this->mCategoryLinks = array();
1043 $this->addCategoryLinks( $categories );
1044 }
1045
1046 /**
1047 * Get the list of category links, in a 2-D array with the following format:
1048 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1049 * hidden categories) and $link a HTML fragment with a link to the category
1050 * page
1051 *
1052 * @return Array
1053 */
1054 public function getCategoryLinks() {
1055 return $this->mCategoryLinks;
1056 }
1057
1058 /**
1059 * Get the list of category names this page belongs to
1060 *
1061 * @return Array of strings
1062 */
1063 public function getCategories() {
1064 return $this->mCategories;
1065 }
1066
1067 /**
1068 * Remove user JavaScript from scripts to load
1069 */
1070 public function disallowUserJs() {
1071 $this->mAllowUserJs = false;
1072 }
1073
1074 /**
1075 * Return whether user JavaScript is allowed for this page
1076 *
1077 * @return Boolean
1078 */
1079 public function isUserJsAllowed() {
1080 return $this->mAllowUserJs;
1081 }
1082
1083 /**
1084 * Prepend $text to the body HTML
1085 *
1086 * @param $text String: HTML
1087 */
1088 public function prependHTML( $text ) {
1089 $this->mBodytext = $text . $this->mBodytext;
1090 }
1091
1092 /**
1093 * Append $text to the body HTML
1094 *
1095 * @param $text String: HTML
1096 */
1097 public function addHTML( $text ) {
1098 $this->mBodytext .= $text;
1099 }
1100
1101 /**
1102 * Clear the body HTML
1103 */
1104 public function clearHTML() {
1105 $this->mBodytext = '';
1106 }
1107
1108 /**
1109 * Get the body HTML
1110 *
1111 * @return String: HTML
1112 */
1113 public function getHTML() {
1114 return $this->mBodytext;
1115 }
1116
1117 /**
1118 * Add $text to the debug output
1119 *
1120 * @param $text String: debug text
1121 */
1122 public function debug( $text ) {
1123 $this->mDebugtext .= $text;
1124 }
1125
1126 /**
1127 * Get/set the ParserOptions object to use for wikitext parsing
1128 *
1129 * @param $options either the ParserOption to use or null to only get the
1130 * current ParserOption object
1131 * @return current ParserOption object
1132 */
1133 public function parserOptions( $options = null ) {
1134 if ( !$this->mParserOptions ) {
1135 $this->mParserOptions = new ParserOptions;
1136 }
1137 return wfSetVar( $this->mParserOptions, $options );
1138 }
1139
1140 /**
1141 * Set the revision ID which will be seen by the wiki text parser
1142 * for things such as embedded {{REVISIONID}} variable use.
1143 *
1144 * @param $revid Mixed: an positive integer, or null
1145 * @return Mixed: previous value
1146 */
1147 public function setRevisionId( $revid ) {
1148 $val = is_null( $revid ) ? null : intval( $revid );
1149 return wfSetVar( $this->mRevisionId, $val );
1150 }
1151
1152 /**
1153 * Get the current revision ID
1154 *
1155 * @return Integer
1156 */
1157 public function getRevisionId() {
1158 return $this->mRevisionId;
1159 }
1160
1161 /**
1162 * Convert wikitext to HTML and add it to the buffer
1163 * Default assumes that the current page title will be used.
1164 *
1165 * @param $text String
1166 * @param $linestart Boolean: is this the start of a line?
1167 */
1168 public function addWikiText( $text, $linestart = true ) {
1169 $title = $this->getTitle(); // Work arround E_STRICT
1170 $this->addWikiTextTitle( $text, $title, $linestart );
1171 }
1172
1173 /**
1174 * Add wikitext with a custom Title object
1175 *
1176 * @param $text String: wikitext
1177 * @param $title Title object
1178 * @param $linestart Boolean: is this the start of a line?
1179 */
1180 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1181 $this->addWikiTextTitle( $text, $title, $linestart );
1182 }
1183
1184 /**
1185 * Add wikitext with a custom Title object and
1186 *
1187 * @param $text String: wikitext
1188 * @param $title Title object
1189 * @param $linestart Boolean: is this the start of a line?
1190 */
1191 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1192 $this->addWikiTextTitle( $text, $title, $linestart, true );
1193 }
1194
1195 /**
1196 * Add wikitext with tidy enabled
1197 *
1198 * @param $text String: wikitext
1199 * @param $linestart Boolean: is this the start of a line?
1200 */
1201 public function addWikiTextTidy( $text, $linestart = true ) {
1202 $title = $this->getTitle();
1203 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1204 }
1205
1206 /**
1207 * Add wikitext with a custom Title object
1208 *
1209 * @param $text String: wikitext
1210 * @param $title Title object
1211 * @param $linestart Boolean: is this the start of a line?
1212 * @param $tidy Boolean: whether to use tidy
1213 */
1214 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false ) {
1215 global $wgParser;
1216
1217 wfProfileIn( __METHOD__ );
1218
1219 wfIncrStats( 'pcache_not_possible' );
1220
1221 $popts = $this->parserOptions();
1222 $oldTidy = $popts->setTidy( $tidy );
1223
1224 $parserOutput = $wgParser->parse(
1225 $text, $title, $popts,
1226 $linestart, true, $this->mRevisionId
1227 );
1228
1229 $popts->setTidy( $oldTidy );
1230
1231 $this->addParserOutput( $parserOutput );
1232
1233 wfProfileOut( __METHOD__ );
1234 }
1235
1236 /**
1237 * Add a ParserOutput object, but without Html
1238 *
1239 * @param $parserOutput ParserOutput object
1240 */
1241 public function addParserOutputNoText( &$parserOutput ) {
1242 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1243 $this->addCategoryLinks( $parserOutput->getCategories() );
1244 $this->mNewSectionLink = $parserOutput->getNewSection();
1245 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1246
1247 $this->mParseWarnings = $parserOutput->getWarnings();
1248 if ( !$parserOutput->isCacheable() ) {
1249 $this->enableClientCache( false );
1250 }
1251 $this->mNoGallery = $parserOutput->getNoGallery();
1252 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1253 $this->addModules( $parserOutput->getModules() );
1254 // Versioning...
1255 foreach ( (array)$parserOutput->mTemplateIds as $ns => $dbks ) {
1256 if ( isset( $this->mTemplateIds[$ns] ) ) {
1257 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1258 } else {
1259 $this->mTemplateIds[$ns] = $dbks;
1260 }
1261 }
1262
1263 // Hooks registered in the object
1264 global $wgParserOutputHooks;
1265 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1266 list( $hookName, $data ) = $hookInfo;
1267 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1268 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1269 }
1270 }
1271
1272 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1273 }
1274
1275 /**
1276 * Add a ParserOutput object
1277 *
1278 * @param $parserOutput ParserOutput
1279 */
1280 function addParserOutput( &$parserOutput ) {
1281 $this->addParserOutputNoText( $parserOutput );
1282 $text = $parserOutput->getText();
1283 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1284 $this->addHTML( $text );
1285 }
1286
1287
1288 /**
1289 * Add the output of a QuickTemplate to the output buffer
1290 *
1291 * @param $template QuickTemplate
1292 */
1293 public function addTemplate( &$template ) {
1294 ob_start();
1295 $template->execute();
1296 $this->addHTML( ob_get_contents() );
1297 ob_end_clean();
1298 }
1299
1300 /**
1301 * Parse wikitext and return the HTML.
1302 *
1303 * @param $text String
1304 * @param $linestart Boolean: is this the start of a line?
1305 * @param $interface Boolean: use interface language ($wgLang instead of
1306 * $wgContLang) while parsing language sensitive magic
1307 * words like GRAMMAR and PLURAL
1308 * @param $language Language object: target language object, will override
1309 * $interface
1310 * @return String: HTML
1311 */
1312 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1313 // Check one for one common cause for parser state resetting
1314 $callers = wfGetAllCallers( 10 );
1315 if ( strpos( $callers, 'Parser::extensionSubstitution' ) !== false ) {
1316 throw new MWException( "wfMsg* function with parsing cannot be used " .
1317 "inside a tag hook. Should use parser->recursiveTagParse() instead" );
1318 }
1319
1320 global $wgParser;
1321
1322 if( is_null( $this->getTitle() ) ) {
1323 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1324 }
1325
1326 $popts = $this->parserOptions();
1327 if ( $interface ) {
1328 $popts->setInterfaceMessage( true );
1329 }
1330 if ( $language !== null ) {
1331 $oldLang = $popts->setTargetLanguage( $language );
1332 }
1333
1334 $parserOutput = $wgParser->parse(
1335 $text, $this->getTitle(), $popts,
1336 $linestart, true, $this->mRevisionId
1337 );
1338
1339 if ( $interface ) {
1340 $popts->setInterfaceMessage( false );
1341 }
1342 if ( $language !== null ) {
1343 $popts->setTargetLanguage( $oldLang );
1344 }
1345
1346 return $parserOutput->getText();
1347 }
1348
1349 /**
1350 * Parse wikitext, strip paragraphs, and return the HTML.
1351 *
1352 * @param $text String
1353 * @param $linestart Boolean: is this the start of a line?
1354 * @param $interface Boolean: use interface language ($wgLang instead of
1355 * $wgContLang) while parsing language sensitive magic
1356 * words like GRAMMAR and PLURAL
1357 * @return String: HTML
1358 */
1359 public function parseInline( $text, $linestart = true, $interface = false ) {
1360 $parsed = $this->parse( $text, $linestart, $interface );
1361
1362 $m = array();
1363 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1364 $parsed = $m[1];
1365 }
1366
1367 return $parsed;
1368 }
1369
1370 /**
1371 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1372 *
1373 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1374 */
1375 public function setSquidMaxage( $maxage ) {
1376 $this->mSquidMaxage = $maxage;
1377 }
1378
1379 /**
1380 * Use enableClientCache(false) to force it to send nocache headers
1381 *
1382 * @param $state ??
1383 */
1384 public function enableClientCache( $state ) {
1385 return wfSetVar( $this->mEnableClientCache, $state );
1386 }
1387
1388 /**
1389 * Get the list of cookies that will influence on the cache
1390 *
1391 * @return Array
1392 */
1393 function getCacheVaryCookies() {
1394 global $wgCookiePrefix, $wgCacheVaryCookies;
1395 static $cookies;
1396 if ( $cookies === null ) {
1397 $cookies = array_merge(
1398 array(
1399 "{$wgCookiePrefix}Token",
1400 "{$wgCookiePrefix}LoggedOut",
1401 session_name()
1402 ),
1403 $wgCacheVaryCookies
1404 );
1405 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1406 }
1407 return $cookies;
1408 }
1409
1410 /**
1411 * Return whether this page is not cacheable because "useskin" or "uselang"
1412 * URL parameters were passed.
1413 *
1414 * @return Boolean
1415 */
1416 function uncacheableBecauseRequestVars() {
1417 global $wgRequest;
1418 return $wgRequest->getText( 'useskin', false ) === false
1419 && $wgRequest->getText( 'uselang', false ) === false;
1420 }
1421
1422 /**
1423 * Check if the request has a cache-varying cookie header
1424 * If it does, it's very important that we don't allow public caching
1425 *
1426 * @return Boolean
1427 */
1428 function haveCacheVaryCookies() {
1429 global $wgRequest;
1430 $cookieHeader = $wgRequest->getHeader( 'cookie' );
1431 if ( $cookieHeader === false ) {
1432 return false;
1433 }
1434 $cvCookies = $this->getCacheVaryCookies();
1435 foreach ( $cvCookies as $cookieName ) {
1436 # Check for a simple string match, like the way squid does it
1437 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1438 wfDebug( __METHOD__ . ": found $cookieName\n" );
1439 return true;
1440 }
1441 }
1442 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1443 return false;
1444 }
1445
1446 /**
1447 * Add an HTTP header that will influence on the cache
1448 *
1449 * @param $header String: header name
1450 * @param $option Array|null
1451 * @fixme Document the $option parameter; it appears to be for
1452 * X-Vary-Options but what format is acceptable?
1453 */
1454 public function addVaryHeader( $header, $option = null ) {
1455 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1456 $this->mVaryHeader[$header] = (array)$option;
1457 } elseif( is_array( $option ) ) {
1458 if( is_array( $this->mVaryHeader[$header] ) ) {
1459 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1460 } else {
1461 $this->mVaryHeader[$header] = $option;
1462 }
1463 }
1464 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1465 }
1466
1467 /**
1468 * Get a complete X-Vary-Options header
1469 *
1470 * @return String
1471 */
1472 public function getXVO() {
1473 $cvCookies = $this->getCacheVaryCookies();
1474
1475 $cookiesOption = array();
1476 foreach ( $cvCookies as $cookieName ) {
1477 $cookiesOption[] = 'string-contains=' . $cookieName;
1478 }
1479 $this->addVaryHeader( 'Cookie', $cookiesOption );
1480
1481 $headers = array();
1482 foreach( $this->mVaryHeader as $header => $option ) {
1483 $newheader = $header;
1484 if( is_array( $option ) ) {
1485 $newheader .= ';' . implode( ';', $option );
1486 }
1487 $headers[] = $newheader;
1488 }
1489 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1490
1491 return $xvo;
1492 }
1493
1494 /**
1495 * bug 21672: Add Accept-Language to Vary and XVO headers
1496 * if there's no 'variant' parameter existed in GET.
1497 *
1498 * For example:
1499 * /w/index.php?title=Main_page should always be served; but
1500 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1501 */
1502 function addAcceptLanguage() {
1503 global $wgRequest, $wgContLang;
1504 if( !$wgRequest->getCheck( 'variant' ) && $wgContLang->hasVariants() ) {
1505 $variants = $wgContLang->getVariants();
1506 $aloption = array();
1507 foreach ( $variants as $variant ) {
1508 if( $variant === $wgContLang->getCode() ) {
1509 continue;
1510 } else {
1511 $aloption[] = 'string-contains=' . $variant;
1512
1513 // IE and some other browsers use another form of language code
1514 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1515 // We should handle these too.
1516 $ievariant = explode( '-', $variant );
1517 if ( count( $ievariant ) == 2 ) {
1518 $ievariant[1] = strtoupper( $ievariant[1] );
1519 $ievariant = implode( '-', $ievariant );
1520 $aloption[] = 'string-contains=' . $ievariant;
1521 }
1522 }
1523 }
1524 $this->addVaryHeader( 'Accept-Language', $aloption );
1525 }
1526 }
1527
1528 /**
1529 * Set a flag which will cause an X-Frame-Options header appropriate for
1530 * edit pages to be sent. The header value is controlled by
1531 * $wgEditPageFrameOptions.
1532 *
1533 * This is the default for special pages. If you display a CSRF-protected
1534 * form on an ordinary view page, then you need to call this function.
1535 */
1536 public function preventClickjacking( $enable = true ) {
1537 $this->mPreventClickjacking = $enable;
1538 }
1539
1540 /**
1541 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1542 * This can be called from pages which do not contain any CSRF-protected
1543 * HTML form.
1544 */
1545 public function allowClickjacking() {
1546 $this->mPreventClickjacking = false;
1547 }
1548
1549 /**
1550 * Get the X-Frame-Options header value (without the name part), or false
1551 * if there isn't one. This is used by Skin to determine whether to enable
1552 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1553 */
1554 public function getFrameOptions() {
1555 global $wgBreakFrames, $wgEditPageFrameOptions;
1556 if ( $wgBreakFrames ) {
1557 return 'DENY';
1558 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1559 return $wgEditPageFrameOptions;
1560 }
1561 }
1562
1563 /**
1564 * Send cache control HTTP headers
1565 */
1566 public function sendCacheControl() {
1567 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgRequest, $wgUseXVO;
1568
1569 $response = $wgRequest->response();
1570 if ( $wgUseETag && $this->mETag ) {
1571 $response->header( "ETag: $this->mETag" );
1572 }
1573
1574 $this->addAcceptLanguage();
1575
1576 # don't serve compressed data to clients who can't handle it
1577 # maintain different caches for logged-in users and non-logged in ones
1578 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1579
1580 if ( $wgUseXVO ) {
1581 # Add an X-Vary-Options header for Squid with Wikimedia patches
1582 $response->header( $this->getXVO() );
1583 }
1584
1585 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1586 if(
1587 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1588 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1589 )
1590 {
1591 if ( $wgUseESI ) {
1592 # We'll purge the proxy cache explicitly, but require end user agents
1593 # to revalidate against the proxy on each visit.
1594 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1595 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1596 # start with a shorter timeout for initial testing
1597 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1598 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1599 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1600 } else {
1601 # We'll purge the proxy cache for anons explicitly, but require end user agents
1602 # to revalidate against the proxy on each visit.
1603 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1604 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1605 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1606 # start with a shorter timeout for initial testing
1607 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1608 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1609 }
1610 } else {
1611 # We do want clients to cache if they can, but they *must* check for updates
1612 # on revisiting the page.
1613 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1614 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1615 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1616 }
1617 if($this->mLastModified) {
1618 $response->header( "Last-Modified: {$this->mLastModified}" );
1619 }
1620 } else {
1621 wfDebug( __METHOD__ . ": no caching **\n", false );
1622
1623 # In general, the absence of a last modified header should be enough to prevent
1624 # the client from using its cache. We send a few other things just to make sure.
1625 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1626 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1627 $response->header( 'Pragma: no-cache' );
1628 }
1629 }
1630
1631 /**
1632 * Get the message associed with the HTTP response code $code
1633 *
1634 * @param $code Integer: status code
1635 * @return String or null: message or null if $code is not in the list of
1636 * messages
1637 */
1638 public static function getStatusMessage( $code ) {
1639 static $statusMessage = array(
1640 100 => 'Continue',
1641 101 => 'Switching Protocols',
1642 102 => 'Processing',
1643 200 => 'OK',
1644 201 => 'Created',
1645 202 => 'Accepted',
1646 203 => 'Non-Authoritative Information',
1647 204 => 'No Content',
1648 205 => 'Reset Content',
1649 206 => 'Partial Content',
1650 207 => 'Multi-Status',
1651 300 => 'Multiple Choices',
1652 301 => 'Moved Permanently',
1653 302 => 'Found',
1654 303 => 'See Other',
1655 304 => 'Not Modified',
1656 305 => 'Use Proxy',
1657 307 => 'Temporary Redirect',
1658 400 => 'Bad Request',
1659 401 => 'Unauthorized',
1660 402 => 'Payment Required',
1661 403 => 'Forbidden',
1662 404 => 'Not Found',
1663 405 => 'Method Not Allowed',
1664 406 => 'Not Acceptable',
1665 407 => 'Proxy Authentication Required',
1666 408 => 'Request Timeout',
1667 409 => 'Conflict',
1668 410 => 'Gone',
1669 411 => 'Length Required',
1670 412 => 'Precondition Failed',
1671 413 => 'Request Entity Too Large',
1672 414 => 'Request-URI Too Large',
1673 415 => 'Unsupported Media Type',
1674 416 => 'Request Range Not Satisfiable',
1675 417 => 'Expectation Failed',
1676 422 => 'Unprocessable Entity',
1677 423 => 'Locked',
1678 424 => 'Failed Dependency',
1679 500 => 'Internal Server Error',
1680 501 => 'Not Implemented',
1681 502 => 'Bad Gateway',
1682 503 => 'Service Unavailable',
1683 504 => 'Gateway Timeout',
1684 505 => 'HTTP Version Not Supported',
1685 507 => 'Insufficient Storage'
1686 );
1687 return isset( $statusMessage[$code] ) ? $statusMessage[$code] : null;
1688 }
1689
1690 /**
1691 * Finally, all the text has been munged and accumulated into
1692 * the object, let's actually output it:
1693 */
1694 public function output() {
1695 global $wgUser, $wgOutputEncoding, $wgRequest;
1696 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType;
1697 global $wgUseAjax, $wgAjaxWatch;
1698 global $wgEnableMWSuggest, $wgUniversalEditButton;
1699
1700 if( $this->mDoNothing ) {
1701 return;
1702 }
1703 wfProfileIn( __METHOD__ );
1704 if ( $this->mRedirect != '' ) {
1705 # Standards require redirect URLs to be absolute
1706 $this->mRedirect = wfExpandUrl( $this->mRedirect );
1707 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1708 if( !$wgDebugRedirects ) {
1709 $message = self::getStatusMessage( $this->mRedirectCode );
1710 $wgRequest->response()->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1711 }
1712 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1713 }
1714 $this->sendCacheControl();
1715
1716 $wgRequest->response()->header( "Content-Type: text/html; charset=utf-8" );
1717 if( $wgDebugRedirects ) {
1718 $url = htmlspecialchars( $this->mRedirect );
1719 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1720 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1721 print "</body>\n</html>\n";
1722 } else {
1723 $wgRequest->response()->header( 'Location: ' . $this->mRedirect );
1724 }
1725 wfProfileOut( __METHOD__ );
1726 return;
1727 } elseif ( $this->mStatusCode ) {
1728 $message = self::getStatusMessage( $this->mStatusCode );
1729 if ( $message ) {
1730 $wgRequest->response()->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1731 }
1732 }
1733
1734 $sk = $wgUser->getSkin();
1735
1736 // Add base resources
1737 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1738
1739 // Add various resources if required
1740 if ( $wgUseAjax ) {
1741 $this->addModules( 'mediawiki.legacy.ajax' );
1742
1743 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1744
1745 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1746 $this->addModules( 'mediawiki.action.watch.ajax' );
1747 }
1748
1749 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1750 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1751 }
1752 }
1753
1754 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1755 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1756 }
1757
1758 if( $wgUniversalEditButton ) {
1759 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1760 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1761 // Original UniversalEditButton
1762 $msg = wfMsg( 'edit' );
1763 $this->addLink( array(
1764 'rel' => 'alternate',
1765 'type' => 'application/x-wiki',
1766 'title' => $msg,
1767 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1768 ) );
1769 // Alternate edit link
1770 $this->addLink( array(
1771 'rel' => 'edit',
1772 'title' => $msg,
1773 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1774 ) );
1775 }
1776 }
1777
1778
1779 # Buffer output; final headers may depend on later processing
1780 ob_start();
1781
1782 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1783 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1784
1785 // Prevent framing, if requested
1786 $frameOptions = $this->getFrameOptions();
1787 if ( $frameOptions ) {
1788 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1789 }
1790
1791 if ( $this->mArticleBodyOnly ) {
1792 $this->out( $this->mBodytext );
1793 } else {
1794 // Hook that allows last minute changes to the output page, e.g.
1795 // adding of CSS or Javascript by extensions.
1796 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1797
1798 wfProfileIn( 'Output-skin' );
1799 $sk->outputPage( $this );
1800 wfProfileOut( 'Output-skin' );
1801 }
1802
1803 $this->sendCacheControl();
1804 ob_end_flush();
1805 wfProfileOut( __METHOD__ );
1806 }
1807
1808 /**
1809 * Actually output something with print(). Performs an iconv to the
1810 * output encoding, if needed.
1811 *
1812 * @param $ins String: the string to output
1813 */
1814 public function out( $ins ) {
1815 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1816 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1817 $outs = $ins;
1818 } else {
1819 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1820 if ( false === $outs ) {
1821 $outs = $ins;
1822 }
1823 }
1824 print $outs;
1825 }
1826
1827 /**
1828 * Produce a "user is blocked" page.
1829 *
1830 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1831 * @return nothing
1832 */
1833 function blockedPage( $return = true ) {
1834 global $wgUser, $wgContLang, $wgLang;
1835
1836 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1837 $this->setRobotPolicy( 'noindex,nofollow' );
1838 $this->setArticleRelated( false );
1839
1840 $name = User::whoIs( $wgUser->blockedBy() );
1841 $reason = $wgUser->blockedFor();
1842 if( $reason == '' ) {
1843 $reason = wfMsg( 'blockednoreason' );
1844 }
1845 $blockTimestamp = $wgLang->timeanddate(
1846 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1847 );
1848 $ip = wfGetIP();
1849
1850 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1851
1852 $blockid = $wgUser->mBlock->mId;
1853
1854 $blockExpiry = $wgUser->mBlock->mExpiry;
1855 if ( $blockExpiry == 'infinity' ) {
1856 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1857 // Search for localization in 'ipboptions'
1858 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1859 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1860 if ( strpos( $option, ':' ) === false ) {
1861 continue;
1862 }
1863 list( $show, $value ) = explode( ':', $option );
1864 if ( $value == 'infinite' || $value == 'indefinite' ) {
1865 $blockExpiry = $show;
1866 break;
1867 }
1868 }
1869 } else {
1870 $blockExpiry = $wgLang->timeanddate(
1871 wfTimestamp( TS_MW, $blockExpiry ),
1872 true
1873 );
1874 }
1875
1876 if ( $wgUser->mBlock->mAuto ) {
1877 $msg = 'autoblockedtext';
1878 } else {
1879 $msg = 'blockedtext';
1880 }
1881
1882 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1883 * This could be a username, an IP range, or a single IP. */
1884 $intended = $wgUser->mBlock->mAddress;
1885
1886 $this->addWikiMsg(
1887 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1888 $intended, $blockTimestamp
1889 );
1890
1891 # Don't auto-return to special pages
1892 if( $return ) {
1893 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1894 $this->returnToMain( null, $return );
1895 }
1896 }
1897
1898 /**
1899 * Output a standard error page
1900 *
1901 * @param $title String: message key for page title
1902 * @param $msg String: message key for page text
1903 * @param $params Array: message parameters
1904 */
1905 public function showErrorPage( $title, $msg, $params = array() ) {
1906 if ( $this->getTitle() ) {
1907 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1908 }
1909 $this->setPageTitle( wfMsg( $title ) );
1910 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1911 $this->setRobotPolicy( 'noindex,nofollow' );
1912 $this->setArticleRelated( false );
1913 $this->enableClientCache( false );
1914 $this->mRedirect = '';
1915 $this->mBodytext = '';
1916
1917 $this->addWikiMsgArray( $msg, $params );
1918
1919 $this->returnToMain();
1920 }
1921
1922 /**
1923 * Output a standard permission error page
1924 *
1925 * @param $errors Array: error message keys
1926 * @param $action String: action that was denied or null if unknown
1927 */
1928 public function showPermissionsErrorPage( $errors, $action = null ) {
1929 $this->mDebugtext .= 'Original title: ' .
1930 $this->getTitle()->getPrefixedText() . "\n";
1931 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1932 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1933 $this->setRobotPolicy( 'noindex,nofollow' );
1934 $this->setArticleRelated( false );
1935 $this->enableClientCache( false );
1936 $this->mRedirect = '';
1937 $this->mBodytext = '';
1938 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1939 }
1940
1941 /**
1942 * Display an error page indicating that a given version of MediaWiki is
1943 * required to use it
1944 *
1945 * @param $version Mixed: the version of MediaWiki needed to use the page
1946 */
1947 public function versionRequired( $version ) {
1948 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1949 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1950 $this->setRobotPolicy( 'noindex,nofollow' );
1951 $this->setArticleRelated( false );
1952 $this->mBodytext = '';
1953
1954 $this->addWikiMsg( 'versionrequiredtext', $version );
1955 $this->returnToMain();
1956 }
1957
1958 /**
1959 * Display an error page noting that a given permission bit is required.
1960 *
1961 * @param $permission String: key required
1962 */
1963 public function permissionRequired( $permission ) {
1964 global $wgLang;
1965
1966 $this->setPageTitle( wfMsg( 'badaccess' ) );
1967 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1968 $this->setRobotPolicy( 'noindex,nofollow' );
1969 $this->setArticleRelated( false );
1970 $this->mBodytext = '';
1971
1972 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1973 User::getGroupsWithPermission( $permission ) );
1974 if( $groups ) {
1975 $this->addWikiMsg(
1976 'badaccess-groups',
1977 $wgLang->commaList( $groups ),
1978 count( $groups )
1979 );
1980 } else {
1981 $this->addWikiMsg( 'badaccess-group0' );
1982 }
1983 $this->returnToMain();
1984 }
1985
1986 /**
1987 * Produce the stock "please login to use the wiki" page
1988 */
1989 public function loginToUse() {
1990 global $wgUser;
1991
1992 if( $wgUser->isLoggedIn() ) {
1993 $this->permissionRequired( 'read' );
1994 return;
1995 }
1996
1997 $skin = $wgUser->getSkin();
1998
1999 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2000 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2001 $this->setRobotPolicy( 'noindex,nofollow' );
2002 $this->setArticleRelated( false );
2003
2004 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2005 $loginLink = $skin->link(
2006 $loginTitle,
2007 wfMsgHtml( 'loginreqlink' ),
2008 array(),
2009 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2010 array( 'known', 'noclasses' )
2011 );
2012 $this->addHTML( wfMsgWikiHtml( 'loginreqpagetext', $loginLink ) );
2013 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2014
2015 # Don't return to the main page if the user can't read it
2016 # otherwise we'll end up in a pointless loop
2017 $mainPage = Title::newMainPage();
2018 if( $mainPage->userCanRead() ) {
2019 $this->returnToMain( null, $mainPage );
2020 }
2021 }
2022
2023 /**
2024 * Format a list of error messages
2025 *
2026 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2027 * @param $action String: action that was denied or null if unknown
2028 * @return String: the wikitext error-messages, formatted into a list.
2029 */
2030 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2031 if ( $action == null ) {
2032 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2033 } else {
2034 $action_desc = wfMsgNoTrans( "action-$action" );
2035 $text = wfMsgNoTrans(
2036 'permissionserrorstext-withaction',
2037 count( $errors ),
2038 $action_desc
2039 ) . "\n\n";
2040 }
2041
2042 if ( count( $errors ) > 1 ) {
2043 $text .= '<ul class="permissions-errors">' . "\n";
2044
2045 foreach( $errors as $error ) {
2046 $text .= '<li>';
2047 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2048 $text .= "</li>\n";
2049 }
2050 $text .= '</ul>';
2051 } else {
2052 $text .= "<div class=\"permissions-errors\">\n" .
2053 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2054 "\n</div>";
2055 }
2056
2057 return $text;
2058 }
2059
2060 /**
2061 * Display a page stating that the Wiki is in read-only mode,
2062 * and optionally show the source of the page that the user
2063 * was trying to edit. Should only be called (for this
2064 * purpose) after wfReadOnly() has returned true.
2065 *
2066 * For historical reasons, this function is _also_ used to
2067 * show the error message when a user tries to edit a page
2068 * they are not allowed to edit. (Unless it's because they're
2069 * blocked, then we show blockedPage() instead.) In this
2070 * case, the second parameter should be set to true and a list
2071 * of reasons supplied as the third parameter.
2072 *
2073 * @todo Needs to be split into multiple functions.
2074 *
2075 * @param $source String: source code to show (or null).
2076 * @param $protected Boolean: is this a permissions error?
2077 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2078 * @param $action String: action that was denied or null if unknown
2079 */
2080 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2081 global $wgUser;
2082 $skin = $wgUser->getSkin();
2083
2084 $this->setRobotPolicy( 'noindex,nofollow' );
2085 $this->setArticleRelated( false );
2086
2087 // If no reason is given, just supply a default "I can't let you do
2088 // that, Dave" message. Should only occur if called by legacy code.
2089 if ( $protected && empty( $reasons ) ) {
2090 $reasons[] = array( 'badaccess-group0' );
2091 }
2092
2093 if ( !empty( $reasons ) ) {
2094 // Permissions error
2095 if( $source ) {
2096 $this->setPageTitle( wfMsg( 'viewsource' ) );
2097 $this->setSubtitle(
2098 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2099 );
2100 } else {
2101 $this->setPageTitle( wfMsg( 'badaccess' ) );
2102 }
2103 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2104 } else {
2105 // Wiki is read only
2106 $this->setPageTitle( wfMsg( 'readonly' ) );
2107 $reason = wfReadOnlyReason();
2108 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2109 }
2110
2111 // Show source, if supplied
2112 if( is_string( $source ) ) {
2113 $this->addWikiMsg( 'viewsourcetext' );
2114
2115 $params = array(
2116 'id' => 'wpTextbox1',
2117 'name' => 'wpTextbox1',
2118 'cols' => $wgUser->getOption( 'cols' ),
2119 'rows' => $wgUser->getOption( 'rows' ),
2120 'readonly' => 'readonly'
2121 );
2122 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2123
2124 // Show templates used by this article
2125 $skin = $wgUser->getSkin();
2126 $article = new Article( $this->getTitle() );
2127 $this->addHTML( "<div class='templatesUsed'>
2128 {$skin->formatTemplates( $article->getUsedTemplates() )}
2129 </div>
2130 " );
2131 }
2132
2133 # If the title doesn't exist, it's fairly pointless to print a return
2134 # link to it. After all, you just tried editing it and couldn't, so
2135 # what's there to do there?
2136 if( $this->getTitle()->exists() ) {
2137 $this->returnToMain( null, $this->getTitle() );
2138 }
2139 }
2140
2141 /**
2142 * Adds JS-based password security checker
2143 * @param $passwordId String ID of input box containing password
2144 * @param $retypeId String ID of input box containing retyped password
2145 * @return none
2146 */
2147 public function addPasswordSecurity( $passwordId, $retypeId ) {
2148 $data = array(
2149 'password' => '#' . $passwordId,
2150 'retype' => '#' . $retypeId,
2151 'messages' => array(),
2152 );
2153 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2154 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2155 ) as $message ) {
2156 $data['messages'][$message] = wfMsg( $message );
2157 }
2158 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
2159 $this->addModules( 'mediawiki.legacy.password' );
2160 }
2161
2162 public function showFatalError( $message ) {
2163 $this->setPageTitle( wfMsg( 'internalerror' ) );
2164 $this->setRobotPolicy( 'noindex,nofollow' );
2165 $this->setArticleRelated( false );
2166 $this->enableClientCache( false );
2167 $this->mRedirect = '';
2168 $this->mBodytext = $message;
2169 }
2170
2171 public function showUnexpectedValueError( $name, $val ) {
2172 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2173 }
2174
2175 public function showFileCopyError( $old, $new ) {
2176 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2177 }
2178
2179 public function showFileRenameError( $old, $new ) {
2180 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2181 }
2182
2183 public function showFileDeleteError( $name ) {
2184 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2185 }
2186
2187 public function showFileNotFoundError( $name ) {
2188 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2189 }
2190
2191 /**
2192 * Add a "return to" link pointing to a specified title
2193 *
2194 * @param $title Title to link
2195 * @param $query String: query string
2196 * @param $text String text of the link (input is not escaped)
2197 */
2198 public function addReturnTo( $title, $query = array(), $text = null ) {
2199 global $wgUser;
2200 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2201 $link = wfMsgHtml(
2202 'returnto',
2203 $wgUser->getSkin()->link( $title, $text, array(), $query )
2204 );
2205 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2206 }
2207
2208 /**
2209 * Add a "return to" link pointing to a specified title,
2210 * or the title indicated in the request, or else the main page
2211 *
2212 * @param $unused No longer used
2213 * @param $returnto Title or String to return to
2214 * @param $returntoquery String: query string for the return to link
2215 */
2216 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2217 global $wgRequest;
2218
2219 if ( $returnto == null ) {
2220 $returnto = $wgRequest->getText( 'returnto' );
2221 }
2222
2223 if ( $returntoquery == null ) {
2224 $returntoquery = $wgRequest->getText( 'returntoquery' );
2225 }
2226
2227 if ( $returnto === '' ) {
2228 $returnto = Title::newMainPage();
2229 }
2230
2231 if ( is_object( $returnto ) ) {
2232 $titleObj = $returnto;
2233 } else {
2234 $titleObj = Title::newFromText( $returnto );
2235 }
2236 if ( !is_object( $titleObj ) ) {
2237 $titleObj = Title::newMainPage();
2238 }
2239
2240 $this->addReturnTo( $titleObj, $returntoquery );
2241 }
2242
2243 /**
2244 * @param $sk Skin The given Skin
2245 * @param $includeStyle Boolean: unused
2246 * @return String: The doctype, opening <html>, and head element.
2247 */
2248 public function headElement( Skin $sk, $includeStyle = true ) {
2249 global $wgOutputEncoding, $wgMimeType;
2250 global $wgUseTrackbacks, $wgHtml5;
2251 global $wgUser, $wgRequest, $wgLang;
2252
2253 if ( $sk->commonPrintStylesheet() ) {
2254 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2255 }
2256 $sk->setupUserCss( $this );
2257
2258 $ret = Html::htmlHeader( array( 'lang' => wfUILang()->getCode() ) );
2259
2260 if ( $this->getHTMLTitle() == '' ) {
2261 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2262 }
2263
2264 $openHead = Html::openElement( 'head' );
2265 if ( $openHead ) {
2266 # Don't bother with the newline if $head == ''
2267 $ret .= "$openHead\n";
2268 }
2269
2270 if ( $wgHtml5 ) {
2271 # More succinct than <meta http-equiv=Content-Type>, has the
2272 # same effect
2273 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2274 } else {
2275 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2276 }
2277
2278 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2279
2280 $ret .= implode( "\n", array(
2281 $this->getHeadLinks( $sk ),
2282 $this->buildCssLinks( $sk ),
2283 $this->getHeadItems()
2284 ) );
2285
2286 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2287 $ret .= $this->getTitle()->trackbackRDF();
2288 }
2289
2290 $closeHead = Html::closeElement( 'head' );
2291 if ( $closeHead ) {
2292 $ret .= "$closeHead\n";
2293 }
2294
2295 $bodyAttrs = array();
2296
2297 # Crazy edit-on-double-click stuff
2298 $action = $wgRequest->getVal( 'action', 'view' );
2299
2300 if (
2301 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2302 !in_array( $action, array( 'edit', 'submit' ) ) &&
2303 $wgUser->getOption( 'editondblclick' )
2304 )
2305 {
2306 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2307 }
2308
2309 # Class bloat
2310 $dir = wfUILang()->getDir();
2311 $bodyAttrs['class'] = "mediawiki $dir";
2312
2313 if ( $wgLang->capitalizeAllNouns() ) {
2314 # A <body> class is probably not the best way to do this . . .
2315 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2316 }
2317 $bodyAttrs['class'] .= ' ns-' . $this->getTitle()->getNamespace();
2318 if ( $this->getTitle()->getNamespace() == NS_SPECIAL ) {
2319 $bodyAttrs['class'] .= ' ns-special';
2320 } elseif ( $this->getTitle()->isTalkPage() ) {
2321 $bodyAttrs['class'] .= ' ns-talk';
2322 } else {
2323 $bodyAttrs['class'] .= ' ns-subject';
2324 }
2325 $bodyAttrs['class'] .= ' ' . Sanitizer::escapeClass( 'page-' . $this->getTitle()->getPrefixedText() );
2326 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $wgUser->getSkin()->getSkinName() );
2327
2328 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2329 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2330
2331 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2332
2333 return $ret;
2334 }
2335
2336 /**
2337 * Get a ResourceLoader object associated with this OutputPage
2338 */
2339 public function getResourceLoader() {
2340 if ( is_null( $this->mResourceLoader ) ) {
2341 $this->mResourceLoader = new ResourceLoader();
2342 }
2343 return $this->mResourceLoader;
2344 }
2345
2346 /**
2347 * TODO: Document
2348 * @param $skin Skin
2349 * @param $modules Array/string with the module name
2350 * @param $only string May be styles, messages or scripts
2351 * @param $useESI boolean
2352 * @return string html <script> and <style> tags
2353 */
2354 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2355 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2356 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2357 // Lazy-load ResourceLoader
2358 // TODO: Should this be a static function of ResourceLoader instead?
2359 // TODO: Divide off modules starting with "user", and add the user parameter to them
2360 $query = array(
2361 'lang' => $wgLang->getCode(),
2362 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2363 'skin' => $skin->getSkinName(),
2364 'only' => $only,
2365 );
2366 // Propagate printable and handheld parameters if present
2367 if ( $wgRequest->getBool( 'printable' ) ) {
2368 $query['printable'] = 1;
2369 }
2370 if ( $wgRequest->getBool( 'handheld' ) ) {
2371 $query['handheld'] = 1;
2372 }
2373
2374 if ( !count( $modules ) ) {
2375 return '';
2376 }
2377
2378 if ( count( $modules ) > 1 ) {
2379 // Remove duplicate module requests
2380 $modules = array_unique( (array) $modules );
2381 // Sort module names so requests are more uniform
2382 sort( $modules );
2383
2384 if ( ResourceLoader::inDebugMode() ) {
2385 // Recursively call us for every item
2386 $links = '';
2387 foreach ( $modules as $name ) {
2388 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2389 }
2390 return $links;
2391 }
2392 }
2393
2394 // Create keyed-by-group list of module objects from modules list
2395 $groups = array();
2396 $resourceLoader = $this->getResourceLoader();
2397 foreach ( (array) $modules as $name ) {
2398 $module = $resourceLoader->getModule( $name );
2399 $group = $module->getGroup();
2400 if ( !isset( $groups[$group] ) ) {
2401 $groups[$group] = array();
2402 }
2403 $groups[$group][$name] = $module;
2404 }
2405 $links = '';
2406 foreach ( $groups as $group => $modules ) {
2407 $query['modules'] = implode( '|', array_keys( $modules ) );
2408 // Special handling for user-specific groups
2409 if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
2410 $query['user'] = $wgUser->getName();
2411 }
2412 // Support inlining of private modules if configured as such
2413 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2414 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2415 if ( $only == 'styles' ) {
2416 $links .= Html::inlineStyle(
2417 $resourceLoader->makeModuleResponse( $context, $modules )
2418 );
2419 } else {
2420 $links .= Html::inlineScript(
2421 ResourceLoader::makeLoaderConditionalScript(
2422 $resourceLoader->makeModuleResponse( $context, $modules )
2423 )
2424 );
2425 }
2426 continue;
2427 }
2428 // Special handling for user and site groups; because users might change their stuff
2429 // on-wiki like site or user pages, or user preferences; we need to find the highest
2430 // timestamp of these user-changable modules so we can ensure cache misses on change
2431 if ( $group === 'user' || $group === 'site' ) {
2432 // Create a fake request based on the one we are about to make so modules return
2433 // correct times
2434 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2435 // Get the maximum timestamp
2436 $timestamp = 1;
2437 foreach ( $modules as $module ) {
2438 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2439 }
2440 // Add a version parameter so cache will break when things change
2441 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, round( $timestamp, -2 ) );
2442 }
2443 // Make queries uniform in order
2444 ksort( $query );
2445
2446 $url = wfAppendQuery( $wgLoadScript, $query );
2447 if ( $useESI && $wgResourceLoaderUseESI ) {
2448 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2449 if ( $only == 'styles' ) {
2450 $links .= Html::inlineStyle( $esi );
2451 } else {
2452 $links .= Html::inlineScript( $esi );
2453 }
2454 } else {
2455 // Automatically select style/script elements
2456 if ( $only === 'styles' ) {
2457 $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2458 } else {
2459 $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2460 }
2461 }
2462 }
2463 return $links;
2464 }
2465
2466 /**
2467 * Gets the global variables and mScripts; also adds userjs to the end if
2468 * enabled. Despite the name, these scripts are no longer put in the
2469 * <head> but at the bottom of the <body>
2470 *
2471 * @param $sk Skin object to use
2472 * @return String: HTML fragment
2473 */
2474 function getHeadScripts( Skin $sk ) {
2475 global $wgUser, $wgRequest, $wgUseSiteJs;
2476
2477 // Startup - this will immediately load jquery and mediawiki modules
2478 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', 'scripts', true );
2479
2480 // Configuration -- This could be merged together with the load and go, but
2481 // makeGlobalVariablesScript returns a whole script tag -- grumble grumble...
2482 $scripts .= Skin::makeGlobalVariablesScript( $sk->getSkinName() ) . "\n";
2483
2484 // Script and Messages "only" requests
2485 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts(), 'scripts' );
2486 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages(), 'messages' );
2487
2488 // Modules requests - let the client calculate dependencies and batch requests as it likes
2489 if ( $this->getModules() ) {
2490 $scripts .= Html::inlineScript(
2491 ResourceLoader::makeLoaderConditionalScript(
2492 Xml::encodeJsCall( 'mediaWiki.loader.load', array( $this->getModules() ) ) .
2493 Xml::encodeJsCall( 'mediaWiki.loader.go', array() )
2494 )
2495 ) . "\n";
2496 }
2497
2498 // Legacy Scripts
2499 $scripts .= "\n" . $this->mScripts;
2500
2501 // Add site JS if enabled
2502 if ( $wgUseSiteJs ) {
2503 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', 'scripts' );
2504 }
2505
2506 // Add user JS if enabled - trying to load user.options as a bundle if possible
2507 $userOptionsAdded = false;
2508 if ( $this->isUserJsAllowed() && $wgUser->isLoggedIn() ) {
2509 $action = $wgRequest->getVal( 'action', 'view' );
2510 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2511 # XXX: additional security check/prompt?
2512 $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2513 } else {
2514 $scripts .= $this->makeResourceLoaderLink(
2515 $sk, array( 'user', 'user.options' ), 'scripts'
2516 );
2517 $userOptionsAdded = true;
2518 }
2519 }
2520 if ( !$userOptionsAdded ) {
2521 $scripts .= $this->makeResourceLoaderLink( $sk, 'user.options', 'scripts' );
2522 }
2523
2524 return $scripts;
2525 }
2526
2527 /**
2528 * Add default \<meta\> tags
2529 */
2530 protected function addDefaultMeta() {
2531 global $wgVersion, $wgHtml5;
2532
2533 static $called = false;
2534 if ( $called ) {
2535 # Don't run this twice
2536 return;
2537 }
2538 $called = true;
2539
2540 if ( !$wgHtml5 ) {
2541 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2542 }
2543 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2544
2545 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2546 if( $p !== 'index,follow' ) {
2547 // http://www.robotstxt.org/wc/meta-user.html
2548 // Only show if it's different from the default robots policy
2549 $this->addMeta( 'robots', $p );
2550 }
2551
2552 if ( count( $this->mKeywords ) > 0 ) {
2553 $strip = array(
2554 "/<.*?" . ">/" => '',
2555 "/_/" => ' '
2556 );
2557 $this->addMeta(
2558 'keywords',
2559 preg_replace(
2560 array_keys( $strip ),
2561 array_values( $strip ),
2562 implode( ',', $this->mKeywords )
2563 )
2564 );
2565 }
2566 }
2567
2568 /**
2569 * @return string HTML tag links to be put in the header.
2570 */
2571 public function getHeadLinks( Skin $sk ) {
2572 global $wgFeed;
2573
2574 // Ideally this should happen earlier, somewhere. :P
2575 $this->addDefaultMeta();
2576
2577 $tags = array();
2578
2579 foreach ( $this->mMetatags as $tag ) {
2580 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2581 $a = 'http-equiv';
2582 $tag[0] = substr( $tag[0], 5 );
2583 } else {
2584 $a = 'name';
2585 }
2586 $tags[] = Html::element( 'meta',
2587 array(
2588 $a => $tag[0],
2589 'content' => $tag[1]
2590 )
2591 );
2592 }
2593 foreach ( $this->mLinktags as $tag ) {
2594 $tags[] = Html::element( 'link', $tag );
2595 }
2596
2597 if( $wgFeed ) {
2598 foreach( $this->getSyndicationLinks() as $format => $link ) {
2599 # Use the page name for the title (accessed through $wgTitle since
2600 # there's no other way). In principle, this could lead to issues
2601 # with having the same name for different feeds corresponding to
2602 # the same page, but we can't avoid that at this low a level.
2603
2604 $tags[] = $this->feedLink(
2605 $format,
2606 $link,
2607 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2608 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2609 );
2610 }
2611
2612 # Recent changes feed should appear on every page (except recentchanges,
2613 # that would be redundant). Put it after the per-page feed to avoid
2614 # changing existing behavior. It's still available, probably via a
2615 # menu in your browser. Some sites might have a different feed they'd
2616 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2617 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2618 # If so, use it instead.
2619
2620 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2621 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2622
2623 if ( $wgOverrideSiteFeed ) {
2624 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2625 $tags[] = $this->feedLink(
2626 $type,
2627 htmlspecialchars( $feedUrl ),
2628 wfMsg( "site-{$type}-feed", $wgSitename )
2629 );
2630 }
2631 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2632 foreach ( $wgAdvertisedFeedTypes as $format ) {
2633 $tags[] = $this->feedLink(
2634 $format,
2635 $rctitle->getLocalURL( "feed={$format}" ),
2636 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2637 );
2638 }
2639 }
2640 }
2641 return implode( "\n", $tags );
2642 }
2643
2644 /**
2645 * Generate a <link rel/> for a feed.
2646 *
2647 * @param $type String: feed type
2648 * @param $url String: URL to the feed
2649 * @param $text String: value of the "title" attribute
2650 * @return String: HTML fragment
2651 */
2652 private function feedLink( $type, $url, $text ) {
2653 return Html::element( 'link', array(
2654 'rel' => 'alternate',
2655 'type' => "application/$type+xml",
2656 'title' => $text,
2657 'href' => $url )
2658 );
2659 }
2660
2661 /**
2662 * Add a local or specified stylesheet, with the given media options.
2663 * Meant primarily for internal use...
2664 *
2665 * @param $style String: URL to the file
2666 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2667 * @param $condition String: for IE conditional comments, specifying an IE version
2668 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2669 */
2670 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2671 $options = array();
2672 // Even though we expect the media type to be lowercase, but here we
2673 // force it to lowercase to be safe.
2674 if( $media ) {
2675 $options['media'] = $media;
2676 }
2677 if( $condition ) {
2678 $options['condition'] = $condition;
2679 }
2680 if( $dir ) {
2681 $options['dir'] = $dir;
2682 }
2683 $this->styles[$style] = $options;
2684 }
2685
2686 /**
2687 * Adds inline CSS styles
2688 * @param $style_css Mixed: inline CSS
2689 */
2690 public function addInlineStyle( $style_css ){
2691 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2692 }
2693
2694 /**
2695 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2696 * These will be applied to various media & IE conditionals.
2697 * @param $sk Skin object
2698 */
2699 public function buildCssLinks( $sk ) {
2700 $ret = '';
2701 // Add ResourceLoader styles
2702 // Split the styles into three groups
2703 $styles = array( 'other' => array(), 'user' => array(), 'site' => array() );
2704 $resourceLoader = $this->getResourceLoader();
2705 foreach ( $this->getModuleStyles() as $name ) {
2706 $group = $resourceLoader->getModule( $name )->getGroup();
2707 // Modules in groups named "other" or anything different than "user" or "site" will
2708 // be placed in the "other" group
2709 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2710 }
2711
2712 // We want site and user styles to override dynamically added styles from modules, but we want
2713 // dynamically added styles to override statically added styles from other modules. So the order
2714 // has to be other, dynamic, site, user
2715 // Add statically added styles for other modules
2716 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], 'styles' );
2717 // Add normal styles added through addStyle()/addInlineStyle() here
2718 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2719 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2720 // We use a <meta> tag with a made-up name for this because that's valid HTML
2721 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2722 // Add site and user styles
2723 $ret .= $this->makeResourceLoaderLink(
2724 $sk, array_merge( $styles['site'], $styles['user'] ), 'styles'
2725 );
2726 return $ret;
2727 }
2728
2729 public function buildCssLinksArray() {
2730 $links = array();
2731 foreach( $this->styles as $file => $options ) {
2732 $link = $this->styleLink( $file, $options );
2733 if( $link ) {
2734 $links[$file] = $link;
2735 }
2736 }
2737 return $links;
2738 }
2739
2740 /**
2741 * Generate \<link\> tags for stylesheets
2742 *
2743 * @param $style String: URL to the file
2744 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2745 * keys
2746 * @return String: HTML fragment
2747 */
2748 protected function styleLink( $style, $options ) {
2749 if( isset( $options['dir'] ) ) {
2750 $siteDir = wfUILang()->getDir();
2751 if( $siteDir != $options['dir'] ) {
2752 return '';
2753 }
2754 }
2755
2756 if( isset( $options['media'] ) ) {
2757 $media = self::transformCssMedia( $options['media'] );
2758 if( is_null( $media ) ) {
2759 return '';
2760 }
2761 } else {
2762 $media = 'all';
2763 }
2764
2765 if( substr( $style, 0, 1 ) == '/' ||
2766 substr( $style, 0, 5 ) == 'http:' ||
2767 substr( $style, 0, 6 ) == 'https:' ) {
2768 $url = $style;
2769 } else {
2770 global $wgStylePath, $wgStyleVersion;
2771 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2772 }
2773
2774 $link = Html::linkedStyle( $url, $media );
2775
2776 if( isset( $options['condition'] ) ) {
2777 $condition = htmlspecialchars( $options['condition'] );
2778 $link = "<!--[if $condition]>$link<![endif]-->";
2779 }
2780 return $link;
2781 }
2782
2783 /**
2784 * Transform "media" attribute based on request parameters
2785 *
2786 * @param $media String: current value of the "media" attribute
2787 * @return String: modified value of the "media" attribute
2788 */
2789 public static function transformCssMedia( $media ) {
2790 global $wgRequest, $wgHandheldForIPhone;
2791
2792 // Switch in on-screen display for media testing
2793 $switches = array(
2794 'printable' => 'print',
2795 'handheld' => 'handheld',
2796 );
2797 foreach( $switches as $switch => $targetMedia ) {
2798 if( $wgRequest->getBool( $switch ) ) {
2799 if( $media == $targetMedia ) {
2800 $media = '';
2801 } elseif( $media == 'screen' ) {
2802 return null;
2803 }
2804 }
2805 }
2806
2807 // Expand longer media queries as iPhone doesn't grok 'handheld'
2808 if( $wgHandheldForIPhone ) {
2809 $mediaAliases = array(
2810 'screen' => 'screen and (min-device-width: 481px)',
2811 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2812 );
2813
2814 if( isset( $mediaAliases[$media] ) ) {
2815 $media = $mediaAliases[$media];
2816 }
2817 }
2818
2819 return $media;
2820 }
2821
2822 /**
2823 * Turn off regular page output and return an error reponse
2824 * for when rate limiting has triggered.
2825 */
2826 public function rateLimited() {
2827 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2828 $this->setRobotPolicy( 'noindex,follow' );
2829 $this->setArticleRelated( false );
2830 $this->enableClientCache( false );
2831 $this->mRedirect = '';
2832 $this->clearHTML();
2833 $this->setStatusCode( 503 );
2834 $this->addWikiMsg( 'actionthrottledtext' );
2835
2836 $this->returnToMain( null, $this->getTitle() );
2837 }
2838
2839 /**
2840 * Show a warning about slave lag
2841 *
2842 * If the lag is higher than $wgSlaveLagCritical seconds,
2843 * then the warning is a bit more obvious. If the lag is
2844 * lower than $wgSlaveLagWarning, then no warning is shown.
2845 *
2846 * @param $lag Integer: slave lag
2847 */
2848 public function showLagWarning( $lag ) {
2849 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2850 if( $lag >= $wgSlaveLagWarning ) {
2851 $message = $lag < $wgSlaveLagCritical
2852 ? 'lag-warn-normal'
2853 : 'lag-warn-high';
2854 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2855 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2856 }
2857 }
2858
2859 /**
2860 * Add a wikitext-formatted message to the output.
2861 * This is equivalent to:
2862 *
2863 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2864 */
2865 public function addWikiMsg( /*...*/ ) {
2866 $args = func_get_args();
2867 $name = array_shift( $args );
2868 $this->addWikiMsgArray( $name, $args );
2869 }
2870
2871 /**
2872 * Add a wikitext-formatted message to the output.
2873 * Like addWikiMsg() except the parameters are taken as an array
2874 * instead of a variable argument list.
2875 *
2876 * $options is passed through to wfMsgExt(), see that function for details.
2877 */
2878 public function addWikiMsgArray( $name, $args, $options = array() ) {
2879 $options[] = 'parse';
2880 $text = wfMsgExt( $name, $options, $args );
2881 $this->addHTML( $text );
2882 }
2883
2884 /**
2885 * This function takes a number of message/argument specifications, wraps them in
2886 * some overall structure, and then parses the result and adds it to the output.
2887 *
2888 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
2889 * on. The subsequent arguments may either be strings, in which case they are the
2890 * message names, or arrays, in which case the first element is the message name,
2891 * and subsequent elements are the parameters to that message.
2892 *
2893 * The special named parameter 'options' in a message specification array is passed
2894 * through to the $options parameter of wfMsgExt().
2895 *
2896 * Don't use this for messages that are not in users interface language.
2897 *
2898 * For example:
2899 *
2900 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
2901 *
2902 * Is equivalent to:
2903 *
2904 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
2905 *
2906 * The newline after opening div is needed in some wikitext. See bug 19226.
2907 */
2908 public function wrapWikiMsg( $wrap /*, ...*/ ) {
2909 $msgSpecs = func_get_args();
2910 array_shift( $msgSpecs );
2911 $msgSpecs = array_values( $msgSpecs );
2912 $s = $wrap;
2913 foreach ( $msgSpecs as $n => $spec ) {
2914 $options = array();
2915 if ( is_array( $spec ) ) {
2916 $args = $spec;
2917 $name = array_shift( $args );
2918 if ( isset( $args['options'] ) ) {
2919 $options = $args['options'];
2920 unset( $args['options'] );
2921 }
2922 } else {
2923 $args = array();
2924 $name = $spec;
2925 }
2926 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
2927 }
2928 $this->addHTML( $this->parse( $s, /*linestart*/true, /*uilang*/true ) );
2929 }
2930
2931 /**
2932 * Include jQuery core. Use this to avoid loading it multiple times
2933 * before we get a usable script loader.
2934 *
2935 * @param $modules Array: list of jQuery modules which should be loaded
2936 * @return Array: the list of modules which were not loaded.
2937 * @since 1.16
2938 * @deprecated @since 1.17
2939 */
2940 public function includeJQuery( $modules = array() ) {
2941 return array();
2942 }
2943
2944 }