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