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