Fix comment in r98374
[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, $wgVaryOnXFP;
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 if ( $wgVaryOnXFP ) {
1830 $this->addVaryHeader( 'X-Forwarded-Proto' );
1831 }
1832 $this->sendCacheControl();
1833
1834 $response->header( "Content-Type: text/html; charset=utf-8" );
1835 if( $wgDebugRedirects ) {
1836 $url = htmlspecialchars( $this->mRedirect );
1837 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1838 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1839 print "</body>\n</html>\n";
1840 } else {
1841 $response->header( 'Location: ' . $this->mRedirect );
1842 }
1843 wfProfileOut( __METHOD__ );
1844 return;
1845 } elseif ( $this->mStatusCode ) {
1846 $message = HttpStatus::getMessage( $this->mStatusCode );
1847 if ( $message ) {
1848 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1849 }
1850 }
1851
1852 # Buffer output; final headers may depend on later processing
1853 ob_start();
1854
1855 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1856 $response->header( 'Content-language: ' . $wgLanguageCode );
1857
1858 // Prevent framing, if requested
1859 $frameOptions = $this->getFrameOptions();
1860 if ( $frameOptions ) {
1861 $response->header( "X-Frame-Options: $frameOptions" );
1862 }
1863
1864 if ( $this->mArticleBodyOnly ) {
1865 $this->out( $this->mBodytext );
1866 } else {
1867 $this->addDefaultModules();
1868
1869 $sk = $this->getSkin();
1870
1871 // Hook that allows last minute changes to the output page, e.g.
1872 // adding of CSS or Javascript by extensions.
1873 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1874
1875 wfProfileIn( 'Output-skin' );
1876 $sk->outputPage();
1877 wfProfileOut( 'Output-skin' );
1878 }
1879
1880 $this->sendCacheControl();
1881 ob_end_flush();
1882 wfProfileOut( __METHOD__ );
1883 }
1884
1885 /**
1886 * Actually output something with print().
1887 *
1888 * @param $ins String: the string to output
1889 */
1890 public function out( $ins ) {
1891 print $ins;
1892 }
1893
1894 /**
1895 * Produce a "user is blocked" page.
1896 * @deprecated since 1.18
1897 */
1898 function blockedPage() {
1899 throw new UserBlockedError( $this->getUser()->mBlock );
1900 }
1901
1902 /**
1903 * Output a standard error page
1904 *
1905 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1906 * showErrorPage( 'titlemsg', $messageObject );
1907 *
1908 * @param $title String: message key for page title
1909 * @param $msg Mixed: message key (string) for page text, or a Message object
1910 * @param $params Array: message parameters; ignored if $msg is a Message object
1911 */
1912 public function showErrorPage( $title, $msg, $params = array() ) {
1913 if ( $this->getTitle() ) {
1914 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1915 }
1916 $this->setPageTitle( wfMsg( $title ) );
1917 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1918 $this->setRobotPolicy( 'noindex,nofollow' );
1919 $this->setArticleRelated( false );
1920 $this->enableClientCache( false );
1921 $this->mRedirect = '';
1922 $this->mBodytext = '';
1923
1924 if ( $msg instanceof Message ){
1925 $this->addHTML( $msg->parse() );
1926 } else {
1927 $this->addWikiMsgArray( $msg, $params );
1928 }
1929
1930 $this->returnToMain();
1931 }
1932
1933 /**
1934 * Output a standard permission error page
1935 *
1936 * @param $errors Array: error message keys
1937 * @param $action String: action that was denied or null if unknown
1938 */
1939 public function showPermissionsErrorPage( $errors, $action = null ) {
1940 $this->mDebugtext .= 'Original title: ' .
1941 $this->getTitle()->getPrefixedText() . "\n";
1942 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1943 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1944 $this->setRobotPolicy( 'noindex,nofollow' );
1945 $this->setArticleRelated( false );
1946 $this->enableClientCache( false );
1947 $this->mRedirect = '';
1948 $this->mBodytext = '';
1949 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1950 }
1951
1952 /**
1953 * Display an error page indicating that a given version of MediaWiki is
1954 * required to use it
1955 *
1956 * @param $version Mixed: the version of MediaWiki needed to use the page
1957 */
1958 public function versionRequired( $version ) {
1959 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1960 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1961 $this->setRobotPolicy( 'noindex,nofollow' );
1962 $this->setArticleRelated( false );
1963 $this->mBodytext = '';
1964
1965 $this->addWikiMsg( 'versionrequiredtext', $version );
1966 $this->returnToMain();
1967 }
1968
1969 /**
1970 * Display an error page noting that a given permission bit is required.
1971 * @deprecated since 1.18, just throw the exception directly
1972 * @param $permission String: key required
1973 */
1974 public function permissionRequired( $permission ) {
1975 throw new PermissionsError( $permission );
1976 }
1977
1978 /**
1979 * Produce the stock "please login to use the wiki" page
1980 */
1981 public function loginToUse() {
1982 if( $this->getUser()->isLoggedIn() ) {
1983 throw new PermissionsError( 'read' );
1984 }
1985
1986 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
1987 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
1988 $this->setRobotPolicy( 'noindex,nofollow' );
1989 $this->setArticleRelated( false );
1990
1991 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1992 $loginLink = Linker::linkKnown(
1993 $loginTitle,
1994 wfMsgHtml( 'loginreqlink' ),
1995 array(),
1996 array( 'returnto' => $this->getTitle()->getPrefixedText() )
1997 );
1998 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
1999 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2000
2001 # Don't return to the main page if the user can't read it
2002 # otherwise we'll end up in a pointless loop
2003 $mainPage = Title::newMainPage();
2004 if( $mainPage->userCanRead() ) {
2005 $this->returnToMain( null, $mainPage );
2006 }
2007 }
2008
2009 /**
2010 * Format a list of error messages
2011 *
2012 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2013 * @param $action String: action that was denied or null if unknown
2014 * @return String: the wikitext error-messages, formatted into a list.
2015 */
2016 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2017 if ( $action == null ) {
2018 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2019 } else {
2020 $action_desc = wfMsgNoTrans( "action-$action" );
2021 $text = wfMsgNoTrans(
2022 'permissionserrorstext-withaction',
2023 count( $errors ),
2024 $action_desc
2025 ) . "\n\n";
2026 }
2027
2028 if ( count( $errors ) > 1 ) {
2029 $text .= '<ul class="permissions-errors">' . "\n";
2030
2031 foreach( $errors as $error ) {
2032 $text .= '<li>';
2033 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2034 $text .= "</li>\n";
2035 }
2036 $text .= '</ul>';
2037 } else {
2038 $text .= "<div class=\"permissions-errors\">\n" .
2039 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2040 "\n</div>";
2041 }
2042
2043 return $text;
2044 }
2045
2046 /**
2047 * Display a page stating that the Wiki is in read-only mode,
2048 * and optionally show the source of the page that the user
2049 * was trying to edit. Should only be called (for this
2050 * purpose) after wfReadOnly() has returned true.
2051 *
2052 * For historical reasons, this function is _also_ used to
2053 * show the error message when a user tries to edit a page
2054 * they are not allowed to edit. (Unless it's because they're
2055 * blocked, then we show blockedPage() instead.) In this
2056 * case, the second parameter should be set to true and a list
2057 * of reasons supplied as the third parameter.
2058 *
2059 * @todo Needs to be split into multiple functions.
2060 *
2061 * @param $source String: source code to show (or null).
2062 * @param $protected Boolean: is this a permissions error?
2063 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2064 * @param $action String: action that was denied or null if unknown
2065 */
2066 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2067 $this->setRobotPolicy( 'noindex,nofollow' );
2068 $this->setArticleRelated( false );
2069
2070 // If no reason is given, just supply a default "I can't let you do
2071 // that, Dave" message. Should only occur if called by legacy code.
2072 if ( $protected && empty( $reasons ) ) {
2073 $reasons[] = array( 'badaccess-group0' );
2074 }
2075
2076 if ( !empty( $reasons ) ) {
2077 // Permissions error
2078 if( $source ) {
2079 $this->setPageTitle( wfMsg( 'viewsource' ) );
2080 $this->setSubtitle(
2081 wfMsg( 'viewsourcefor', Linker::linkKnown( $this->getTitle() ) )
2082 );
2083 } else {
2084 $this->setPageTitle( wfMsg( 'badaccess' ) );
2085 }
2086 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2087 } else {
2088 // Wiki is read only
2089 throw new ReadOnlyError;
2090 }
2091
2092 // Show source, if supplied
2093 if( is_string( $source ) ) {
2094 $this->addWikiMsg( 'viewsourcetext' );
2095
2096 $pageLang = $this->getTitle()->getPageLanguage();
2097 $params = array(
2098 'id' => 'wpTextbox1',
2099 'name' => 'wpTextbox1',
2100 'cols' => $this->getUser()->getOption( 'cols' ),
2101 'rows' => $this->getUser()->getOption( 'rows' ),
2102 'readonly' => 'readonly',
2103 'lang' => $pageLang->getCode(),
2104 'dir' => $pageLang->getDir(),
2105 );
2106 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2107
2108 // Show templates used by this article
2109 $article = new Article( $this->getTitle() );
2110 $templates = Linker::formatTemplates( $article->getUsedTemplates() );
2111 $this->addHTML( "<div class='templatesUsed'>
2112 $templates
2113 </div>
2114 " );
2115 }
2116
2117 # If the title doesn't exist, it's fairly pointless to print a return
2118 # link to it. After all, you just tried editing it and couldn't, so
2119 # what's there to do there?
2120 if( $this->getTitle()->exists() ) {
2121 $this->returnToMain( null, $this->getTitle() );
2122 }
2123 }
2124
2125 /**
2126 * Turn off regular page output and return an error reponse
2127 * for when rate limiting has triggered.
2128 */
2129 public function rateLimited() {
2130 throw new ThrottledError;
2131 }
2132
2133 /**
2134 * Show a warning about slave lag
2135 *
2136 * If the lag is higher than $wgSlaveLagCritical seconds,
2137 * then the warning is a bit more obvious. If the lag is
2138 * lower than $wgSlaveLagWarning, then no warning is shown.
2139 *
2140 * @param $lag Integer: slave lag
2141 */
2142 public function showLagWarning( $lag ) {
2143 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2144 if( $lag >= $wgSlaveLagWarning ) {
2145 $message = $lag < $wgSlaveLagCritical
2146 ? 'lag-warn-normal'
2147 : 'lag-warn-high';
2148 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2149 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2150 }
2151 }
2152
2153 public function showFatalError( $message ) {
2154 $this->setPageTitle( wfMsg( 'internalerror' ) );
2155 $this->setRobotPolicy( 'noindex,nofollow' );
2156 $this->setArticleRelated( false );
2157 $this->enableClientCache( false );
2158 $this->mRedirect = '';
2159 $this->mBodytext = $message;
2160 }
2161
2162 public function showUnexpectedValueError( $name, $val ) {
2163 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2164 }
2165
2166 public function showFileCopyError( $old, $new ) {
2167 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2168 }
2169
2170 public function showFileRenameError( $old, $new ) {
2171 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2172 }
2173
2174 public function showFileDeleteError( $name ) {
2175 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2176 }
2177
2178 public function showFileNotFoundError( $name ) {
2179 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2180 }
2181
2182 /**
2183 * Add a "return to" link pointing to a specified title
2184 *
2185 * @param $title Title to link
2186 * @param $query String query string
2187 * @param $text String text of the link (input is not escaped)
2188 */
2189 public function addReturnTo( $title, $query = array(), $text = null ) {
2190 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2191 $link = wfMsgHtml(
2192 'returnto',
2193 Linker::link( $title, $text, array(), $query )
2194 );
2195 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2196 }
2197
2198 /**
2199 * Add a "return to" link pointing to a specified title,
2200 * or the title indicated in the request, or else the main page
2201 *
2202 * @param $unused No longer used
2203 * @param $returnto Title or String to return to
2204 * @param $returntoquery String: query string for the return to link
2205 */
2206 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2207 if ( $returnto == null ) {
2208 $returnto = $this->getRequest()->getText( 'returnto' );
2209 }
2210
2211 if ( $returntoquery == null ) {
2212 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2213 }
2214
2215 if ( $returnto === '' ) {
2216 $returnto = Title::newMainPage();
2217 }
2218
2219 if ( is_object( $returnto ) ) {
2220 $titleObj = $returnto;
2221 } else {
2222 $titleObj = Title::newFromText( $returnto );
2223 }
2224 if ( !is_object( $titleObj ) ) {
2225 $titleObj = Title::newMainPage();
2226 }
2227
2228 $this->addReturnTo( $titleObj, $returntoquery );
2229 }
2230
2231 /**
2232 * @param $sk Skin The given Skin
2233 * @param $includeStyle Boolean: unused
2234 * @return String: The doctype, opening <html>, and head element.
2235 */
2236 public function headElement( Skin $sk, $includeStyle = true ) {
2237 global $wgContLang, $wgUseTrackbacks;
2238 $userdir = $this->getLang()->getDir();
2239 $sitedir = $wgContLang->getDir();
2240
2241 if ( $sk->commonPrintStylesheet() ) {
2242 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2243 }
2244
2245 $ret = Html::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2246
2247 if ( $this->getHTMLTitle() == '' ) {
2248 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2249 }
2250
2251 $openHead = Html::openElement( 'head' );
2252 if ( $openHead ) {
2253 # Don't bother with the newline if $head == ''
2254 $ret .= "$openHead\n";
2255 }
2256
2257 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2258
2259 $ret .= implode( "\n", array(
2260 $this->getHeadLinks( null, true ),
2261 $this->buildCssLinks(),
2262 $this->getHeadScripts(),
2263 $this->getHeadItems()
2264 ) );
2265
2266 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2267 $ret .= $this->getTitle()->trackbackRDF();
2268 }
2269
2270 $closeHead = Html::closeElement( 'head' );
2271 if ( $closeHead ) {
2272 $ret .= "$closeHead\n";
2273 }
2274
2275 $bodyAttrs = array();
2276
2277 # Classes for LTR/RTL directionality support
2278 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2279
2280 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2281 # A <body> class is probably not the best way to do this . . .
2282 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2283 }
2284 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2285 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2286
2287 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2288 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2289
2290 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2291
2292 return $ret;
2293 }
2294
2295 /**
2296 * Add the default ResourceLoader modules to this object
2297 */
2298 private function addDefaultModules() {
2299 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2300
2301 // Add base resources
2302 $this->addModules( array(
2303 'mediawiki.user',
2304 'mediawiki.util',
2305 'mediawiki.page.startup',
2306 'mediawiki.page.ready',
2307 ) );
2308 if ( $wgIncludeLegacyJavaScript ){
2309 $this->addModules( 'mediawiki.legacy.wikibits' );
2310 }
2311
2312 // Add various resources if required
2313 if ( $wgUseAjax ) {
2314 $this->addModules( 'mediawiki.legacy.ajax' );
2315
2316 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2317
2318 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2319 $this->addModules( 'mediawiki.action.watch.ajax' );
2320 }
2321
2322 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2323 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2324 }
2325 }
2326
2327 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2328 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2329 }
2330
2331 # Crazy edit-on-double-click stuff
2332 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2333 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2334 }
2335 }
2336
2337 /**
2338 * Get a ResourceLoader object associated with this OutputPage
2339 *
2340 * @return ResourceLoader
2341 */
2342 public function getResourceLoader() {
2343 if ( is_null( $this->mResourceLoader ) ) {
2344 $this->mResourceLoader = new ResourceLoader();
2345 }
2346 return $this->mResourceLoader;
2347 }
2348
2349 /**
2350 * TODO: Document
2351 * @param $modules Array/string with the module name(s)
2352 * @param $only String ResourceLoaderModule TYPE_ class constant
2353 * @param $useESI boolean
2354 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2355 * @return string html <script> and <style> tags
2356 */
2357 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2358 global $wgLoadScript, $wgResourceLoaderUseESI,
2359 $wgResourceLoaderInlinePrivateModules;
2360
2361 if ( !count( $modules ) ) {
2362 return '';
2363 }
2364
2365 if ( count( $modules ) > 1 ) {
2366 // Remove duplicate module requests
2367 $modules = array_unique( (array) $modules );
2368 // Sort module names so requests are more uniform
2369 sort( $modules );
2370
2371 if ( ResourceLoader::inDebugMode() ) {
2372 // Recursively call us for every item
2373 $links = '';
2374 foreach ( $modules as $name ) {
2375 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2376 }
2377 return $links;
2378 }
2379 }
2380
2381 // Create keyed-by-group list of module objects from modules list
2382 $groups = array();
2383 $resourceLoader = $this->getResourceLoader();
2384 foreach ( (array) $modules as $name ) {
2385 $module = $resourceLoader->getModule( $name );
2386 # Check that we're allowed to include this module on this page
2387 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2388 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2389 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2390 && $only == ResourceLoaderModule::TYPE_STYLES )
2391 )
2392 {
2393 continue;
2394 }
2395
2396 $group = $module->getGroup();
2397 if ( !isset( $groups[$group] ) ) {
2398 $groups[$group] = array();
2399 }
2400 $groups[$group][$name] = $module;
2401 }
2402
2403 $links = '';
2404 foreach ( $groups as $group => $modules ) {
2405 // Special handling for user-specific groups
2406 $user = null;
2407 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2408 $user = $this->getUser()->getName();
2409 }
2410
2411 // Create a fake request based on the one we are about to make so modules return
2412 // correct timestamp and emptiness data
2413 $query = ResourceLoader::makeLoaderQuery(
2414 array(), // modules; not determined yet
2415 $this->getContext()->getLang()->getCode(),
2416 $this->getSkin()->getSkinName(),
2417 $user,
2418 null, // version; not determined yet
2419 ResourceLoader::inDebugMode(),
2420 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2421 $this->isPrintable(),
2422 $this->getRequest()->getBool( 'handheld' ),
2423 $extraQuery
2424 );
2425 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2426 // Drop modules that know they're empty
2427 foreach ( $modules as $key => $module ) {
2428 if ( $module->isKnownEmpty( $context ) ) {
2429 unset( $modules[$key] );
2430 }
2431 }
2432 // If there are no modules left, skip this group
2433 if ( $modules === array() ) {
2434 continue;
2435 }
2436
2437 // Support inlining of private modules if configured as such
2438 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2439 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2440 $links .= Html::inlineStyle(
2441 $resourceLoader->makeModuleResponse( $context, $modules )
2442 );
2443 } else {
2444 $links .= Html::inlineScript(
2445 ResourceLoader::makeLoaderConditionalScript(
2446 $resourceLoader->makeModuleResponse( $context, $modules )
2447 )
2448 );
2449 }
2450 $links .= "\n";
2451 continue;
2452 }
2453 // Special handling for the user group; because users might change their stuff
2454 // on-wiki like user pages, or user preferences; we need to find the highest
2455 // timestamp of these user-changable modules so we can ensure cache misses on change
2456 // This should NOT be done for the site group (bug 27564) because anons get that too
2457 // and we shouldn't be putting timestamps in Squid-cached HTML
2458 $version = null;
2459 if ( $group === 'user' ) {
2460 // Get the maximum timestamp
2461 $timestamp = 1;
2462 foreach ( $modules as $module ) {
2463 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2464 }
2465 // Add a version parameter so cache will break when things change
2466 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2467 }
2468
2469 $url = ResourceLoader::makeLoaderURL(
2470 array_keys( $modules ),
2471 $this->getContext()->getLang()->getCode(),
2472 $this->getSkin()->getSkinName(),
2473 $user,
2474 $version,
2475 ResourceLoader::inDebugMode(),
2476 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2477 $this->isPrintable(),
2478 $this->getRequest()->getBool( 'handheld' ),
2479 $extraQuery
2480 );
2481 if ( $useESI && $wgResourceLoaderUseESI ) {
2482 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2483 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2484 $link = Html::inlineStyle( $esi );
2485 } else {
2486 $link = Html::inlineScript( $esi );
2487 }
2488 } else {
2489 // Automatically select style/script elements
2490 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2491 $link = Html::linkedStyle( $url );
2492 } else {
2493 $link = Html::linkedScript( $url );
2494 }
2495 }
2496
2497 if( $group == 'noscript' ){
2498 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2499 } else {
2500 $links .= $link . "\n";
2501 }
2502 }
2503 return $links;
2504 }
2505
2506 /**
2507 * JS stuff to put in the <head>. This is the startup module, config
2508 * vars and modules marked with position 'top'
2509 *
2510 * @return String: HTML fragment
2511 */
2512 function getHeadScripts() {
2513 // Startup - this will immediately load jquery and mediawiki modules
2514 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2515
2516 // Load config before anything else
2517 $scripts .= Html::inlineScript(
2518 ResourceLoader::makeLoaderConditionalScript(
2519 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2520 )
2521 );
2522
2523 // Script and Messages "only" requests marked for top inclusion
2524 // Messages should go first
2525 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2526 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2527
2528 // Modules requests - let the client calculate dependencies and batch requests as it likes
2529 // Only load modules that have marked themselves for loading at the top
2530 $modules = $this->getModules( true, 'top' );
2531 if ( $modules ) {
2532 $scripts .= Html::inlineScript(
2533 ResourceLoader::makeLoaderConditionalScript(
2534 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2535 )
2536 );
2537 }
2538
2539 return $scripts;
2540 }
2541
2542 /**
2543 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2544 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2545 *
2546 * @return string
2547 */
2548 function getBottomScripts() {
2549 global $wgUseSiteJs, $wgAllowUserJs;
2550
2551 // Script and Messages "only" requests marked for bottom inclusion
2552 // Messages should go first
2553 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule::TYPE_MESSAGES );
2554 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule::TYPE_SCRIPTS );
2555
2556 // Modules requests - let the client calculate dependencies and batch requests as it likes
2557 // Only load modules that have marked themselves for loading at the bottom
2558 $modules = $this->getModules( true, 'bottom' );
2559 if ( $modules ) {
2560 $scripts .= Html::inlineScript(
2561 ResourceLoader::makeLoaderConditionalScript(
2562 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2563 )
2564 );
2565 }
2566
2567 // Legacy Scripts
2568 $scripts .= "\n" . $this->mScripts;
2569
2570 $userScripts = array( 'user.options', 'user.tokens' );
2571
2572 // Add site JS if enabled
2573 if ( $wgUseSiteJs ) {
2574 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS );
2575 if( $this->getUser()->isLoggedIn() ){
2576 $userScripts[] = 'user.groups';
2577 }
2578 }
2579
2580 // Add user JS if enabled
2581 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2582 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2583 # XXX: additional security check/prompt?
2584 // We're on a preview of a JS subpage
2585 // Exclude this page from the user module in case it's in there (bug 26283)
2586 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2587 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2588 );
2589 // Load the previewed JS
2590 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2591 } else {
2592 // Include the user module normally
2593 // We can't do $userScripts[] = 'user'; because the user module would end up
2594 // being wrapped in a closure, so load it raw like 'site'
2595 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS );
2596 }
2597 }
2598 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule::TYPE_COMBINED );
2599
2600 return $scripts;
2601 }
2602
2603 /**
2604 * Add one or more variables to be set in mw.config in JavaScript.
2605 *
2606 * @param $key {String|Array} Key or array of key/value pars.
2607 * @param $value {Mixed} Value of the configuration variable.
2608 */
2609 public function addJsConfigVars( $keys, $value ) {
2610 if ( is_array( $keys ) ) {
2611 foreach ( $keys as $key => $value ) {
2612 $this->mJsConfigVars[$key] = $value;
2613 }
2614 return;
2615 }
2616
2617 $this->mJsConfigVars[$keys] = $value;
2618 }
2619
2620
2621 /**
2622 * Get an array containing the variables to be set in mw.config in JavaScript.
2623 *
2624 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2625 * - in other words, page-independent/site-wide variables (without state).
2626 * You will only be adding bloat to the html page and causing page caches to
2627 * have to be purged on configuration changes.
2628 */
2629 protected function getJSVars() {
2630 global $wgUseAjax, $wgEnableMWSuggest;
2631
2632 $title = $this->getTitle();
2633 $ns = $title->getNamespace();
2634 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2635 if ( $ns == NS_SPECIAL ) {
2636 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2637 } else {
2638 $canonicalName = false; # bug 21115
2639 }
2640
2641 $vars = array(
2642 'wgCanonicalNamespace' => $nsname,
2643 'wgCanonicalSpecialPageName' => $canonicalName,
2644 'wgNamespaceNumber' => $title->getNamespace(),
2645 'wgPageName' => $title->getPrefixedDBKey(),
2646 'wgTitle' => $title->getText(),
2647 'wgCurRevisionId' => $title->getLatestRevID(),
2648 'wgArticleId' => $title->getArticleId(),
2649 'wgIsArticle' => $this->isArticle(),
2650 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2651 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2652 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2653 'wgCategories' => $this->getCategories(),
2654 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2655 );
2656 $lang = $this->getTitle()->getPageLanguage();
2657 if ( $lang->hasVariants() ) {
2658 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2659 }
2660 foreach ( $title->getRestrictionTypes() as $type ) {
2661 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2662 }
2663 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2664 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $this->getUser() );
2665 }
2666 if ( $title->isMainPage() ) {
2667 $vars['wgIsMainPage'] = true;
2668 }
2669
2670 // Allow extensions to add their custom variables to the mw.config map.
2671 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2672 // page-dependant but site-wide (without state).
2673 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2674 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, &$this ) );
2675
2676 // Merge in variables from addJsConfigVars last
2677 return array_merge( $vars, $this->mJsConfigVars );
2678 }
2679
2680 /**
2681 * To make it harder for someone to slip a user a fake
2682 * user-JavaScript or user-CSS preview, a random token
2683 * is associated with the login session. If it's not
2684 * passed back with the preview request, we won't render
2685 * the code.
2686 *
2687 * @return bool
2688 */
2689 public function userCanPreview() {
2690 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2691 || !$this->getRequest()->wasPosted()
2692 || !$this->getUser()->matchEditToken(
2693 $this->getRequest()->getVal( 'wpEditToken' ) )
2694 ) {
2695 return false;
2696 }
2697 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2698 return false;
2699 }
2700
2701 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2702 }
2703
2704 /**
2705 * @param $unused Unused
2706 * @param $addContentType bool
2707 *
2708 * @return string HTML tag links to be put in the header.
2709 */
2710 public function getHeadLinks( $unused = null, $addContentType = false ) {
2711 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2712 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2713 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2714 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2715 $wgRightsPage, $wgRightsUrl;
2716
2717 $tags = array();
2718
2719 if ( $addContentType ) {
2720 if ( $wgHtml5 ) {
2721 # More succinct than <meta http-equiv=Content-Type>, has the
2722 # same effect
2723 $tags[] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
2724 } else {
2725 $tags[] = Html::element( 'meta', array(
2726 'http-equiv' => 'Content-Type',
2727 'content' => "$wgMimeType; charset=UTF-8"
2728 ) );
2729 $tags[] = Html::element( 'meta', array( // bug 15835
2730 'http-equiv' => 'Content-Style-Type',
2731 'content' => 'text/css'
2732 ) );
2733 }
2734 }
2735
2736 $tags[] = Html::element( 'meta', array(
2737 'name' => 'generator',
2738 'content' => "MediaWiki $wgVersion",
2739 ) );
2740
2741 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2742 if( $p !== 'index,follow' ) {
2743 // http://www.robotstxt.org/wc/meta-user.html
2744 // Only show if it's different from the default robots policy
2745 $tags[] = Html::element( 'meta', array(
2746 'name' => 'robots',
2747 'content' => $p,
2748 ) );
2749 }
2750
2751 if ( count( $this->mKeywords ) > 0 ) {
2752 $strip = array(
2753 "/<.*?" . ">/" => '',
2754 "/_/" => ' '
2755 );
2756 $tags[] = Html::element( 'meta', array(
2757 'name' => 'keywords',
2758 'content' => preg_replace(
2759 array_keys( $strip ),
2760 array_values( $strip ),
2761 implode( ',', $this->mKeywords )
2762 )
2763 ) );
2764 }
2765
2766 foreach ( $this->mMetatags as $tag ) {
2767 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2768 $a = 'http-equiv';
2769 $tag[0] = substr( $tag[0], 5 );
2770 } else {
2771 $a = 'name';
2772 }
2773 $tags[] = Html::element( 'meta',
2774 array(
2775 $a => $tag[0],
2776 'content' => $tag[1]
2777 )
2778 );
2779 }
2780
2781 foreach ( $this->mLinktags as $tag ) {
2782 $tags[] = Html::element( 'link', $tag );
2783 }
2784
2785 # Universal edit button
2786 if ( $wgUniversalEditButton ) {
2787 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2788 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
2789 // Original UniversalEditButton
2790 $msg = wfMsg( 'edit' );
2791 $tags[] = Html::element( 'link', array(
2792 'rel' => 'alternate',
2793 'type' => 'application/x-wiki',
2794 'title' => $msg,
2795 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2796 ) );
2797 // Alternate edit link
2798 $tags[] = Html::element( 'link', array(
2799 'rel' => 'edit',
2800 'title' => $msg,
2801 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2802 ) );
2803 }
2804 }
2805
2806 # Generally the order of the favicon and apple-touch-icon links
2807 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2808 # uses whichever one appears later in the HTML source. Make sure
2809 # apple-touch-icon is specified first to avoid this.
2810 if ( $wgAppleTouchIcon !== false ) {
2811 $tags[] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2812 }
2813
2814 if ( $wgFavicon !== false ) {
2815 $tags[] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2816 }
2817
2818 # OpenSearch description link
2819 $tags[] = Html::element( 'link', array(
2820 'rel' => 'search',
2821 'type' => 'application/opensearchdescription+xml',
2822 'href' => wfScript( 'opensearch_desc' ),
2823 'title' => wfMsgForContent( 'opensearch-desc' ),
2824 ) );
2825
2826 if ( $wgEnableAPI ) {
2827 # Real Simple Discovery link, provides auto-discovery information
2828 # for the MediaWiki API (and potentially additional custom API
2829 # support such as WordPress or Twitter-compatible APIs for a
2830 # blogging extension, etc)
2831 $tags[] = Html::element( 'link', array(
2832 'rel' => 'EditURI',
2833 'type' => 'application/rsd+xml',
2834 // Output a protocol-relative URL here if $wgServer is protocol-relative
2835 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2836 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
2837 ) );
2838 }
2839
2840 $lang = $this->getTitle()->getPageLanguage();
2841
2842 # Language variants
2843 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2844 && $lang->hasVariants() ) {
2845
2846 $urlvar = $lang->getURLVariant();
2847
2848 if ( !$urlvar ) {
2849 $variants = $lang->getVariants();
2850 foreach ( $variants as $_v ) {
2851 $tags[] = Html::element( 'link', array(
2852 'rel' => 'alternate',
2853 'hreflang' => $_v,
2854 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2855 );
2856 }
2857 } else {
2858 $tags[] = Html::element( 'link', array(
2859 'rel' => 'canonical',
2860 'href' => $this->getTitle()->getCanonicalUrl()
2861 ) );
2862 }
2863 }
2864
2865 # Copyright
2866 $copyright = '';
2867 if ( $wgRightsPage ) {
2868 $copy = Title::newFromText( $wgRightsPage );
2869
2870 if ( $copy ) {
2871 $copyright = $copy->getLocalURL();
2872 }
2873 }
2874
2875 if ( !$copyright && $wgRightsUrl ) {
2876 $copyright = $wgRightsUrl;
2877 }
2878
2879 if ( $copyright ) {
2880 $tags[] = Html::element( 'link', array(
2881 'rel' => 'copyright',
2882 'href' => $copyright )
2883 );
2884 }
2885
2886 # Feeds
2887 if ( $wgFeed ) {
2888 foreach( $this->getSyndicationLinks() as $format => $link ) {
2889 # Use the page name for the title. In principle, this could
2890 # lead to issues with having the same name for different feeds
2891 # corresponding to the same page, but we can't avoid that at
2892 # this low a level.
2893
2894 $tags[] = $this->feedLink(
2895 $format,
2896 $link,
2897 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2898 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2899 );
2900 }
2901
2902 # Recent changes feed should appear on every page (except recentchanges,
2903 # that would be redundant). Put it after the per-page feed to avoid
2904 # changing existing behavior. It's still available, probably via a
2905 # menu in your browser. Some sites might have a different feed they'd
2906 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2907 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2908 # If so, use it instead.
2909
2910 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2911
2912 if ( $wgOverrideSiteFeed ) {
2913 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2914 // Note, this->feedLink escapes the url.
2915 $tags[] = $this->feedLink(
2916 $type,
2917 $feedUrl,
2918 wfMsg( "site-{$type}-feed", $wgSitename )
2919 );
2920 }
2921 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2922 foreach ( $wgAdvertisedFeedTypes as $format ) {
2923 $tags[] = $this->feedLink(
2924 $format,
2925 $rctitle->getLocalURL( "feed={$format}" ),
2926 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2927 );
2928 }
2929 }
2930 }
2931 return implode( "\n", $tags );
2932 }
2933
2934 /**
2935 * Generate a <link rel/> for a feed.
2936 *
2937 * @param $type String: feed type
2938 * @param $url String: URL to the feed
2939 * @param $text String: value of the "title" attribute
2940 * @return String: HTML fragment
2941 */
2942 private function feedLink( $type, $url, $text ) {
2943 return Html::element( 'link', array(
2944 'rel' => 'alternate',
2945 'type' => "application/$type+xml",
2946 'title' => $text,
2947 'href' => $url )
2948 );
2949 }
2950
2951 /**
2952 * Add a local or specified stylesheet, with the given media options.
2953 * Meant primarily for internal use...
2954 *
2955 * @param $style String: URL to the file
2956 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2957 * @param $condition String: for IE conditional comments, specifying an IE version
2958 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2959 */
2960 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2961 $options = array();
2962 // Even though we expect the media type to be lowercase, but here we
2963 // force it to lowercase to be safe.
2964 if( $media ) {
2965 $options['media'] = $media;
2966 }
2967 if( $condition ) {
2968 $options['condition'] = $condition;
2969 }
2970 if( $dir ) {
2971 $options['dir'] = $dir;
2972 }
2973 $this->styles[$style] = $options;
2974 }
2975
2976 /**
2977 * Adds inline CSS styles
2978 * @param $style_css Mixed: inline CSS
2979 * @param $flip String: Set to 'flip' to flip the CSS if needed
2980 */
2981 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
2982 if( $flip === 'flip' && $this->getLang()->isRTL() ) {
2983 # If wanted, and the interface is right-to-left, flip the CSS
2984 $style_css = CSSJanus::transform( $style_css, true, false );
2985 }
2986 $this->mInlineStyles .= Html::inlineStyle( $style_css );
2987 }
2988
2989 /**
2990 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
2991 * These will be applied to various media & IE conditionals.
2992 *
2993 * @return string
2994 */
2995 public function buildCssLinks() {
2996 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
2997
2998 $this->getSkin()->setupSkinUserCss( $this );
2999
3000 // Add ResourceLoader styles
3001 // Split the styles into four groups
3002 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3003 $otherTags = ''; // Tags to append after the normal <link> tags
3004 $resourceLoader = $this->getResourceLoader();
3005
3006 $moduleStyles = $this->getModuleStyles();
3007
3008 // Per-site custom styles
3009 if ( $wgUseSiteCss ) {
3010 $moduleStyles[] = 'site';
3011 $moduleStyles[] = 'noscript';
3012 if( $this->getUser()->isLoggedIn() ){
3013 $moduleStyles[] = 'user.groups';
3014 }
3015 }
3016
3017 // Per-user custom styles
3018 if ( $wgAllowUserCss ) {
3019 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3020 // We're on a preview of a CSS subpage
3021 // Exclude this page from the user module in case it's in there (bug 26283)
3022 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3023 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3024 );
3025 // Load the previewed CSS
3026 $otherTags .= Html::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3027 } else {
3028 // Load the user styles normally
3029 $moduleStyles[] = 'user';
3030 }
3031 }
3032
3033 // Per-user preference styles
3034 if ( $wgAllowUserCssPrefs ) {
3035 $moduleStyles[] = 'user.options';
3036 }
3037
3038 foreach ( $moduleStyles as $name ) {
3039 $group = $resourceLoader->getModule( $name )->getGroup();
3040 // Modules in groups named "other" or anything different than "user", "site" or "private"
3041 // will be placed in the "other" group
3042 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3043 }
3044
3045 // We want site, private and user styles to override dynamically added styles from modules, but we want
3046 // dynamically added styles to override statically added styles from other modules. So the order
3047 // has to be other, dynamic, site, private, user
3048 // Add statically added styles for other modules
3049 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3050 // Add normal styles added through addStyle()/addInlineStyle() here
3051 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3052 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3053 // We use a <meta> tag with a made-up name for this because that's valid HTML
3054 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3055
3056 // Add site, private and user styles
3057 // 'private' at present only contains user.options, so put that before 'user'
3058 // Any future private modules will likely have a similar user-specific character
3059 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3060 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3061 ResourceLoaderModule::TYPE_STYLES
3062 );
3063 }
3064
3065 // Add stuff in $otherTags (previewed user CSS if applicable)
3066 $ret .= $otherTags;
3067 return $ret;
3068 }
3069
3070 /**
3071 * @return Array
3072 */
3073 public function buildCssLinksArray() {
3074 $links = array();
3075
3076 // Add any extension CSS
3077 foreach ( $this->mExtStyles as $url ) {
3078 $this->addStyle( $url );
3079 }
3080 $this->mExtStyles = array();
3081
3082 foreach( $this->styles as $file => $options ) {
3083 $link = $this->styleLink( $file, $options );
3084 if( $link ) {
3085 $links[$file] = $link;
3086 }
3087 }
3088 return $links;
3089 }
3090
3091 /**
3092 * Generate \<link\> tags for stylesheets
3093 *
3094 * @param $style String: URL to the file
3095 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3096 * keys
3097 * @return String: HTML fragment
3098 */
3099 protected function styleLink( $style, $options ) {
3100 if( isset( $options['dir'] ) ) {
3101 if( $this->getLang()->getDir() != $options['dir'] ) {
3102 return '';
3103 }
3104 }
3105
3106 if( isset( $options['media'] ) ) {
3107 $media = self::transformCssMedia( $options['media'] );
3108 if( is_null( $media ) ) {
3109 return '';
3110 }
3111 } else {
3112 $media = 'all';
3113 }
3114
3115 if( substr( $style, 0, 1 ) == '/' ||
3116 substr( $style, 0, 5 ) == 'http:' ||
3117 substr( $style, 0, 6 ) == 'https:' ) {
3118 $url = $style;
3119 } else {
3120 global $wgStylePath, $wgStyleVersion;
3121 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3122 }
3123
3124 $link = Html::linkedStyle( $url, $media );
3125
3126 if( isset( $options['condition'] ) ) {
3127 $condition = htmlspecialchars( $options['condition'] );
3128 $link = "<!--[if $condition]>$link<![endif]-->";
3129 }
3130 return $link;
3131 }
3132
3133 /**
3134 * Transform "media" attribute based on request parameters
3135 *
3136 * @param $media String: current value of the "media" attribute
3137 * @return String: modified value of the "media" attribute
3138 */
3139 public static function transformCssMedia( $media ) {
3140 global $wgRequest, $wgHandheldForIPhone;
3141
3142 // Switch in on-screen display for media testing
3143 $switches = array(
3144 'printable' => 'print',
3145 'handheld' => 'handheld',
3146 );
3147 foreach( $switches as $switch => $targetMedia ) {
3148 if( $wgRequest->getBool( $switch ) ) {
3149 if( $media == $targetMedia ) {
3150 $media = '';
3151 } elseif( $media == 'screen' ) {
3152 return null;
3153 }
3154 }
3155 }
3156
3157 // Expand longer media queries as iPhone doesn't grok 'handheld'
3158 if( $wgHandheldForIPhone ) {
3159 $mediaAliases = array(
3160 'screen' => 'screen and (min-device-width: 481px)',
3161 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3162 );
3163
3164 if( isset( $mediaAliases[$media] ) ) {
3165 $media = $mediaAliases[$media];
3166 }
3167 }
3168
3169 return $media;
3170 }
3171
3172 /**
3173 * Add a wikitext-formatted message to the output.
3174 * This is equivalent to:
3175 *
3176 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3177 */
3178 public function addWikiMsg( /*...*/ ) {
3179 $args = func_get_args();
3180 $name = array_shift( $args );
3181 $this->addWikiMsgArray( $name, $args );
3182 }
3183
3184 /**
3185 * Add a wikitext-formatted message to the output.
3186 * Like addWikiMsg() except the parameters are taken as an array
3187 * instead of a variable argument list.
3188 *
3189 * $options is passed through to wfMsgExt(), see that function for details.
3190 *
3191 * @param $name string
3192 * @param $args array
3193 * @param $options array
3194 */
3195 public function addWikiMsgArray( $name, $args, $options = array() ) {
3196 $options[] = 'parse';
3197 $text = wfMsgExt( $name, $options, $args );
3198 $this->addHTML( $text );
3199 }
3200
3201 /**
3202 * This function takes a number of message/argument specifications, wraps them in
3203 * some overall structure, and then parses the result and adds it to the output.
3204 *
3205 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3206 * on. The subsequent arguments may either be strings, in which case they are the
3207 * message names, or arrays, in which case the first element is the message name,
3208 * and subsequent elements are the parameters to that message.
3209 *
3210 * The special named parameter 'options' in a message specification array is passed
3211 * through to the $options parameter of wfMsgExt().
3212 *
3213 * Don't use this for messages that are not in users interface language.
3214 *
3215 * For example:
3216 *
3217 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3218 *
3219 * Is equivalent to:
3220 *
3221 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3222 *
3223 * The newline after opening div is needed in some wikitext. See bug 19226.
3224 *
3225 * @param $wrap string
3226 */
3227 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3228 $msgSpecs = func_get_args();
3229 array_shift( $msgSpecs );
3230 $msgSpecs = array_values( $msgSpecs );
3231 $s = $wrap;
3232 foreach ( $msgSpecs as $n => $spec ) {
3233 $options = array();
3234 if ( is_array( $spec ) ) {
3235 $args = $spec;
3236 $name = array_shift( $args );
3237 if ( isset( $args['options'] ) ) {
3238 $options = $args['options'];
3239 unset( $args['options'] );
3240 }
3241 } else {
3242 $args = array();
3243 $name = $spec;
3244 }
3245 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3246 }
3247 $this->addWikiText( $s );
3248 }
3249
3250 /**
3251 * Include jQuery core. Use this to avoid loading it multiple times
3252 * before we get a usable script loader.
3253 *
3254 * @param $modules Array: list of jQuery modules which should be loaded
3255 * @return Array: the list of modules which were not loaded.
3256 * @since 1.16
3257 * @deprecated since 1.17
3258 */
3259 public function includeJQuery( $modules = array() ) {
3260 return array();
3261 }
3262
3263 }