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