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