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