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