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