(bug 27468) Move private styles out to their own section, so they override everything...
[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 current ParserOption 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 $sk = $wgUser->getSkin();
1789
1790 // Add base resources
1791 $this->addModules( array( 'mediawiki.legacy.wikibits', 'mediawiki.util' ) );
1792
1793 // Add various resources if required
1794 if ( $wgUseAjax ) {
1795 $this->addModules( 'mediawiki.legacy.ajax' );
1796
1797 wfRunHooks( 'AjaxAddScript', array( &$this ) );
1798
1799 if( $wgAjaxWatch && $wgUser->isLoggedIn() ) {
1800 $this->addModules( 'mediawiki.action.watch.ajax' );
1801 }
1802
1803 if ( $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
1804 $this->addModules( 'mediawiki.legacy.mwsuggest' );
1805 }
1806 }
1807
1808 if( $wgUser->getBoolOption( 'editsectiononrightclick' ) ) {
1809 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
1810 }
1811
1812 if( $wgUniversalEditButton ) {
1813 if( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
1814 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
1815 // Original UniversalEditButton
1816 $msg = wfMsg( 'edit' );
1817 $this->addLink( array(
1818 'rel' => 'alternate',
1819 'type' => 'application/x-wiki',
1820 'title' => $msg,
1821 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1822 ) );
1823 // Alternate edit link
1824 $this->addLink( array(
1825 'rel' => 'edit',
1826 'title' => $msg,
1827 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
1828 ) );
1829 }
1830 }
1831
1832
1833 # Buffer output; final headers may depend on later processing
1834 ob_start();
1835
1836 $wgRequest->response()->header( "Content-type: $wgMimeType; charset={$wgOutputEncoding}" );
1837 $wgRequest->response()->header( 'Content-language: ' . $wgLanguageCode );
1838
1839 // Prevent framing, if requested
1840 $frameOptions = $this->getFrameOptions();
1841 if ( $frameOptions ) {
1842 $wgRequest->response()->header( "X-Frame-Options: $frameOptions" );
1843 }
1844
1845 if ( $this->mArticleBodyOnly ) {
1846 $this->out( $this->mBodytext );
1847 } else {
1848 // Hook that allows last minute changes to the output page, e.g.
1849 // adding of CSS or Javascript by extensions.
1850 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1851
1852 wfProfileIn( 'Output-skin' );
1853 $sk->outputPage( $this );
1854 wfProfileOut( 'Output-skin' );
1855 }
1856
1857 $this->sendCacheControl();
1858 ob_end_flush();
1859 wfProfileOut( __METHOD__ );
1860 }
1861
1862 /**
1863 * Actually output something with print(). Performs an iconv to the
1864 * output encoding, if needed.
1865 *
1866 * @param $ins String: the string to output
1867 */
1868 public function out( $ins ) {
1869 global $wgInputEncoding, $wgOutputEncoding, $wgContLang;
1870 if ( 0 == strcmp( $wgInputEncoding, $wgOutputEncoding ) ) {
1871 $outs = $ins;
1872 } else {
1873 $outs = $wgContLang->iconv( $wgInputEncoding, $wgOutputEncoding, $ins );
1874 if ( false === $outs ) {
1875 $outs = $ins;
1876 }
1877 }
1878 print $outs;
1879 }
1880
1881 /**
1882 * Produce a "user is blocked" page.
1883 *
1884 * @param $return Boolean: whether to have a "return to $wgTitle" message or not.
1885 * @return nothing
1886 */
1887 function blockedPage( $return = true ) {
1888 global $wgUser, $wgContLang, $wgLang;
1889
1890 $this->setPageTitle( wfMsg( 'blockedtitle' ) );
1891 $this->setRobotPolicy( 'noindex,nofollow' );
1892 $this->setArticleRelated( false );
1893
1894 $name = User::whoIs( $wgUser->blockedBy() );
1895 $reason = $wgUser->blockedFor();
1896 if( $reason == '' ) {
1897 $reason = wfMsg( 'blockednoreason' );
1898 }
1899 $blockTimestamp = $wgLang->timeanddate(
1900 wfTimestamp( TS_MW, $wgUser->mBlock->mTimestamp ), true
1901 );
1902 $ip = wfGetIP();
1903
1904 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1905
1906 $blockid = $wgUser->mBlock->mId;
1907
1908 $blockExpiry = $wgUser->mBlock->mExpiry;
1909 if ( $blockExpiry == 'infinity' ) {
1910 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1911 // Search for localization in 'ipboptions'
1912 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1913 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1914 if ( strpos( $option, ':' ) === false ) {
1915 continue;
1916 }
1917 list( $show, $value ) = explode( ':', $option );
1918 if ( $value == 'infinite' || $value == 'indefinite' ) {
1919 $blockExpiry = $show;
1920 break;
1921 }
1922 }
1923 } else {
1924 $blockExpiry = $wgLang->timeanddate(
1925 wfTimestamp( TS_MW, $blockExpiry ),
1926 true
1927 );
1928 }
1929
1930 if ( $wgUser->mBlock->mAuto ) {
1931 $msg = 'autoblockedtext';
1932 } else {
1933 $msg = 'blockedtext';
1934 }
1935
1936 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1937 * This could be a username, an IP range, or a single IP. */
1938 $intended = $wgUser->mBlock->mAddress;
1939
1940 $this->addWikiMsg(
1941 $msg, $link, $reason, $ip, $name, $blockid, $blockExpiry,
1942 $intended, $blockTimestamp
1943 );
1944
1945 # Don't auto-return to special pages
1946 if( $return ) {
1947 $return = $this->getTitle()->getNamespace() > -1 ? $this->getTitle() : null;
1948 $this->returnToMain( null, $return );
1949 }
1950 }
1951
1952 /**
1953 * Output a standard error page
1954 *
1955 * @param $title String: message key for page title
1956 * @param $msg String: message key for page text
1957 * @param $params Array: message parameters
1958 */
1959 public function showErrorPage( $title, $msg, $params = array() ) {
1960 if ( $this->getTitle() ) {
1961 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1962 }
1963 $this->setPageTitle( wfMsg( $title ) );
1964 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1965 $this->setRobotPolicy( 'noindex,nofollow' );
1966 $this->setArticleRelated( false );
1967 $this->enableClientCache( false );
1968 $this->mRedirect = '';
1969 $this->mBodytext = '';
1970
1971 $this->addWikiMsgArray( $msg, $params );
1972
1973 $this->returnToMain();
1974 }
1975
1976 /**
1977 * Output a standard permission error page
1978 *
1979 * @param $errors Array: error message keys
1980 * @param $action String: action that was denied or null if unknown
1981 */
1982 public function showPermissionsErrorPage( $errors, $action = null ) {
1983 $this->mDebugtext .= 'Original title: ' .
1984 $this->getTitle()->getPrefixedText() . "\n";
1985 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1986 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1987 $this->setRobotPolicy( 'noindex,nofollow' );
1988 $this->setArticleRelated( false );
1989 $this->enableClientCache( false );
1990 $this->mRedirect = '';
1991 $this->mBodytext = '';
1992 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1993 }
1994
1995 /**
1996 * Display an error page indicating that a given version of MediaWiki is
1997 * required to use it
1998 *
1999 * @param $version Mixed: the version of MediaWiki needed to use the page
2000 */
2001 public function versionRequired( $version ) {
2002 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
2003 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
2004 $this->setRobotPolicy( 'noindex,nofollow' );
2005 $this->setArticleRelated( false );
2006 $this->mBodytext = '';
2007
2008 $this->addWikiMsg( 'versionrequiredtext', $version );
2009 $this->returnToMain();
2010 }
2011
2012 /**
2013 * Display an error page noting that a given permission bit is required.
2014 *
2015 * @param $permission String: key required
2016 */
2017 public function permissionRequired( $permission ) {
2018 global $wgLang;
2019
2020 $this->setPageTitle( wfMsg( 'badaccess' ) );
2021 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
2022 $this->setRobotPolicy( 'noindex,nofollow' );
2023 $this->setArticleRelated( false );
2024 $this->mBodytext = '';
2025
2026 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2027 User::getGroupsWithPermission( $permission ) );
2028 if( $groups ) {
2029 $this->addWikiMsg(
2030 'badaccess-groups',
2031 $wgLang->commaList( $groups ),
2032 count( $groups )
2033 );
2034 } else {
2035 $this->addWikiMsg( 'badaccess-group0' );
2036 }
2037 $this->returnToMain();
2038 }
2039
2040 /**
2041 * Produce the stock "please login to use the wiki" page
2042 */
2043 public function loginToUse() {
2044 global $wgUser;
2045
2046 if( $wgUser->isLoggedIn() ) {
2047 $this->permissionRequired( 'read' );
2048 return;
2049 }
2050
2051 $skin = $wgUser->getSkin();
2052
2053 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2054 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2055 $this->setRobotPolicy( 'noindex,nofollow' );
2056 $this->setArticleRelated( false );
2057
2058 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2059 $loginLink = $skin->link(
2060 $loginTitle,
2061 wfMsgHtml( 'loginreqlink' ),
2062 array(),
2063 array( 'returnto' => $this->getTitle()->getPrefixedText() ),
2064 array( 'known', 'noclasses' )
2065 );
2066 $this->addWikiMsgArray( 'loginreqpagetext', array( $loginLink ), array( 'replaceafter' ) );
2067 $this->addHTML( "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2068
2069 # Don't return to the main page if the user can't read it
2070 # otherwise we'll end up in a pointless loop
2071 $mainPage = Title::newMainPage();
2072 if( $mainPage->userCanRead() ) {
2073 $this->returnToMain( null, $mainPage );
2074 }
2075 }
2076
2077 /**
2078 * Format a list of error messages
2079 *
2080 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2081 * @param $action String: action that was denied or null if unknown
2082 * @return String: the wikitext error-messages, formatted into a list.
2083 */
2084 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2085 if ( $action == null ) {
2086 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2087 } else {
2088 $action_desc = wfMsgNoTrans( "action-$action" );
2089 $text = wfMsgNoTrans(
2090 'permissionserrorstext-withaction',
2091 count( $errors ),
2092 $action_desc
2093 ) . "\n\n";
2094 }
2095
2096 if ( count( $errors ) > 1 ) {
2097 $text .= '<ul class="permissions-errors">' . "\n";
2098
2099 foreach( $errors as $error ) {
2100 $text .= '<li>';
2101 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2102 $text .= "</li>\n";
2103 }
2104 $text .= '</ul>';
2105 } else {
2106 $text .= "<div class=\"permissions-errors\">\n" .
2107 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2108 "\n</div>";
2109 }
2110
2111 return $text;
2112 }
2113
2114 /**
2115 * Display a page stating that the Wiki is in read-only mode,
2116 * and optionally show the source of the page that the user
2117 * was trying to edit. Should only be called (for this
2118 * purpose) after wfReadOnly() has returned true.
2119 *
2120 * For historical reasons, this function is _also_ used to
2121 * show the error message when a user tries to edit a page
2122 * they are not allowed to edit. (Unless it's because they're
2123 * blocked, then we show blockedPage() instead.) In this
2124 * case, the second parameter should be set to true and a list
2125 * of reasons supplied as the third parameter.
2126 *
2127 * @todo Needs to be split into multiple functions.
2128 *
2129 * @param $source String: source code to show (or null).
2130 * @param $protected Boolean: is this a permissions error?
2131 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2132 * @param $action String: action that was denied or null if unknown
2133 */
2134 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2135 global $wgUser;
2136 $skin = $wgUser->getSkin();
2137
2138 $this->setRobotPolicy( 'noindex,nofollow' );
2139 $this->setArticleRelated( false );
2140
2141 // If no reason is given, just supply a default "I can't let you do
2142 // that, Dave" message. Should only occur if called by legacy code.
2143 if ( $protected && empty( $reasons ) ) {
2144 $reasons[] = array( 'badaccess-group0' );
2145 }
2146
2147 if ( !empty( $reasons ) ) {
2148 // Permissions error
2149 if( $source ) {
2150 $this->setPageTitle( wfMsg( 'viewsource' ) );
2151 $this->setSubtitle(
2152 wfMsg( 'viewsourcefor', $skin->linkKnown( $this->getTitle() ) )
2153 );
2154 } else {
2155 $this->setPageTitle( wfMsg( 'badaccess' ) );
2156 }
2157 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2158 } else {
2159 // Wiki is read only
2160 $this->setPageTitle( wfMsg( 'readonly' ) );
2161 $reason = wfReadOnlyReason();
2162 $this->wrapWikiMsg( "<div class='mw-readonly-error'>\n$1\n</div>", array( 'readonlytext', $reason ) );
2163 }
2164
2165 // Show source, if supplied
2166 if( is_string( $source ) ) {
2167 $this->addWikiMsg( 'viewsourcetext' );
2168
2169 $params = array(
2170 'id' => 'wpTextbox1',
2171 'name' => 'wpTextbox1',
2172 'cols' => $wgUser->getOption( 'cols' ),
2173 'rows' => $wgUser->getOption( 'rows' ),
2174 'readonly' => 'readonly'
2175 );
2176 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2177
2178 // Show templates used by this article
2179 $skin = $wgUser->getSkin();
2180 $article = new Article( $this->getTitle() );
2181 $this->addHTML( "<div class='templatesUsed'>
2182 {$skin->formatTemplates( $article->getUsedTemplates() )}
2183 </div>
2184 " );
2185 }
2186
2187 # If the title doesn't exist, it's fairly pointless to print a return
2188 # link to it. After all, you just tried editing it and couldn't, so
2189 # what's there to do there?
2190 if( $this->getTitle()->exists() ) {
2191 $this->returnToMain( null, $this->getTitle() );
2192 }
2193 }
2194
2195 /**
2196 * Adds JS-based password security checker
2197 * @param $passwordId String ID of input box containing password
2198 * @param $retypeId String ID of input box containing retyped password
2199 * @return none
2200 */
2201 public function addPasswordSecurity( $passwordId, $retypeId ) {
2202 $data = array(
2203 'password' => '#' . $passwordId,
2204 'retype' => '#' . $retypeId,
2205 'messages' => array(),
2206 );
2207 foreach ( array( 'password-strength', 'password-strength-bad', 'password-strength-mediocre',
2208 'password-strength-acceptable', 'password-strength-good', 'password-retype', 'password-retype-mismatch'
2209 ) as $message ) {
2210 $data['messages'][$message] = wfMsg( $message );
2211 }
2212 $this->addScript( Html::inlineScript( 'var passwordSecurity=' . FormatJson::encode( $data ) ) );
2213 $this->addModules( 'mediawiki.legacy.password' );
2214 }
2215
2216 public function showFatalError( $message ) {
2217 $this->setPageTitle( wfMsg( 'internalerror' ) );
2218 $this->setRobotPolicy( 'noindex,nofollow' );
2219 $this->setArticleRelated( false );
2220 $this->enableClientCache( false );
2221 $this->mRedirect = '';
2222 $this->mBodytext = $message;
2223 }
2224
2225 public function showUnexpectedValueError( $name, $val ) {
2226 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2227 }
2228
2229 public function showFileCopyError( $old, $new ) {
2230 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2231 }
2232
2233 public function showFileRenameError( $old, $new ) {
2234 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2235 }
2236
2237 public function showFileDeleteError( $name ) {
2238 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2239 }
2240
2241 public function showFileNotFoundError( $name ) {
2242 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2243 }
2244
2245 /**
2246 * Add a "return to" link pointing to a specified title
2247 *
2248 * @param $title Title to link
2249 * @param $query String: query string
2250 * @param $text String text of the link (input is not escaped)
2251 */
2252 public function addReturnTo( $title, $query = array(), $text = null ) {
2253 global $wgUser;
2254 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2255 $link = wfMsgHtml(
2256 'returnto',
2257 $wgUser->getSkin()->link( $title, $text, array(), $query )
2258 );
2259 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2260 }
2261
2262 /**
2263 * Add a "return to" link pointing to a specified title,
2264 * or the title indicated in the request, or else the main page
2265 *
2266 * @param $unused No longer used
2267 * @param $returnto Title or String to return to
2268 * @param $returntoquery String: query string for the return to link
2269 */
2270 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2271 global $wgRequest;
2272
2273 if ( $returnto == null ) {
2274 $returnto = $wgRequest->getText( 'returnto' );
2275 }
2276
2277 if ( $returntoquery == null ) {
2278 $returntoquery = $wgRequest->getText( 'returntoquery' );
2279 }
2280
2281 if ( $returnto === '' ) {
2282 $returnto = Title::newMainPage();
2283 }
2284
2285 if ( is_object( $returnto ) ) {
2286 $titleObj = $returnto;
2287 } else {
2288 $titleObj = Title::newFromText( $returnto );
2289 }
2290 if ( !is_object( $titleObj ) ) {
2291 $titleObj = Title::newMainPage();
2292 }
2293
2294 $this->addReturnTo( $titleObj, $returntoquery );
2295 }
2296
2297 /**
2298 * @param $sk Skin The given Skin
2299 * @param $includeStyle Boolean: unused
2300 * @return String: The doctype, opening <html>, and head element.
2301 */
2302 public function headElement( Skin $sk, $includeStyle = true ) {
2303 global $wgOutputEncoding, $wgMimeType;
2304 global $wgUseTrackbacks, $wgHtml5;
2305 global $wgUser, $wgRequest, $wgLang;
2306
2307 if ( $sk->commonPrintStylesheet() ) {
2308 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2309 }
2310 $sk->setupUserCss( $this );
2311
2312 $lang = wfUILang();
2313 $ret = Html::htmlHeader( array( 'lang' => $lang->getCode(), 'dir' => $lang->getDir() ) );
2314
2315 if ( $this->getHTMLTitle() == '' ) {
2316 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2317 }
2318
2319 $openHead = Html::openElement( 'head' );
2320 if ( $openHead ) {
2321 # Don't bother with the newline if $head == ''
2322 $ret .= "$openHead\n";
2323 }
2324
2325 if ( $wgHtml5 ) {
2326 # More succinct than <meta http-equiv=Content-Type>, has the
2327 # same effect
2328 $ret .= Html::element( 'meta', array( 'charset' => $wgOutputEncoding ) ) . "\n";
2329 } else {
2330 $this->addMeta( 'http:Content-Type', "$wgMimeType; charset=$wgOutputEncoding" );
2331 }
2332
2333 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2334
2335 $ret .= implode( "\n", array(
2336 $this->getHeadLinks( $sk ),
2337 $this->buildCssLinks( $sk ),
2338 $this->getHeadItems()
2339 ) );
2340
2341 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2342 $ret .= $this->getTitle()->trackbackRDF();
2343 }
2344
2345 $closeHead = Html::closeElement( 'head' );
2346 if ( $closeHead ) {
2347 $ret .= "$closeHead\n";
2348 }
2349
2350 $bodyAttrs = array();
2351
2352 # Crazy edit-on-double-click stuff
2353 $action = $wgRequest->getVal( 'action', 'view' );
2354
2355 if (
2356 $this->getTitle()->getNamespace() != NS_SPECIAL &&
2357 !in_array( $action, array( 'edit', 'submit' ) ) &&
2358 $wgUser->getOption( 'editondblclick' )
2359 )
2360 {
2361 $bodyAttrs['ondblclick'] = "document.location = '" . Xml::escapeJsString( $this->getTitle()->getEditURL() ) . "'";
2362 }
2363
2364 # Class bloat
2365 $dir = wfUILang()->getDir();
2366 $bodyAttrs['class'] = "mediawiki $dir";
2367
2368 if ( $wgLang->capitalizeAllNouns() ) {
2369 # A <body> class is probably not the best way to do this . . .
2370 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2371 }
2372 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2373 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2374
2375 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2376 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2377
2378 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2379
2380 return $ret;
2381 }
2382
2383 /**
2384 * Get a ResourceLoader object associated with this OutputPage
2385 */
2386 public function getResourceLoader() {
2387 if ( is_null( $this->mResourceLoader ) ) {
2388 $this->mResourceLoader = new ResourceLoader();
2389 }
2390 return $this->mResourceLoader;
2391 }
2392
2393 /**
2394 * TODO: Document
2395 * @param $skin Skin
2396 * @param $modules Array/string with the module name
2397 * @param $only String ResourceLoaderModule TYPE_ class constant
2398 * @param $useESI boolean
2399 * @return string html <script> and <style> tags
2400 */
2401 protected function makeResourceLoaderLink( Skin $skin, $modules, $only, $useESI = false ) {
2402 global $wgUser, $wgLang, $wgLoadScript, $wgResourceLoaderUseESI,
2403 $wgResourceLoaderInlinePrivateModules, $wgRequest;
2404 // Lazy-load ResourceLoader
2405 // TODO: Should this be a static function of ResourceLoader instead?
2406 // TODO: Divide off modules starting with "user", and add the user parameter to them
2407 $baseQuery = array(
2408 'lang' => $wgLang->getCode(),
2409 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
2410 'skin' => $skin->getSkinName(),
2411 'only' => $only,
2412 );
2413 // Propagate printable and handheld parameters if present
2414 if ( $this->isPrintable() ) {
2415 $baseQuery['printable'] = 1;
2416 }
2417 if ( $wgRequest->getBool( 'handheld' ) ) {
2418 $baseQuery['handheld'] = 1;
2419 }
2420
2421 if ( !count( $modules ) ) {
2422 return '';
2423 }
2424
2425 if ( count( $modules ) > 1 ) {
2426 // Remove duplicate module requests
2427 $modules = array_unique( (array) $modules );
2428 // Sort module names so requests are more uniform
2429 sort( $modules );
2430
2431 if ( ResourceLoader::inDebugMode() ) {
2432 // Recursively call us for every item
2433 $links = '';
2434 foreach ( $modules as $name ) {
2435 $links .= $this->makeResourceLoaderLink( $skin, $name, $only, $useESI );
2436 }
2437 return $links;
2438 }
2439 }
2440
2441 // Create keyed-by-group list of module objects from modules list
2442 $groups = array();
2443 $resourceLoader = $this->getResourceLoader();
2444 foreach ( (array) $modules as $name ) {
2445 $module = $resourceLoader->getModule( $name );
2446 # Check that we're allowed to include this module on this page
2447 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2448 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2449 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2450 && $only == ResourceLoaderModule::TYPE_STYLES )
2451 )
2452 {
2453 continue;
2454 }
2455
2456 $group = $module->getGroup();
2457 if ( !isset( $groups[$group] ) ) {
2458 $groups[$group] = array();
2459 }
2460 $groups[$group][$name] = $module;
2461 }
2462
2463 $links = '';
2464 foreach ( $groups as $group => $modules ) {
2465 $query = $baseQuery;
2466 // Special handling for user-specific groups
2467 if ( ( $group === 'user' || $group === 'private' ) && $wgUser->isLoggedIn() ) {
2468 $query['user'] = $wgUser->getName();
2469 }
2470
2471 // Create a fake request based on the one we are about to make so modules return
2472 // correct timestamp and emptiness data
2473 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2474 // Drop modules that know they're empty
2475 foreach ( $modules as $key => $module ) {
2476 if ( $module->isKnownEmpty( $context ) ) {
2477 unset( $modules[$key] );
2478 }
2479 }
2480 // If there are no modules left, skip this group
2481 if ( $modules === array() ) {
2482 continue;
2483 }
2484
2485 $query['modules'] = implode( '|', array_keys( $modules ) );
2486
2487 // Support inlining of private modules if configured as such
2488 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2489 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2490 $links .= Html::inlineStyle(
2491 $resourceLoader->makeModuleResponse( $context, $modules )
2492 );
2493 } else {
2494 $links .= Html::inlineScript(
2495 ResourceLoader::makeLoaderConditionalScript(
2496 $resourceLoader->makeModuleResponse( $context, $modules )
2497 )
2498 );
2499 }
2500 continue;
2501 }
2502 // Special handling for user and site groups; because users might change their stuff
2503 // on-wiki like site or user pages, or user preferences; we need to find the highest
2504 // timestamp of these user-changable modules so we can ensure cache misses on change
2505 if ( $group === 'user' || $group === 'site' ) {
2506 // Get the maximum timestamp
2507 $timestamp = 1;
2508 foreach ( $modules as $module ) {
2509 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2510 }
2511 // Add a version parameter so cache will break when things change
2512 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2513 }
2514 // Make queries uniform in order
2515 ksort( $query );
2516
2517 $url = wfAppendQuery( $wgLoadScript, $query );
2518 if ( $useESI && $wgResourceLoaderUseESI ) {
2519 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2520 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2521 $links .= Html::inlineStyle( $esi );
2522 } else {
2523 $links .= Html::inlineScript( $esi );
2524 }
2525 } else {
2526 // Automatically select style/script elements
2527 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2528 $links .= Html::linkedStyle( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2529 } else {
2530 $links .= Html::linkedScript( wfAppendQuery( $wgLoadScript, $query ) ) . "\n";
2531 }
2532 }
2533 }
2534 return $links;
2535 }
2536
2537 /**
2538 * Gets the global variables and mScripts; also adds userjs to the end if
2539 * enabled. Despite the name, these scripts are no longer put in the
2540 * <head> but at the bottom of the <body>
2541 *
2542 * @param $sk Skin object to use
2543 * @return String: HTML fragment
2544 */
2545 function getHeadScripts( Skin $sk ) {
2546 global $wgUser, $wgRequest, $wgUseSiteJs, $wgAllowUserJs;
2547
2548 // Startup - this will immediately load jquery and mediawiki modules
2549 $scripts = $this->makeResourceLoaderLink( $sk, 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2550
2551 // Script and Messages "only" requests
2552 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleScripts( true ), ResourceLoaderModule::TYPE_SCRIPTS );
2553 $scripts .= $this->makeResourceLoaderLink( $sk, $this->getModuleMessages( true ), ResourceLoaderModule::TYPE_MESSAGES );
2554
2555 // Modules requests - let the client calculate dependencies and batch requests as it likes
2556 $loader = '';
2557 if ( $this->getModules( true ) ) {
2558 $loader = Xml::encodeJsCall( 'mw.loader.load', array( $this->getModules( true ) ) ) .
2559 Xml::encodeJsCall( 'mw.loader.go', array() );
2560 }
2561
2562 $scripts .= Html::inlineScript(
2563 ResourceLoader::makeLoaderConditionalScript(
2564 ResourceLoader::makeConfigSetScript( $this->getJSVars() ) . $loader
2565 )
2566 );
2567
2568 // Legacy Scripts
2569 $scripts .= "\n" . $this->mScripts;
2570
2571 $userScripts = array( 'user.options' );
2572
2573 // Add site JS if enabled
2574 if ( $wgUseSiteJs ) {
2575 $scripts .= $this->makeResourceLoaderLink( $sk, 'site', ResourceLoaderModule::TYPE_SCRIPTS );
2576 if( $wgUser->isLoggedIn() ){
2577 $userScripts[] = 'user.groups';
2578 }
2579 }
2580
2581 // Add user JS if enabled
2582 if ( $wgAllowUserJs && $wgUser->isLoggedIn() ) {
2583 $action = $wgRequest->getVal( 'action', 'view' );
2584 if( $this->mTitle && $this->mTitle->isJsSubpage() && $sk->userCanPreview( $action ) ) {
2585 # XXX: additional security check/prompt?
2586 $scripts .= Html::inlineScript( "\n" . $wgRequest->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2587 } else {
2588 # FIXME: this means that User:Me/Common.js doesn't load when previewing
2589 # User:Me/Vector.js, and vice versa (bug26283)
2590 $userScripts[] = 'user';
2591 }
2592 }
2593 $scripts .= $this->makeResourceLoaderLink( $sk, $userScripts, ResourceLoaderModule::TYPE_SCRIPTS );
2594
2595 return $scripts;
2596 }
2597
2598 /**
2599 * Get an array containing global JS variables
2600 *
2601 * Do not add things here which can be evaluated in
2602 * ResourceLoaderStartupScript - in other words, without state.
2603 * You will only be adding bloat to the page and causing page caches to
2604 * have to be purged on configuration changes.
2605 */
2606 protected function getJSVars() {
2607 global $wgUser, $wgRequest, $wgUseAjax, $wgEnableMWSuggest, $wgContLang;
2608
2609 $title = $this->getTitle();
2610 $ns = $title->getNamespace();
2611 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2612
2613 $vars = array(
2614 'wgCanonicalNamespace' => $nsname,
2615 'wgCanonicalSpecialPageName' => $ns == NS_SPECIAL ?
2616 SpecialPage::resolveAlias( $title->getDBkey() ) : false, # bug 21115
2617 'wgNamespaceNumber' => $title->getNamespace(),
2618 'wgPageName' => $title->getPrefixedDBKey(),
2619 'wgTitle' => $title->getText(),
2620 'wgCurRevisionId' => $title->getLatestRevID(),
2621 'wgArticleId' => $title->getArticleId(),
2622 'wgIsArticle' => $this->isArticle(),
2623 'wgAction' => $wgRequest->getText( 'action', 'view' ),
2624 'wgUserName' => $wgUser->isAnon() ? null : $wgUser->getName(),
2625 'wgUserGroups' => $wgUser->getEffectiveGroups(),
2626 'wgCategories' => $this->getCategories(),
2627 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2628 );
2629 if ( $wgContLang->hasVariants() ) {
2630 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
2631 }
2632 foreach ( $title->getRestrictionTypes() as $type ) {
2633 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2634 }
2635 if ( $wgUseAjax && $wgEnableMWSuggest && !$wgUser->getOption( 'disablesuggest', false ) ) {
2636 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $wgUser );
2637 }
2638
2639 // Allow extensions to add their custom variables to the global JS variables
2640 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars ) );
2641
2642 return $vars;
2643 }
2644
2645 /**
2646 * Add default \<meta\> tags
2647 */
2648 protected function addDefaultMeta() {
2649 global $wgVersion, $wgHtml5;
2650
2651 static $called = false;
2652 if ( $called ) {
2653 # Don't run this twice
2654 return;
2655 }
2656 $called = true;
2657
2658 if ( !$wgHtml5 ) {
2659 $this->addMeta( 'http:Content-Style-Type', 'text/css' ); // bug 15835
2660 }
2661 $this->addMeta( 'generator', "MediaWiki $wgVersion" );
2662
2663 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2664 if( $p !== 'index,follow' ) {
2665 // http://www.robotstxt.org/wc/meta-user.html
2666 // Only show if it's different from the default robots policy
2667 $this->addMeta( 'robots', $p );
2668 }
2669
2670 if ( count( $this->mKeywords ) > 0 ) {
2671 $strip = array(
2672 "/<.*?" . ">/" => '',
2673 "/_/" => ' '
2674 );
2675 $this->addMeta(
2676 'keywords',
2677 preg_replace(
2678 array_keys( $strip ),
2679 array_values( $strip ),
2680 implode( ',', $this->mKeywords )
2681 )
2682 );
2683 }
2684 }
2685
2686 /**
2687 * @return string HTML tag links to be put in the header.
2688 */
2689 public function getHeadLinks( Skin $sk ) {
2690 global $wgFeed;
2691
2692 // Ideally this should happen earlier, somewhere. :P
2693 $this->addDefaultMeta();
2694
2695 $tags = array();
2696
2697 foreach ( $this->mMetatags as $tag ) {
2698 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2699 $a = 'http-equiv';
2700 $tag[0] = substr( $tag[0], 5 );
2701 } else {
2702 $a = 'name';
2703 }
2704 $tags[] = Html::element( 'meta',
2705 array(
2706 $a => $tag[0],
2707 'content' => $tag[1]
2708 )
2709 );
2710 }
2711 foreach ( $this->mLinktags as $tag ) {
2712 $tags[] = Html::element( 'link', $tag );
2713 }
2714
2715 if( $wgFeed ) {
2716 foreach( $this->getSyndicationLinks() as $format => $link ) {
2717 # Use the page name for the title (accessed through $wgTitle since
2718 # there's no other way). In principle, this could lead to issues
2719 # with having the same name for different feeds corresponding to
2720 # the same page, but we can't avoid that at this low a level.
2721
2722 $tags[] = $this->feedLink(
2723 $format,
2724 $link,
2725 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2726 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2727 );
2728 }
2729
2730 # Recent changes feed should appear on every page (except recentchanges,
2731 # that would be redundant). Put it after the per-page feed to avoid
2732 # changing existing behavior. It's still available, probably via a
2733 # menu in your browser. Some sites might have a different feed they'd
2734 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2735 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2736 # If so, use it instead.
2737
2738 global $wgOverrideSiteFeed, $wgSitename, $wgAdvertisedFeedTypes;
2739 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2740
2741 if ( $wgOverrideSiteFeed ) {
2742 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2743 $tags[] = $this->feedLink(
2744 $type,
2745 htmlspecialchars( $feedUrl ),
2746 wfMsg( "site-{$type}-feed", $wgSitename )
2747 );
2748 }
2749 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2750 foreach ( $wgAdvertisedFeedTypes as $format ) {
2751 $tags[] = $this->feedLink(
2752 $format,
2753 $rctitle->getLocalURL( "feed={$format}" ),
2754 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2755 );
2756 }
2757 }
2758 }
2759 return implode( "\n", $tags );
2760 }
2761
2762 /**
2763 * Generate a <link rel/> for a feed.
2764 *
2765 * @param $type String: feed type
2766 * @param $url String: URL to the feed
2767 * @param $text String: value of the "title" attribute
2768 * @return String: HTML fragment
2769 */
2770 private function feedLink( $type, $url, $text ) {
2771 return Html::element( 'link', array(
2772 'rel' => 'alternate',
2773 'type' => "application/$type+xml",
2774 'title' => $text,
2775 'href' => $url )
2776 );
2777 }
2778
2779 /**
2780 * Add a local or specified stylesheet, with the given media options.
2781 * Meant primarily for internal use...
2782 *
2783 * @param $style String: URL to the file
2784 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2785 * @param $condition String: for IE conditional comments, specifying an IE version
2786 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2787 */
2788 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2789 $options = array();
2790 // Even though we expect the media type to be lowercase, but here we
2791 // force it to lowercase to be safe.
2792 if( $media ) {
2793 $options['media'] = $media;
2794 }
2795 if( $condition ) {
2796 $options['condition'] = $condition;
2797 }
2798 if( $dir ) {
2799 $options['dir'] = $dir;
2800 }
2801 $this->styles[$style] = $options;
2802 }
2803
2804 /**
2805 * Adds inline CSS styles
2806 * @param $style_css Mixed: inline CSS
2807 */
2808 public function addInlineStyle( $style_css ){
2809 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2810 }
2811
2812 /**
2813 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2814 * These will be applied to various media & IE conditionals.
2815 * @param $sk Skin object
2816 */
2817 public function buildCssLinks( $sk ) {
2818 $ret = '';
2819 // Add ResourceLoader styles
2820 // Split the styles into four groups
2821 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array() );
2822 $resourceLoader = $this->getResourceLoader();
2823 foreach ( $this->getModuleStyles() as $name ) {
2824 $group = $resourceLoader->getModule( $name )->getGroup();
2825 // Modules in groups named "other" or anything different than "user", "site" or "private"
2826 // will be placed in the "other" group
2827 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
2828 }
2829
2830 // We want site, private and user styles to override dynamically added styles from modules, but we want
2831 // dynamically added styles to override statically added styles from other modules. So the order
2832 // has to be other, dynamic, site, private, user
2833 // Add statically added styles for other modules
2834 $ret .= $this->makeResourceLoaderLink( $sk, $styles['other'], ResourceLoaderModule::TYPE_STYLES );
2835 // Add normal styles added through addStyle()/addInlineStyle() here
2836 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
2837 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
2838 // We use a <meta> tag with a made-up name for this because that's valid HTML
2839 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) );
2840
2841 // Add site, private and user styles
2842 // 'private' at present only contains user.options, so put that before 'user'
2843 // Any future private modules will likely have a similar user-specific character
2844 foreach ( array( 'site', 'private', 'user' ) as $group ) {
2845 $ret .= $this->makeResourceLoaderLink( $sk, $styles[$group],
2846 ResourceLoaderModule::TYPE_STYLES
2847 );
2848 }
2849 return $ret;
2850 }
2851
2852 public function buildCssLinksArray() {
2853 $links = array();
2854 foreach( $this->styles as $file => $options ) {
2855 $link = $this->styleLink( $file, $options );
2856 if( $link ) {
2857 $links[$file] = $link;
2858 }
2859 }
2860 return $links;
2861 }
2862
2863 /**
2864 * Generate \<link\> tags for stylesheets
2865 *
2866 * @param $style String: URL to the file
2867 * @param $options Array: option, can contain 'condition', 'dir', 'media'
2868 * keys
2869 * @return String: HTML fragment
2870 */
2871 protected function styleLink( $style, $options ) {
2872 if( isset( $options['dir'] ) ) {
2873 $siteDir = wfUILang()->getDir();
2874 if( $siteDir != $options['dir'] ) {
2875 return '';
2876 }
2877 }
2878
2879 if( isset( $options['media'] ) ) {
2880 $media = self::transformCssMedia( $options['media'] );
2881 if( is_null( $media ) ) {
2882 return '';
2883 }
2884 } else {
2885 $media = 'all';
2886 }
2887
2888 if( substr( $style, 0, 1 ) == '/' ||
2889 substr( $style, 0, 5 ) == 'http:' ||
2890 substr( $style, 0, 6 ) == 'https:' ) {
2891 $url = $style;
2892 } else {
2893 global $wgStylePath, $wgStyleVersion;
2894 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
2895 }
2896
2897 $link = Html::linkedStyle( $url, $media );
2898
2899 if( isset( $options['condition'] ) ) {
2900 $condition = htmlspecialchars( $options['condition'] );
2901 $link = "<!--[if $condition]>$link<![endif]-->";
2902 }
2903 return $link;
2904 }
2905
2906 /**
2907 * Transform "media" attribute based on request parameters
2908 *
2909 * @param $media String: current value of the "media" attribute
2910 * @return String: modified value of the "media" attribute
2911 */
2912 public static function transformCssMedia( $media ) {
2913 global $wgRequest, $wgHandheldForIPhone;
2914
2915 // Switch in on-screen display for media testing
2916 $switches = array(
2917 'printable' => 'print',
2918 'handheld' => 'handheld',
2919 );
2920 foreach( $switches as $switch => $targetMedia ) {
2921 if( $wgRequest->getBool( $switch ) ) {
2922 if( $media == $targetMedia ) {
2923 $media = '';
2924 } elseif( $media == 'screen' ) {
2925 return null;
2926 }
2927 }
2928 }
2929
2930 // Expand longer media queries as iPhone doesn't grok 'handheld'
2931 if( $wgHandheldForIPhone ) {
2932 $mediaAliases = array(
2933 'screen' => 'screen and (min-device-width: 481px)',
2934 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
2935 );
2936
2937 if( isset( $mediaAliases[$media] ) ) {
2938 $media = $mediaAliases[$media];
2939 }
2940 }
2941
2942 return $media;
2943 }
2944
2945 /**
2946 * Turn off regular page output and return an error reponse
2947 * for when rate limiting has triggered.
2948 */
2949 public function rateLimited() {
2950 $this->setPageTitle( wfMsg( 'actionthrottled' ) );
2951 $this->setRobotPolicy( 'noindex,follow' );
2952 $this->setArticleRelated( false );
2953 $this->enableClientCache( false );
2954 $this->mRedirect = '';
2955 $this->clearHTML();
2956 $this->setStatusCode( 503 );
2957 $this->addWikiMsg( 'actionthrottledtext' );
2958
2959 $this->returnToMain( null, $this->getTitle() );
2960 }
2961
2962 /**
2963 * Show a warning about slave lag
2964 *
2965 * If the lag is higher than $wgSlaveLagCritical seconds,
2966 * then the warning is a bit more obvious. If the lag is
2967 * lower than $wgSlaveLagWarning, then no warning is shown.
2968 *
2969 * @param $lag Integer: slave lag
2970 */
2971 public function showLagWarning( $lag ) {
2972 global $wgSlaveLagWarning, $wgSlaveLagCritical, $wgLang;
2973 if( $lag >= $wgSlaveLagWarning ) {
2974 $message = $lag < $wgSlaveLagCritical
2975 ? 'lag-warn-normal'
2976 : 'lag-warn-high';
2977 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2978 $this->wrapWikiMsg( "$wrap\n", array( $message, $wgLang->formatNum( $lag ) ) );
2979 }
2980 }
2981
2982 /**
2983 * Add a wikitext-formatted message to the output.
2984 * This is equivalent to:
2985 *
2986 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
2987 */
2988 public function addWikiMsg( /*...*/ ) {
2989 $args = func_get_args();
2990 $name = array_shift( $args );
2991 $this->addWikiMsgArray( $name, $args );
2992 }
2993
2994 /**
2995 * Add a wikitext-formatted message to the output.
2996 * Like addWikiMsg() except the parameters are taken as an array
2997 * instead of a variable argument list.
2998 *
2999 * $options is passed through to wfMsgExt(), see that function for details.
3000 */
3001 public function addWikiMsgArray( $name, $args, $options = array() ) {
3002 $options[] = 'parse';
3003 $text = wfMsgExt( $name, $options, $args );
3004 $this->addHTML( $text );
3005 }
3006
3007 /**
3008 * This function takes a number of message/argument specifications, wraps them in
3009 * some overall structure, and then parses the result and adds it to the output.
3010 *
3011 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3012 * on. The subsequent arguments may either be strings, in which case they are the
3013 * message names, or arrays, in which case the first element is the message name,
3014 * and subsequent elements are the parameters to that message.
3015 *
3016 * The special named parameter 'options' in a message specification array is passed
3017 * through to the $options parameter of wfMsgExt().
3018 *
3019 * Don't use this for messages that are not in users interface language.
3020 *
3021 * For example:
3022 *
3023 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3024 *
3025 * Is equivalent to:
3026 *
3027 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3028 *
3029 * The newline after opening div is needed in some wikitext. See bug 19226.
3030 */
3031 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3032 $msgSpecs = func_get_args();
3033 array_shift( $msgSpecs );
3034 $msgSpecs = array_values( $msgSpecs );
3035 $s = $wrap;
3036 foreach ( $msgSpecs as $n => $spec ) {
3037 $options = array();
3038 if ( is_array( $spec ) ) {
3039 $args = $spec;
3040 $name = array_shift( $args );
3041 if ( isset( $args['options'] ) ) {
3042 $options = $args['options'];
3043 unset( $args['options'] );
3044 }
3045 } else {
3046 $args = array();
3047 $name = $spec;
3048 }
3049 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3050 }
3051 $this->addWikiText( $s );
3052 }
3053
3054 /**
3055 * Include jQuery core. Use this to avoid loading it multiple times
3056 * before we get a usable script loader.
3057 *
3058 * @param $modules Array: list of jQuery modules which should be loaded
3059 * @return Array: the list of modules which were not loaded.
3060 * @since 1.16
3061 * @deprecated @since 1.17
3062 */
3063 public function includeJQuery( $modules = array() ) {
3064 return array();
3065 }
3066
3067 }