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