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