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