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