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