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