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