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