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