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