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