* Changed ParserOptions to store a Language object instead of only a string, avoids...
[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 * Shortcut for adding an Html::element via addHTML.
1207 *
1208 * @since 1.19
1209 *
1210 * @param $element string
1211 * @param $attribs array
1212 * @param $contents string
1213 */
1214 public function addElement( $element, $attribs = array(), $contents = '' ) {
1215 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1216 }
1217
1218 /**
1219 * Clear the body HTML
1220 */
1221 public function clearHTML() {
1222 $this->mBodytext = '';
1223 }
1224
1225 /**
1226 * Get the body HTML
1227 *
1228 * @return String: HTML
1229 */
1230 public function getHTML() {
1231 return $this->mBodytext;
1232 }
1233
1234 /**
1235 * Add $text to the debug output
1236 *
1237 * @param $text String: debug text
1238 */
1239 public function debug( $text ) {
1240 $this->mDebugtext .= $text;
1241 }
1242
1243 /**
1244 * Get/set the ParserOptions object to use for wikitext parsing
1245 *
1246 * @param $options either the ParserOption to use or null to only get the
1247 * current ParserOption object
1248 * @return ParserOptions object
1249 */
1250 public function parserOptions( $options = null ) {
1251 if ( !$this->mParserOptions ) {
1252 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1253 $this->mParserOptions->setEditSection( false );
1254 }
1255 return wfSetVar( $this->mParserOptions, $options );
1256 }
1257
1258 /**
1259 * Set the revision ID which will be seen by the wiki text parser
1260 * for things such as embedded {{REVISIONID}} variable use.
1261 *
1262 * @param $revid Mixed: an positive integer, or null
1263 * @return Mixed: previous value
1264 */
1265 public function setRevisionId( $revid ) {
1266 $val = is_null( $revid ) ? null : intval( $revid );
1267 return wfSetVar( $this->mRevisionId, $val );
1268 }
1269
1270 /**
1271 * Get the displayed revision ID
1272 *
1273 * @return Integer
1274 */
1275 public function getRevisionId() {
1276 return $this->mRevisionId;
1277 }
1278
1279 /**
1280 * Set the displayed file version
1281 *
1282 * @param $file File|false
1283 * @return Mixed: previous value
1284 */
1285 public function setFileVersion( $file ) {
1286 $val = null;
1287 if ( $file instanceof File && $file->exists() ) {
1288 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1289 }
1290 return wfSetVar( $this->mFileVersion, $val, true );
1291 }
1292
1293 /**
1294 * Get the displayed file version
1295 *
1296 * @return Array|null ('time' => MW timestamp, 'sha1' => sha1)
1297 */
1298 public function getFileVersion() {
1299 return $this->mFileVersion;
1300 }
1301
1302 /**
1303 * Get the templates used on this page
1304 *
1305 * @return Array (namespace => dbKey => revId)
1306 * @since 1.18
1307 */
1308 public function getTemplateIds() {
1309 return $this->mTemplateIds;
1310 }
1311
1312 /**
1313 * Get the files used on this page
1314 *
1315 * @return Array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1316 * @since 1.18
1317 */
1318 public function getFileSearchOptions() {
1319 return $this->mImageTimeKeys;
1320 }
1321
1322 /**
1323 * Convert wikitext to HTML and add it to the buffer
1324 * Default assumes that the current page title will be used.
1325 *
1326 * @param $text String
1327 * @param $linestart Boolean: is this the start of a line?
1328 * @param $interface Boolean: is this text in the user interface language?
1329 */
1330 public function addWikiText( $text, $linestart = true, $interface = true ) {
1331 $title = $this->getTitle(); // Work arround E_STRICT
1332 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1333 }
1334
1335 /**
1336 * Add wikitext with a custom Title object
1337 *
1338 * @param $text String: wikitext
1339 * @param $title Title object
1340 * @param $linestart Boolean: is this the start of a line?
1341 */
1342 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1343 $this->addWikiTextTitle( $text, $title, $linestart );
1344 }
1345
1346 /**
1347 * Add wikitext with a custom Title object and tidy enabled.
1348 *
1349 * @param $text String: wikitext
1350 * @param $title Title object
1351 * @param $linestart Boolean: is this the start of a line?
1352 */
1353 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1354 $this->addWikiTextTitle( $text, $title, $linestart, true );
1355 }
1356
1357 /**
1358 * Add wikitext with tidy enabled
1359 *
1360 * @param $text String: wikitext
1361 * @param $linestart Boolean: is this the start of a line?
1362 */
1363 public function addWikiTextTidy( $text, $linestart = true ) {
1364 $title = $this->getTitle();
1365 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1366 }
1367
1368 /**
1369 * Add wikitext with a custom Title object
1370 *
1371 * @param $text String: wikitext
1372 * @param $title Title object
1373 * @param $linestart Boolean: is this the start of a line?
1374 * @param $tidy Boolean: whether to use tidy
1375 * @param $interface Boolean: whether it is an interface message
1376 * (for example disables conversion)
1377 */
1378 public function addWikiTextTitle( $text, &$title, $linestart, $tidy = false, $interface = false ) {
1379 global $wgParser;
1380
1381 wfProfileIn( __METHOD__ );
1382
1383 wfIncrStats( 'pcache_not_possible' );
1384
1385 $popts = $this->parserOptions();
1386 $oldTidy = $popts->setTidy( $tidy );
1387 $popts->setInterfaceMessage( (bool) $interface );
1388
1389 $parserOutput = $wgParser->parse(
1390 $text, $title, $popts,
1391 $linestart, true, $this->mRevisionId
1392 );
1393
1394 $popts->setTidy( $oldTidy );
1395
1396 $this->addParserOutput( $parserOutput );
1397
1398 wfProfileOut( __METHOD__ );
1399 }
1400
1401 /**
1402 * Add a ParserOutput object, but without Html
1403 *
1404 * @param $parserOutput ParserOutput object
1405 */
1406 public function addParserOutputNoText( &$parserOutput ) {
1407 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1408 $this->addCategoryLinks( $parserOutput->getCategories() );
1409 $this->mNewSectionLink = $parserOutput->getNewSection();
1410 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1411
1412 $this->mParseWarnings = $parserOutput->getWarnings();
1413 if ( !$parserOutput->isCacheable() ) {
1414 $this->enableClientCache( false );
1415 }
1416 $this->mNoGallery = $parserOutput->getNoGallery();
1417 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1418 $this->addModules( $parserOutput->getModules() );
1419 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1420 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1421 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1422
1423 // Template versioning...
1424 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1425 if ( isset( $this->mTemplateIds[$ns] ) ) {
1426 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1427 } else {
1428 $this->mTemplateIds[$ns] = $dbks;
1429 }
1430 }
1431 // File versioning...
1432 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1433 $this->mImageTimeKeys[$dbk] = $data;
1434 }
1435
1436 // Hooks registered in the object
1437 global $wgParserOutputHooks;
1438 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1439 list( $hookName, $data ) = $hookInfo;
1440 if ( isset( $wgParserOutputHooks[$hookName] ) ) {
1441 call_user_func( $wgParserOutputHooks[$hookName], $this, $parserOutput, $data );
1442 }
1443 }
1444
1445 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1446 }
1447
1448 /**
1449 * Add a ParserOutput object
1450 *
1451 * @param $parserOutput ParserOutput
1452 */
1453 function addParserOutput( &$parserOutput ) {
1454 $this->addParserOutputNoText( $parserOutput );
1455 $text = $parserOutput->getText();
1456 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1457 $this->addHTML( $text );
1458 }
1459
1460
1461 /**
1462 * Add the output of a QuickTemplate to the output buffer
1463 *
1464 * @param $template QuickTemplate
1465 */
1466 public function addTemplate( &$template ) {
1467 ob_start();
1468 $template->execute();
1469 $this->addHTML( ob_get_contents() );
1470 ob_end_clean();
1471 }
1472
1473 /**
1474 * Parse wikitext and return the HTML.
1475 *
1476 * @param $text String
1477 * @param $linestart Boolean: is this the start of a line?
1478 * @param $interface Boolean: use interface language ($wgLang instead of
1479 * $wgContLang) while parsing language sensitive magic
1480 * words like GRAMMAR and PLURAL. This also disables
1481 * LanguageConverter.
1482 * @param $language Language object: target language object, will override
1483 * $interface
1484 * @return String: HTML
1485 */
1486 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1487 global $wgParser;
1488
1489 if( is_null( $this->getTitle() ) ) {
1490 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1491 }
1492
1493 $popts = $this->parserOptions();
1494 if ( $interface ) {
1495 $popts->setInterfaceMessage( true );
1496 }
1497 if ( $language !== null ) {
1498 $oldLang = $popts->setTargetLanguage( $language );
1499 }
1500
1501 $parserOutput = $wgParser->parse(
1502 $text, $this->getTitle(), $popts,
1503 $linestart, true, $this->mRevisionId
1504 );
1505
1506 if ( $interface ) {
1507 $popts->setInterfaceMessage( false );
1508 }
1509 if ( $language !== null ) {
1510 $popts->setTargetLanguage( $oldLang );
1511 }
1512
1513 return $parserOutput->getText();
1514 }
1515
1516 /**
1517 * Parse wikitext, strip paragraphs, and return the HTML.
1518 *
1519 * @param $text String
1520 * @param $linestart Boolean: is this the start of a line?
1521 * @param $interface Boolean: use interface language ($wgLang instead of
1522 * $wgContLang) while parsing language sensitive magic
1523 * words like GRAMMAR and PLURAL
1524 * @return String: HTML
1525 */
1526 public function parseInline( $text, $linestart = true, $interface = false ) {
1527 $parsed = $this->parse( $text, $linestart, $interface );
1528
1529 $m = array();
1530 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?/sU', $parsed, $m ) ) {
1531 $parsed = $m[1];
1532 }
1533
1534 return $parsed;
1535 }
1536
1537 /**
1538 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1539 *
1540 * @param $maxage Integer: maximum cache time on the Squid, in seconds.
1541 */
1542 public function setSquidMaxage( $maxage ) {
1543 $this->mSquidMaxage = $maxage;
1544 }
1545
1546 /**
1547 * Use enableClientCache(false) to force it to send nocache headers
1548 *
1549 * @param $state bool
1550 *
1551 * @return bool
1552 */
1553 public function enableClientCache( $state ) {
1554 return wfSetVar( $this->mEnableClientCache, $state );
1555 }
1556
1557 /**
1558 * Get the list of cookies that will influence on the cache
1559 *
1560 * @return Array
1561 */
1562 function getCacheVaryCookies() {
1563 global $wgCookiePrefix, $wgCacheVaryCookies;
1564 static $cookies;
1565 if ( $cookies === null ) {
1566 $cookies = array_merge(
1567 array(
1568 "{$wgCookiePrefix}Token",
1569 "{$wgCookiePrefix}LoggedOut",
1570 session_name()
1571 ),
1572 $wgCacheVaryCookies
1573 );
1574 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1575 }
1576 return $cookies;
1577 }
1578
1579 /**
1580 * Return whether this page is not cacheable because "useskin" or "uselang"
1581 * URL parameters were passed.
1582 *
1583 * @return Boolean
1584 */
1585 function uncacheableBecauseRequestVars() {
1586 $request = $this->getRequest();
1587 return $request->getText( 'useskin', false ) === false
1588 && $request->getText( 'uselang', false ) === false;
1589 }
1590
1591 /**
1592 * Check if the request has a cache-varying cookie header
1593 * If it does, it's very important that we don't allow public caching
1594 *
1595 * @return Boolean
1596 */
1597 function haveCacheVaryCookies() {
1598 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1599 if ( $cookieHeader === false ) {
1600 return false;
1601 }
1602 $cvCookies = $this->getCacheVaryCookies();
1603 foreach ( $cvCookies as $cookieName ) {
1604 # Check for a simple string match, like the way squid does it
1605 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1606 wfDebug( __METHOD__ . ": found $cookieName\n" );
1607 return true;
1608 }
1609 }
1610 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1611 return false;
1612 }
1613
1614 /**
1615 * Add an HTTP header that will influence on the cache
1616 *
1617 * @param $header String: header name
1618 * @param $option Array|null
1619 * @todo FIXME: Document the $option parameter; it appears to be for
1620 * X-Vary-Options but what format is acceptable?
1621 */
1622 public function addVaryHeader( $header, $option = null ) {
1623 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1624 $this->mVaryHeader[$header] = (array)$option;
1625 } elseif( is_array( $option ) ) {
1626 if( is_array( $this->mVaryHeader[$header] ) ) {
1627 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1628 } else {
1629 $this->mVaryHeader[$header] = $option;
1630 }
1631 }
1632 $this->mVaryHeader[$header] = array_unique( $this->mVaryHeader[$header] );
1633 }
1634
1635 /**
1636 * Get a complete X-Vary-Options header
1637 *
1638 * @return String
1639 */
1640 public function getXVO() {
1641 $cvCookies = $this->getCacheVaryCookies();
1642
1643 $cookiesOption = array();
1644 foreach ( $cvCookies as $cookieName ) {
1645 $cookiesOption[] = 'string-contains=' . $cookieName;
1646 }
1647 $this->addVaryHeader( 'Cookie', $cookiesOption );
1648
1649 $headers = array();
1650 foreach( $this->mVaryHeader as $header => $option ) {
1651 $newheader = $header;
1652 if( is_array( $option ) ) {
1653 $newheader .= ';' . implode( ';', $option );
1654 }
1655 $headers[] = $newheader;
1656 }
1657 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1658
1659 return $xvo;
1660 }
1661
1662 /**
1663 * bug 21672: Add Accept-Language to Vary and XVO headers
1664 * if there's no 'variant' parameter existed in GET.
1665 *
1666 * For example:
1667 * /w/index.php?title=Main_page should always be served; but
1668 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1669 */
1670 function addAcceptLanguage() {
1671 $lang = $this->getTitle()->getPageLanguage();
1672 if( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1673 $variants = $lang->getVariants();
1674 $aloption = array();
1675 foreach ( $variants as $variant ) {
1676 if( $variant === $lang->getCode() ) {
1677 continue;
1678 } else {
1679 $aloption[] = 'string-contains=' . $variant;
1680
1681 // IE and some other browsers use another form of language code
1682 // in their Accept-Language header, like "zh-CN" or "zh-TW".
1683 // We should handle these too.
1684 $ievariant = explode( '-', $variant );
1685 if ( count( $ievariant ) == 2 ) {
1686 $ievariant[1] = strtoupper( $ievariant[1] );
1687 $ievariant = implode( '-', $ievariant );
1688 $aloption[] = 'string-contains=' . $ievariant;
1689 }
1690 }
1691 }
1692 $this->addVaryHeader( 'Accept-Language', $aloption );
1693 }
1694 }
1695
1696 /**
1697 * Set a flag which will cause an X-Frame-Options header appropriate for
1698 * edit pages to be sent. The header value is controlled by
1699 * $wgEditPageFrameOptions.
1700 *
1701 * This is the default for special pages. If you display a CSRF-protected
1702 * form on an ordinary view page, then you need to call this function.
1703 *
1704 * @param $enable bool
1705 */
1706 public function preventClickjacking( $enable = true ) {
1707 $this->mPreventClickjacking = $enable;
1708 }
1709
1710 /**
1711 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
1712 * This can be called from pages which do not contain any CSRF-protected
1713 * HTML form.
1714 */
1715 public function allowClickjacking() {
1716 $this->mPreventClickjacking = false;
1717 }
1718
1719 /**
1720 * Get the X-Frame-Options header value (without the name part), or false
1721 * if there isn't one. This is used by Skin to determine whether to enable
1722 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
1723 *
1724 * @return string
1725 */
1726 public function getFrameOptions() {
1727 global $wgBreakFrames, $wgEditPageFrameOptions;
1728 if ( $wgBreakFrames ) {
1729 return 'DENY';
1730 } elseif ( $this->mPreventClickjacking && $wgEditPageFrameOptions ) {
1731 return $wgEditPageFrameOptions;
1732 }
1733 return false;
1734 }
1735
1736 /**
1737 * Send cache control HTTP headers
1738 */
1739 public function sendCacheControl() {
1740 global $wgUseSquid, $wgUseESI, $wgUseETag, $wgSquidMaxage, $wgUseXVO;
1741
1742 $response = $this->getRequest()->response();
1743 if ( $wgUseETag && $this->mETag ) {
1744 $response->header( "ETag: $this->mETag" );
1745 }
1746
1747 $this->addAcceptLanguage();
1748
1749 # don't serve compressed data to clients who can't handle it
1750 # maintain different caches for logged-in users and non-logged in ones
1751 $response->header( 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) ) );
1752
1753 if ( $wgUseXVO ) {
1754 # Add an X-Vary-Options header for Squid with Wikimedia patches
1755 $response->header( $this->getXVO() );
1756 }
1757
1758 if( !$this->uncacheableBecauseRequestVars() && $this->mEnableClientCache ) {
1759 if(
1760 $wgUseSquid && session_id() == '' && !$this->isPrintable() &&
1761 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
1762 )
1763 {
1764 if ( $wgUseESI ) {
1765 # We'll purge the proxy cache explicitly, but require end user agents
1766 # to revalidate against the proxy on each visit.
1767 # Surrogate-Control controls our Squid, Cache-Control downstream caches
1768 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", false );
1769 # start with a shorter timeout for initial testing
1770 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
1771 $response->header( 'Surrogate-Control: max-age='.$wgSquidMaxage.'+'.$this->mSquidMaxage.', content="ESI/1.0"');
1772 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
1773 } else {
1774 # We'll purge the proxy cache for anons explicitly, but require end user agents
1775 # to revalidate against the proxy on each visit.
1776 # IMPORTANT! The Squid needs to replace the Cache-Control header with
1777 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
1778 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", false );
1779 # start with a shorter timeout for initial testing
1780 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
1781 $response->header( 'Cache-Control: s-maxage='.$this->mSquidMaxage.', must-revalidate, max-age=0' );
1782 }
1783 } else {
1784 # We do want clients to cache if they can, but they *must* check for updates
1785 # on revisiting the page.
1786 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", false );
1787 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1788 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
1789 }
1790 if($this->mLastModified) {
1791 $response->header( "Last-Modified: {$this->mLastModified}" );
1792 }
1793 } else {
1794 wfDebug( __METHOD__ . ": no caching **\n", false );
1795
1796 # In general, the absence of a last modified header should be enough to prevent
1797 # the client from using its cache. We send a few other things just to make sure.
1798 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1799 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1800 $response->header( 'Pragma: no-cache' );
1801 }
1802 }
1803
1804 /**
1805 * Get the message associed with the HTTP response code $code
1806 *
1807 * @param $code Integer: status code
1808 * @return String or null: message or null if $code is not in the list of
1809 * messages
1810 *
1811 * @deprecated since 1.18 Use HttpStatus::getMessage() instead.
1812 */
1813 public static function getStatusMessage( $code ) {
1814 wfDeprecated( __METHOD__ );
1815 return HttpStatus::getMessage( $code );
1816 }
1817
1818 /**
1819 * Finally, all the text has been munged and accumulated into
1820 * the object, let's actually output it:
1821 */
1822 public function output() {
1823 global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP;
1824
1825 if( $this->mDoNothing ) {
1826 return;
1827 }
1828
1829 wfProfileIn( __METHOD__ );
1830
1831 $response = $this->getRequest()->response();
1832
1833 if ( $this->mRedirect != '' ) {
1834 # Standards require redirect URLs to be absolute
1835 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
1836 if( $this->mRedirectCode == '301' || $this->mRedirectCode == '303' ) {
1837 if( !$wgDebugRedirects ) {
1838 $message = HttpStatus::getMessage( $this->mRedirectCode );
1839 $response->header( "HTTP/1.1 {$this->mRedirectCode} $message" );
1840 }
1841 $this->mLastModified = wfTimestamp( TS_RFC2822 );
1842 }
1843 if ( $wgVaryOnXFP ) {
1844 $this->addVaryHeader( 'X-Forwarded-Proto' );
1845 }
1846 $this->sendCacheControl();
1847
1848 $response->header( "Content-Type: text/html; charset=utf-8" );
1849 if( $wgDebugRedirects ) {
1850 $url = htmlspecialchars( $this->mRedirect );
1851 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
1852 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
1853 print "</body>\n</html>\n";
1854 } else {
1855 $response->header( 'Location: ' . $this->mRedirect );
1856 }
1857 wfProfileOut( __METHOD__ );
1858 return;
1859 } elseif ( $this->mStatusCode ) {
1860 $message = HttpStatus::getMessage( $this->mStatusCode );
1861 if ( $message ) {
1862 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
1863 }
1864 }
1865
1866 # Buffer output; final headers may depend on later processing
1867 ob_start();
1868
1869 $response->header( "Content-type: $wgMimeType; charset=UTF-8" );
1870 $response->header( 'Content-language: ' . $wgLanguageCode );
1871
1872 // Prevent framing, if requested
1873 $frameOptions = $this->getFrameOptions();
1874 if ( $frameOptions ) {
1875 $response->header( "X-Frame-Options: $frameOptions" );
1876 }
1877
1878 if ( $this->mArticleBodyOnly ) {
1879 $this->out( $this->mBodytext );
1880 } else {
1881 $this->addDefaultModules();
1882
1883 $sk = $this->getSkin();
1884
1885 // Hook that allows last minute changes to the output page, e.g.
1886 // adding of CSS or Javascript by extensions.
1887 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
1888
1889 wfProfileIn( 'Output-skin' );
1890 $sk->outputPage();
1891 wfProfileOut( 'Output-skin' );
1892 }
1893
1894 $this->sendCacheControl();
1895 ob_end_flush();
1896 wfProfileOut( __METHOD__ );
1897 }
1898
1899 /**
1900 * Actually output something with print().
1901 *
1902 * @param $ins String: the string to output
1903 */
1904 public function out( $ins ) {
1905 print $ins;
1906 }
1907
1908 /**
1909 * Produce a "user is blocked" page.
1910 * @deprecated since 1.18
1911 */
1912 function blockedPage() {
1913 throw new UserBlockedError( $this->getUser()->mBlock );
1914 }
1915
1916 /**
1917 * Output a standard error page
1918 *
1919 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
1920 * showErrorPage( 'titlemsg', $messageObject );
1921 *
1922 * @param $title String: message key for page title
1923 * @param $msg Mixed: message key (string) for page text, or a Message object
1924 * @param $params Array: message parameters; ignored if $msg is a Message object
1925 */
1926 public function showErrorPage( $title, $msg, $params = array() ) {
1927 if ( $this->getTitle() ) {
1928 $this->mDebugtext .= 'Original title: ' . $this->getTitle()->getPrefixedText() . "\n";
1929 }
1930 $this->setPageTitle( wfMsg( $title ) );
1931 $this->setHTMLTitle( wfMsg( 'errorpagetitle' ) );
1932 $this->setRobotPolicy( 'noindex,nofollow' );
1933 $this->setArticleRelated( false );
1934 $this->enableClientCache( false );
1935 $this->mRedirect = '';
1936 $this->mBodytext = '';
1937
1938 if ( $msg instanceof Message ){
1939 $this->addHTML( $msg->parse() );
1940 } else {
1941 $this->addWikiMsgArray( $msg, $params );
1942 }
1943
1944 $this->returnToMain();
1945 }
1946
1947 /**
1948 * Output a standard permission error page
1949 *
1950 * @param $errors Array: error message keys
1951 * @param $action String: action that was denied or null if unknown
1952 */
1953 public function showPermissionsErrorPage( $errors, $action = null ) {
1954 $this->mDebugtext .= 'Original title: ' .
1955 $this->getTitle()->getPrefixedText() . "\n";
1956 $this->setPageTitle( wfMsg( 'permissionserrors' ) );
1957 $this->setHTMLTitle( wfMsg( 'permissionserrors' ) );
1958 $this->setRobotPolicy( 'noindex,nofollow' );
1959 $this->setArticleRelated( false );
1960 $this->enableClientCache( false );
1961 $this->mRedirect = '';
1962 $this->mBodytext = '';
1963 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
1964 }
1965
1966 /**
1967 * Display an error page indicating that a given version of MediaWiki is
1968 * required to use it
1969 *
1970 * @param $version Mixed: the version of MediaWiki needed to use the page
1971 */
1972 public function versionRequired( $version ) {
1973 $this->setPageTitle( wfMsg( 'versionrequired', $version ) );
1974 $this->setHTMLTitle( wfMsg( 'versionrequired', $version ) );
1975 $this->setRobotPolicy( 'noindex,nofollow' );
1976 $this->setArticleRelated( false );
1977 $this->mBodytext = '';
1978
1979 $this->addWikiMsg( 'versionrequiredtext', $version );
1980 $this->returnToMain();
1981 }
1982
1983 /**
1984 * Display an error page noting that a given permission bit is required.
1985 * @deprecated since 1.18, just throw the exception directly
1986 * @param $permission String: key required
1987 */
1988 public function permissionRequired( $permission ) {
1989 throw new PermissionsError( $permission );
1990 }
1991
1992 /**
1993 * Produce the stock "please login to use the wiki" page
1994 */
1995 public function loginToUse() {
1996 if( $this->getUser()->isLoggedIn() ) {
1997 throw new PermissionsError( 'read' );
1998 }
1999
2000 $this->setPageTitle( wfMsg( 'loginreqtitle' ) );
2001 $this->setHtmlTitle( wfMsg( 'errorpagetitle' ) );
2002 $this->setRobotPolicy( 'noindex,nofollow' );
2003 $this->setArticleRelated( false );
2004
2005 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
2006 $loginLink = Linker::linkKnown(
2007 $loginTitle,
2008 wfMsgHtml( 'loginreqlink' ),
2009 array(),
2010 array( 'returnto' => $this->getTitle()->getPrefixedText() )
2011 );
2012 $this->addHTML( wfMessage( 'loginreqpagetext' )->rawParams( $loginLink )->parse() .
2013 "\n<!--" . $this->getTitle()->getPrefixedUrl() . '-->' );
2014
2015 # Don't return to the main page if the user can't read it
2016 # otherwise we'll end up in a pointless loop
2017 $mainPage = Title::newMainPage();
2018 if( $mainPage->userCanRead() ) {
2019 $this->returnToMain( null, $mainPage );
2020 }
2021 }
2022
2023 /**
2024 * Format a list of error messages
2025 *
2026 * @param $errors Array of arrays returned by Title::getUserPermissionsErrors
2027 * @param $action String: action that was denied or null if unknown
2028 * @return String: the wikitext error-messages, formatted into a list.
2029 */
2030 public function formatPermissionsErrorMessage( $errors, $action = null ) {
2031 if ( $action == null ) {
2032 $text = wfMsgNoTrans( 'permissionserrorstext', count( $errors ) ) . "\n\n";
2033 } else {
2034 $action_desc = wfMsgNoTrans( "action-$action" );
2035 $text = wfMsgNoTrans(
2036 'permissionserrorstext-withaction',
2037 count( $errors ),
2038 $action_desc
2039 ) . "\n\n";
2040 }
2041
2042 if ( count( $errors ) > 1 ) {
2043 $text .= '<ul class="permissions-errors">' . "\n";
2044
2045 foreach( $errors as $error ) {
2046 $text .= '<li>';
2047 $text .= call_user_func_array( 'wfMsgNoTrans', $error );
2048 $text .= "</li>\n";
2049 }
2050 $text .= '</ul>';
2051 } else {
2052 $text .= "<div class=\"permissions-errors\">\n" .
2053 call_user_func_array( 'wfMsgNoTrans', reset( $errors ) ) .
2054 "\n</div>";
2055 }
2056
2057 return $text;
2058 }
2059
2060 /**
2061 * Display a page stating that the Wiki is in read-only mode,
2062 * and optionally show the source of the page that the user
2063 * was trying to edit. Should only be called (for this
2064 * purpose) after wfReadOnly() has returned true.
2065 *
2066 * For historical reasons, this function is _also_ used to
2067 * show the error message when a user tries to edit a page
2068 * they are not allowed to edit. (Unless it's because they're
2069 * blocked, then we show blockedPage() instead.) In this
2070 * case, the second parameter should be set to true and a list
2071 * of reasons supplied as the third parameter.
2072 *
2073 * @todo Needs to be split into multiple functions.
2074 *
2075 * @param $source String: source code to show (or null).
2076 * @param $protected Boolean: is this a permissions error?
2077 * @param $reasons Array: list of reasons for this error, as returned by Title::getUserPermissionsErrors().
2078 * @param $action String: action that was denied or null if unknown
2079 */
2080 public function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
2081 $this->setRobotPolicy( 'noindex,nofollow' );
2082 $this->setArticleRelated( false );
2083
2084 // If no reason is given, just supply a default "I can't let you do
2085 // that, Dave" message. Should only occur if called by legacy code.
2086 if ( $protected && empty( $reasons ) ) {
2087 $reasons[] = array( 'badaccess-group0' );
2088 }
2089
2090 if ( !empty( $reasons ) ) {
2091 // Permissions error
2092 if( $source ) {
2093 $this->setPageTitle( wfMsg( 'viewsource' ) );
2094 $this->setSubtitle(
2095 wfMsg( 'viewsourcefor', Linker::linkKnown( $this->getTitle() ) )
2096 );
2097 } else {
2098 $this->setPageTitle( wfMsg( 'badaccess' ) );
2099 }
2100 $this->addWikiText( $this->formatPermissionsErrorMessage( $reasons, $action ) );
2101 } else {
2102 // Wiki is read only
2103 throw new ReadOnlyError;
2104 }
2105
2106 // Show source, if supplied
2107 if( is_string( $source ) ) {
2108 $this->addWikiMsg( 'viewsourcetext' );
2109
2110 $pageLang = $this->getTitle()->getPageLanguage();
2111 $params = array(
2112 'id' => 'wpTextbox1',
2113 'name' => 'wpTextbox1',
2114 'cols' => $this->getUser()->getOption( 'cols' ),
2115 'rows' => $this->getUser()->getOption( 'rows' ),
2116 'readonly' => 'readonly',
2117 'lang' => $pageLang->getCode(),
2118 'dir' => $pageLang->getDir(),
2119 );
2120 $this->addHTML( Html::element( 'textarea', $params, $source ) );
2121
2122 // Show templates used by this article
2123 $article = new Article( $this->getTitle() );
2124 $templates = Linker::formatTemplates( $article->getUsedTemplates() );
2125 $this->addHTML( "<div class='templatesUsed'>
2126 $templates
2127 </div>
2128 " );
2129 }
2130
2131 # If the title doesn't exist, it's fairly pointless to print a return
2132 # link to it. After all, you just tried editing it and couldn't, so
2133 # what's there to do there?
2134 if( $this->getTitle()->exists() ) {
2135 $this->returnToMain( null, $this->getTitle() );
2136 }
2137 }
2138
2139 /**
2140 * Turn off regular page output and return an error reponse
2141 * for when rate limiting has triggered.
2142 */
2143 public function rateLimited() {
2144 throw new ThrottledError;
2145 }
2146
2147 /**
2148 * Show a warning about slave lag
2149 *
2150 * If the lag is higher than $wgSlaveLagCritical seconds,
2151 * then the warning is a bit more obvious. If the lag is
2152 * lower than $wgSlaveLagWarning, then no warning is shown.
2153 *
2154 * @param $lag Integer: slave lag
2155 */
2156 public function showLagWarning( $lag ) {
2157 global $wgSlaveLagWarning, $wgSlaveLagCritical;
2158 if( $lag >= $wgSlaveLagWarning ) {
2159 $message = $lag < $wgSlaveLagCritical
2160 ? 'lag-warn-normal'
2161 : 'lag-warn-high';
2162 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2163 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getContext()->getLang()->formatNum( $lag ) ) );
2164 }
2165 }
2166
2167 public function showFatalError( $message ) {
2168 $this->setPageTitle( wfMsg( 'internalerror' ) );
2169 $this->setRobotPolicy( 'noindex,nofollow' );
2170 $this->setArticleRelated( false );
2171 $this->enableClientCache( false );
2172 $this->mRedirect = '';
2173 $this->mBodytext = $message;
2174 }
2175
2176 public function showUnexpectedValueError( $name, $val ) {
2177 $this->showFatalError( wfMsg( 'unexpected', $name, $val ) );
2178 }
2179
2180 public function showFileCopyError( $old, $new ) {
2181 $this->showFatalError( wfMsg( 'filecopyerror', $old, $new ) );
2182 }
2183
2184 public function showFileRenameError( $old, $new ) {
2185 $this->showFatalError( wfMsg( 'filerenameerror', $old, $new ) );
2186 }
2187
2188 public function showFileDeleteError( $name ) {
2189 $this->showFatalError( wfMsg( 'filedeleteerror', $name ) );
2190 }
2191
2192 public function showFileNotFoundError( $name ) {
2193 $this->showFatalError( wfMsg( 'filenotfound', $name ) );
2194 }
2195
2196 /**
2197 * Add a "return to" link pointing to a specified title
2198 *
2199 * @param $title Title to link
2200 * @param $query String query string
2201 * @param $text String text of the link (input is not escaped)
2202 */
2203 public function addReturnTo( $title, $query = array(), $text = null ) {
2204 $this->addLink( array( 'rel' => 'next', 'href' => $title->getFullURL() ) );
2205 $link = wfMsgHtml(
2206 'returnto',
2207 Linker::link( $title, $text, array(), $query )
2208 );
2209 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2210 }
2211
2212 /**
2213 * Add a "return to" link pointing to a specified title,
2214 * or the title indicated in the request, or else the main page
2215 *
2216 * @param $unused No longer used
2217 * @param $returnto Title or String to return to
2218 * @param $returntoquery String: query string for the return to link
2219 */
2220 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2221 if ( $returnto == null ) {
2222 $returnto = $this->getRequest()->getText( 'returnto' );
2223 }
2224
2225 if ( $returntoquery == null ) {
2226 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2227 }
2228
2229 if ( $returnto === '' ) {
2230 $returnto = Title::newMainPage();
2231 }
2232
2233 if ( is_object( $returnto ) ) {
2234 $titleObj = $returnto;
2235 } else {
2236 $titleObj = Title::newFromText( $returnto );
2237 }
2238 if ( !is_object( $titleObj ) ) {
2239 $titleObj = Title::newMainPage();
2240 }
2241
2242 $this->addReturnTo( $titleObj, $returntoquery );
2243 }
2244
2245 /**
2246 * @param $sk Skin The given Skin
2247 * @param $includeStyle Boolean: unused
2248 * @return String: The doctype, opening <html>, and head element.
2249 */
2250 public function headElement( Skin $sk, $includeStyle = true ) {
2251 global $wgContLang, $wgUseTrackbacks;
2252 $userdir = $this->getLang()->getDir();
2253 $sitedir = $wgContLang->getDir();
2254
2255 if ( $sk->commonPrintStylesheet() ) {
2256 $this->addModuleStyles( 'mediawiki.legacy.wikiprintable' );
2257 }
2258
2259 $ret = Html::htmlHeader( array( 'lang' => $this->getLang()->getCode(), 'dir' => $userdir, 'class' => 'client-nojs' ) );
2260
2261 if ( $this->getHTMLTitle() == '' ) {
2262 $this->setHTMLTitle( wfMsg( 'pagetitle', $this->getPageTitle() ) );
2263 }
2264
2265 $openHead = Html::openElement( 'head' );
2266 if ( $openHead ) {
2267 # Don't bother with the newline if $head == ''
2268 $ret .= "$openHead\n";
2269 }
2270
2271 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2272
2273 $ret .= implode( "\n", array(
2274 $this->getHeadLinks( null, true ),
2275 $this->buildCssLinks(),
2276 $this->getHeadScripts(),
2277 $this->getHeadItems()
2278 ) );
2279
2280 if ( $wgUseTrackbacks && $this->isArticleRelated() ) {
2281 $ret .= $this->getTitle()->trackbackRDF();
2282 }
2283
2284 $closeHead = Html::closeElement( 'head' );
2285 if ( $closeHead ) {
2286 $ret .= "$closeHead\n";
2287 }
2288
2289 $bodyAttrs = array();
2290
2291 # Classes for LTR/RTL directionality support
2292 $bodyAttrs['class'] = "mediawiki $userdir sitedir-$sitedir";
2293
2294 if ( $this->getContext()->getLang()->capitalizeAllNouns() ) {
2295 # A <body> class is probably not the best way to do this . . .
2296 $bodyAttrs['class'] .= ' capitalize-all-nouns';
2297 }
2298 $bodyAttrs['class'] .= ' ' . $sk->getPageClasses( $this->getTitle() );
2299 $bodyAttrs['class'] .= ' skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2300
2301 $sk->addToBodyAttributes( $this, $bodyAttrs ); // Allow skins to add body attributes they need
2302 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2303
2304 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2305
2306 return $ret;
2307 }
2308
2309 /**
2310 * Add the default ResourceLoader modules to this object
2311 */
2312 private function addDefaultModules() {
2313 global $wgIncludeLegacyJavaScript, $wgUseAjax, $wgAjaxWatch, $wgEnableMWSuggest;
2314
2315 // Add base resources
2316 $this->addModules( array(
2317 'mediawiki.user',
2318 'mediawiki.util',
2319 'mediawiki.page.startup',
2320 'mediawiki.page.ready',
2321 ) );
2322 if ( $wgIncludeLegacyJavaScript ){
2323 $this->addModules( 'mediawiki.legacy.wikibits' );
2324 }
2325
2326 // Add various resources if required
2327 if ( $wgUseAjax ) {
2328 $this->addModules( 'mediawiki.legacy.ajax' );
2329
2330 wfRunHooks( 'AjaxAddScript', array( &$this ) );
2331
2332 if( $wgAjaxWatch && $this->getUser()->isLoggedIn() ) {
2333 $this->addModules( 'mediawiki.action.watch.ajax' );
2334 }
2335
2336 if ( $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2337 $this->addModules( 'mediawiki.legacy.mwsuggest' );
2338 }
2339 }
2340
2341 if ( $this->getUser()->getBoolOption( 'editsectiononrightclick' ) ) {
2342 $this->addModules( 'mediawiki.action.view.rightClickEdit' );
2343 }
2344
2345 # Crazy edit-on-double-click stuff
2346 if ( $this->isArticle() && $this->getUser()->getOption( 'editondblclick' ) ) {
2347 $this->addModules( 'mediawiki.action.view.dblClickEdit' );
2348 }
2349 }
2350
2351 /**
2352 * Get a ResourceLoader object associated with this OutputPage
2353 *
2354 * @return ResourceLoader
2355 */
2356 public function getResourceLoader() {
2357 if ( is_null( $this->mResourceLoader ) ) {
2358 $this->mResourceLoader = new ResourceLoader();
2359 }
2360 return $this->mResourceLoader;
2361 }
2362
2363 /**
2364 * TODO: Document
2365 * @param $modules Array/string with the module name(s)
2366 * @param $only String ResourceLoaderModule TYPE_ class constant
2367 * @param $useESI boolean
2368 * @param $extraQuery Array with extra query parameters to add to each request. array( param => value )
2369 * @return string html <script> and <style> tags
2370 */
2371 protected function makeResourceLoaderLink( $modules, $only, $useESI = false, array $extraQuery = array() ) {
2372 global $wgResourceLoaderUseESI, $wgResourceLoaderInlinePrivateModules;
2373
2374 if ( !count( $modules ) ) {
2375 return '';
2376 }
2377
2378 if ( count( $modules ) > 1 ) {
2379 // Remove duplicate module requests
2380 $modules = array_unique( (array) $modules );
2381 // Sort module names so requests are more uniform
2382 sort( $modules );
2383
2384 if ( ResourceLoader::inDebugMode() ) {
2385 // Recursively call us for every item
2386 $links = '';
2387 foreach ( $modules as $name ) {
2388 $links .= $this->makeResourceLoaderLink( $name, $only, $useESI );
2389 }
2390 return $links;
2391 }
2392 }
2393
2394 // Create keyed-by-group list of module objects from modules list
2395 $groups = array();
2396 $resourceLoader = $this->getResourceLoader();
2397 foreach ( (array) $modules as $name ) {
2398 $module = $resourceLoader->getModule( $name );
2399 # Check that we're allowed to include this module on this page
2400 if ( ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2401 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2402 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2403 && $only == ResourceLoaderModule::TYPE_STYLES )
2404 )
2405 {
2406 continue;
2407 }
2408
2409 $group = $module->getGroup();
2410 if ( !isset( $groups[$group] ) ) {
2411 $groups[$group] = array();
2412 }
2413 $groups[$group][$name] = $module;
2414 }
2415
2416 $links = '';
2417 foreach ( $groups as $group => $modules ) {
2418 // Special handling for user-specific groups
2419 $user = null;
2420 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2421 $user = $this->getUser()->getName();
2422 }
2423
2424 // Create a fake request based on the one we are about to make so modules return
2425 // correct timestamp and emptiness data
2426 $query = ResourceLoader::makeLoaderQuery(
2427 array(), // modules; not determined yet
2428 $this->getContext()->getLang()->getCode(),
2429 $this->getSkin()->getSkinName(),
2430 $user,
2431 null, // version; not determined yet
2432 ResourceLoader::inDebugMode(),
2433 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2434 $this->isPrintable(),
2435 $this->getRequest()->getBool( 'handheld' ),
2436 $extraQuery
2437 );
2438 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2439 // Drop modules that know they're empty
2440 foreach ( $modules as $key => $module ) {
2441 if ( $module->isKnownEmpty( $context ) ) {
2442 unset( $modules[$key] );
2443 }
2444 }
2445 // If there are no modules left, skip this group
2446 if ( $modules === array() ) {
2447 continue;
2448 }
2449
2450 // Support inlining of private modules if configured as such
2451 if ( $group === 'private' && $wgResourceLoaderInlinePrivateModules ) {
2452 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2453 $links .= Html::inlineStyle(
2454 $resourceLoader->makeModuleResponse( $context, $modules )
2455 );
2456 } else {
2457 $links .= Html::inlineScript(
2458 ResourceLoader::makeLoaderConditionalScript(
2459 $resourceLoader->makeModuleResponse( $context, $modules )
2460 )
2461 );
2462 }
2463 $links .= "\n";
2464 continue;
2465 }
2466 // Special handling for the user group; because users might change their stuff
2467 // on-wiki like user pages, or user preferences; we need to find the highest
2468 // timestamp of these user-changable modules so we can ensure cache misses on change
2469 // This should NOT be done for the site group (bug 27564) because anons get that too
2470 // and we shouldn't be putting timestamps in Squid-cached HTML
2471 $version = null;
2472 if ( $group === 'user' ) {
2473 // Get the maximum timestamp
2474 $timestamp = 1;
2475 foreach ( $modules as $module ) {
2476 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2477 }
2478 // Add a version parameter so cache will break when things change
2479 $version = wfTimestamp( TS_ISO_8601_BASIC, $timestamp );
2480 }
2481
2482 $url = ResourceLoader::makeLoaderURL(
2483 array_keys( $modules ),
2484 $this->getContext()->getLang()->getCode(),
2485 $this->getSkin()->getSkinName(),
2486 $user,
2487 $version,
2488 ResourceLoader::inDebugMode(),
2489 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2490 $this->isPrintable(),
2491 $this->getRequest()->getBool( 'handheld' ),
2492 $extraQuery
2493 );
2494 if ( $useESI && $wgResourceLoaderUseESI ) {
2495 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2496 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2497 $link = Html::inlineStyle( $esi );
2498 } else {
2499 $link = Html::inlineScript( $esi );
2500 }
2501 } else {
2502 // Automatically select style/script elements
2503 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2504 $link = Html::linkedStyle( $url );
2505 } else {
2506 $link = Html::linkedScript( $url );
2507 }
2508 }
2509
2510 if( $group == 'noscript' ){
2511 $links .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2512 } else {
2513 $links .= $link . "\n";
2514 }
2515 }
2516 return $links;
2517 }
2518
2519 /**
2520 * JS stuff to put in the <head>. This is the startup module, config
2521 * vars and modules marked with position 'top'
2522 *
2523 * @return String: HTML fragment
2524 */
2525 function getHeadScripts() {
2526 // Startup - this will immediately load jquery and mediawiki modules
2527 $scripts = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2528
2529 // Load config before anything else
2530 $scripts .= Html::inlineScript(
2531 ResourceLoader::makeLoaderConditionalScript(
2532 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2533 )
2534 );
2535
2536 // Script and Messages "only" requests marked for top inclusion
2537 // Messages should go first
2538 $scripts .= $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'top' ), ResourceLoaderModule::TYPE_MESSAGES );
2539 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'top' ), ResourceLoaderModule::TYPE_SCRIPTS );
2540
2541 // Modules requests - let the client calculate dependencies and batch requests as it likes
2542 // Only load modules that have marked themselves for loading at the top
2543 $modules = $this->getModules( true, 'top' );
2544 if ( $modules ) {
2545 $scripts .= Html::inlineScript(
2546 ResourceLoader::makeLoaderConditionalScript(
2547 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2548 )
2549 );
2550 }
2551
2552 return $scripts;
2553 }
2554
2555 /**
2556 * JS stuff to put at the bottom of the <body>: modules marked with position 'bottom',
2557 * legacy scripts ($this->mScripts), user preferences, site JS and user JS
2558 *
2559 * @return string
2560 */
2561 function getBottomScripts() {
2562 global $wgUseSiteJs, $wgAllowUserJs;
2563
2564 // Script and Messages "only" requests marked for bottom inclusion
2565 // Messages should go first
2566 $scripts = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ), ResourceLoaderModule::TYPE_MESSAGES );
2567 $scripts .= $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ), ResourceLoaderModule::TYPE_SCRIPTS );
2568
2569 // Modules requests - let the client calculate dependencies and batch requests as it likes
2570 // Only load modules that have marked themselves for loading at the bottom
2571 $modules = $this->getModules( true, 'bottom' );
2572 if ( $modules ) {
2573 $scripts .= Html::inlineScript(
2574 ResourceLoader::makeLoaderConditionalScript(
2575 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2576 )
2577 );
2578 }
2579
2580 // Legacy Scripts
2581 $scripts .= "\n" . $this->mScripts;
2582
2583 $userScripts = array( 'user.options', 'user.tokens' );
2584
2585 // Add site JS if enabled
2586 if ( $wgUseSiteJs ) {
2587 $scripts .= $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS );
2588 if( $this->getUser()->isLoggedIn() ){
2589 $userScripts[] = 'user.groups';
2590 }
2591 }
2592
2593 // Add user JS if enabled
2594 if ( $wgAllowUserJs && $this->getUser()->isLoggedIn() ) {
2595 if( $this->getTitle() && $this->getTitle()->isJsSubpage() && $this->userCanPreview() ) {
2596 # XXX: additional security check/prompt?
2597 // We're on a preview of a JS subpage
2598 // Exclude this page from the user module in case it's in there (bug 26283)
2599 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
2600 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
2601 );
2602 // Load the previewed JS
2603 $scripts .= Html::inlineScript( "\n" . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
2604 } else {
2605 // Include the user module normally
2606 // We can't do $userScripts[] = 'user'; because the user module would end up
2607 // being wrapped in a closure, so load it raw like 'site'
2608 $scripts .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS );
2609 }
2610 }
2611 $scripts .= $this->makeResourceLoaderLink( $userScripts, ResourceLoaderModule::TYPE_COMBINED );
2612
2613 return $scripts;
2614 }
2615
2616 /**
2617 * Add one or more variables to be set in mw.config in JavaScript.
2618 *
2619 * @param $key {String|Array} Key or array of key/value pars.
2620 * @param $value {Mixed} Value of the configuration variable.
2621 */
2622 public function addJsConfigVars( $keys, $value ) {
2623 if ( is_array( $keys ) ) {
2624 foreach ( $keys as $key => $value ) {
2625 $this->mJsConfigVars[$key] = $value;
2626 }
2627 return;
2628 }
2629
2630 $this->mJsConfigVars[$keys] = $value;
2631 }
2632
2633
2634 /**
2635 * Get an array containing the variables to be set in mw.config in JavaScript.
2636 *
2637 * Do not add things here which can be evaluated in ResourceLoaderStartupScript
2638 * - in other words, page-independent/site-wide variables (without state).
2639 * You will only be adding bloat to the html page and causing page caches to
2640 * have to be purged on configuration changes.
2641 */
2642 protected function getJSVars() {
2643 global $wgUseAjax, $wgEnableMWSuggest;
2644
2645 $title = $this->getTitle();
2646 $ns = $title->getNamespace();
2647 $nsname = MWNamespace::exists( $ns ) ? MWNamespace::getCanonicalName( $ns ) : $title->getNsText();
2648 if ( $ns == NS_SPECIAL ) {
2649 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
2650 } else {
2651 $canonicalName = false; # bug 21115
2652 }
2653
2654 $vars = array(
2655 'wgCanonicalNamespace' => $nsname,
2656 'wgCanonicalSpecialPageName' => $canonicalName,
2657 'wgNamespaceNumber' => $title->getNamespace(),
2658 'wgPageName' => $title->getPrefixedDBKey(),
2659 'wgTitle' => $title->getText(),
2660 'wgCurRevisionId' => $title->getLatestRevID(),
2661 'wgArticleId' => $title->getArticleId(),
2662 'wgIsArticle' => $this->isArticle(),
2663 'wgAction' => $this->getRequest()->getText( 'action', 'view' ),
2664 'wgUserName' => $this->getUser()->isAnon() ? null : $this->getUser()->getName(),
2665 'wgUserGroups' => $this->getUser()->getEffectiveGroups(),
2666 'wgCategories' => $this->getCategories(),
2667 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
2668 );
2669 $lang = $this->getTitle()->getPageLanguage();
2670 if ( $lang->hasVariants() ) {
2671 $vars['wgUserVariant'] = $lang->getPreferredVariant();
2672 }
2673 foreach ( $title->getRestrictionTypes() as $type ) {
2674 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
2675 }
2676 if ( $wgUseAjax && $wgEnableMWSuggest && !$this->getUser()->getOption( 'disablesuggest', false ) ) {
2677 $vars['wgSearchNamespaces'] = SearchEngine::userNamespaces( $this->getUser() );
2678 }
2679 if ( $title->isMainPage() ) {
2680 $vars['wgIsMainPage'] = true;
2681 }
2682
2683 // Allow extensions to add their custom variables to the mw.config map.
2684 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
2685 // page-dependant but site-wide (without state).
2686 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
2687 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, &$this ) );
2688
2689 // Merge in variables from addJsConfigVars last
2690 return array_merge( $vars, $this->mJsConfigVars );
2691 }
2692
2693 /**
2694 * To make it harder for someone to slip a user a fake
2695 * user-JavaScript or user-CSS preview, a random token
2696 * is associated with the login session. If it's not
2697 * passed back with the preview request, we won't render
2698 * the code.
2699 *
2700 * @return bool
2701 */
2702 public function userCanPreview() {
2703 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
2704 || !$this->getRequest()->wasPosted()
2705 || !$this->getUser()->matchEditToken(
2706 $this->getRequest()->getVal( 'wpEditToken' ) )
2707 ) {
2708 return false;
2709 }
2710 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
2711 return false;
2712 }
2713
2714 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
2715 }
2716
2717 /**
2718 * @param $unused Unused
2719 * @param $addContentType bool
2720 *
2721 * @return string HTML tag links to be put in the header.
2722 */
2723 public function getHeadLinks( $unused = null, $addContentType = false ) {
2724 global $wgUniversalEditButton, $wgFavicon, $wgAppleTouchIcon, $wgEnableAPI,
2725 $wgSitename, $wgVersion, $wgHtml5, $wgMimeType,
2726 $wgFeed, $wgOverrideSiteFeed, $wgAdvertisedFeedTypes,
2727 $wgDisableLangConversion, $wgCanonicalLanguageLinks,
2728 $wgRightsPage, $wgRightsUrl;
2729
2730 $tags = array();
2731
2732 if ( $addContentType ) {
2733 if ( $wgHtml5 ) {
2734 # More succinct than <meta http-equiv=Content-Type>, has the
2735 # same effect
2736 $tags[] = Html::element( 'meta', array( 'charset' => 'UTF-8' ) );
2737 } else {
2738 $tags[] = Html::element( 'meta', array(
2739 'http-equiv' => 'Content-Type',
2740 'content' => "$wgMimeType; charset=UTF-8"
2741 ) );
2742 $tags[] = Html::element( 'meta', array( // bug 15835
2743 'http-equiv' => 'Content-Style-Type',
2744 'content' => 'text/css'
2745 ) );
2746 }
2747 }
2748
2749 $tags[] = Html::element( 'meta', array(
2750 'name' => 'generator',
2751 'content' => "MediaWiki $wgVersion",
2752 ) );
2753
2754 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
2755 if( $p !== 'index,follow' ) {
2756 // http://www.robotstxt.org/wc/meta-user.html
2757 // Only show if it's different from the default robots policy
2758 $tags[] = Html::element( 'meta', array(
2759 'name' => 'robots',
2760 'content' => $p,
2761 ) );
2762 }
2763
2764 if ( count( $this->mKeywords ) > 0 ) {
2765 $strip = array(
2766 "/<.*?" . ">/" => '',
2767 "/_/" => ' '
2768 );
2769 $tags[] = Html::element( 'meta', array(
2770 'name' => 'keywords',
2771 'content' => preg_replace(
2772 array_keys( $strip ),
2773 array_values( $strip ),
2774 implode( ',', $this->mKeywords )
2775 )
2776 ) );
2777 }
2778
2779 foreach ( $this->mMetatags as $tag ) {
2780 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
2781 $a = 'http-equiv';
2782 $tag[0] = substr( $tag[0], 5 );
2783 } else {
2784 $a = 'name';
2785 }
2786 $tags[] = Html::element( 'meta',
2787 array(
2788 $a => $tag[0],
2789 'content' => $tag[1]
2790 )
2791 );
2792 }
2793
2794 foreach ( $this->mLinktags as $tag ) {
2795 $tags[] = Html::element( 'link', $tag );
2796 }
2797
2798 # Universal edit button
2799 if ( $wgUniversalEditButton ) {
2800 if ( $this->isArticleRelated() && $this->getTitle() && $this->getTitle()->quickUserCan( 'edit' )
2801 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create' ) ) ) {
2802 // Original UniversalEditButton
2803 $msg = wfMsg( 'edit' );
2804 $tags[] = Html::element( 'link', array(
2805 'rel' => 'alternate',
2806 'type' => 'application/x-wiki',
2807 'title' => $msg,
2808 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2809 ) );
2810 // Alternate edit link
2811 $tags[] = Html::element( 'link', array(
2812 'rel' => 'edit',
2813 'title' => $msg,
2814 'href' => $this->getTitle()->getLocalURL( 'action=edit' )
2815 ) );
2816 }
2817 }
2818
2819 # Generally the order of the favicon and apple-touch-icon links
2820 # should not matter, but Konqueror (3.5.9 at least) incorrectly
2821 # uses whichever one appears later in the HTML source. Make sure
2822 # apple-touch-icon is specified first to avoid this.
2823 if ( $wgAppleTouchIcon !== false ) {
2824 $tags[] = Html::element( 'link', array( 'rel' => 'apple-touch-icon', 'href' => $wgAppleTouchIcon ) );
2825 }
2826
2827 if ( $wgFavicon !== false ) {
2828 $tags[] = Html::element( 'link', array( 'rel' => 'shortcut icon', 'href' => $wgFavicon ) );
2829 }
2830
2831 # OpenSearch description link
2832 $tags[] = Html::element( 'link', array(
2833 'rel' => 'search',
2834 'type' => 'application/opensearchdescription+xml',
2835 'href' => wfScript( 'opensearch_desc' ),
2836 'title' => wfMsgForContent( 'opensearch-desc' ),
2837 ) );
2838
2839 if ( $wgEnableAPI ) {
2840 # Real Simple Discovery link, provides auto-discovery information
2841 # for the MediaWiki API (and potentially additional custom API
2842 # support such as WordPress or Twitter-compatible APIs for a
2843 # blogging extension, etc)
2844 $tags[] = Html::element( 'link', array(
2845 'rel' => 'EditURI',
2846 'type' => 'application/rsd+xml',
2847 // Output a protocol-relative URL here if $wgServer is protocol-relative
2848 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
2849 'href' => wfExpandUrl( wfAppendQuery( wfScript( 'api' ), array( 'action' => 'rsd' ) ), PROTO_RELATIVE ),
2850 ) );
2851 }
2852
2853 $lang = $this->getTitle()->getPageLanguage();
2854
2855 # Language variants
2856 if ( !$wgDisableLangConversion && $wgCanonicalLanguageLinks
2857 && $lang->hasVariants() ) {
2858
2859 $urlvar = $lang->getURLVariant();
2860
2861 if ( !$urlvar ) {
2862 $variants = $lang->getVariants();
2863 foreach ( $variants as $_v ) {
2864 $tags[] = Html::element( 'link', array(
2865 'rel' => 'alternate',
2866 'hreflang' => $_v,
2867 'href' => $this->getTitle()->getLocalURL( '', $_v ) )
2868 );
2869 }
2870 } else {
2871 $tags[] = Html::element( 'link', array(
2872 'rel' => 'canonical',
2873 'href' => $this->getTitle()->getCanonicalUrl()
2874 ) );
2875 }
2876 }
2877
2878 # Copyright
2879 $copyright = '';
2880 if ( $wgRightsPage ) {
2881 $copy = Title::newFromText( $wgRightsPage );
2882
2883 if ( $copy ) {
2884 $copyright = $copy->getLocalURL();
2885 }
2886 }
2887
2888 if ( !$copyright && $wgRightsUrl ) {
2889 $copyright = $wgRightsUrl;
2890 }
2891
2892 if ( $copyright ) {
2893 $tags[] = Html::element( 'link', array(
2894 'rel' => 'copyright',
2895 'href' => $copyright )
2896 );
2897 }
2898
2899 # Feeds
2900 if ( $wgFeed ) {
2901 foreach( $this->getSyndicationLinks() as $format => $link ) {
2902 # Use the page name for the title. In principle, this could
2903 # lead to issues with having the same name for different feeds
2904 # corresponding to the same page, but we can't avoid that at
2905 # this low a level.
2906
2907 $tags[] = $this->feedLink(
2908 $format,
2909 $link,
2910 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
2911 wfMsg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )
2912 );
2913 }
2914
2915 # Recent changes feed should appear on every page (except recentchanges,
2916 # that would be redundant). Put it after the per-page feed to avoid
2917 # changing existing behavior. It's still available, probably via a
2918 # menu in your browser. Some sites might have a different feed they'd
2919 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
2920 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
2921 # If so, use it instead.
2922
2923 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
2924
2925 if ( $wgOverrideSiteFeed ) {
2926 foreach ( $wgOverrideSiteFeed as $type => $feedUrl ) {
2927 // Note, this->feedLink escapes the url.
2928 $tags[] = $this->feedLink(
2929 $type,
2930 $feedUrl,
2931 wfMsg( "site-{$type}-feed", $wgSitename )
2932 );
2933 }
2934 } elseif ( $this->getTitle()->getPrefixedText() != $rctitle->getPrefixedText() ) {
2935 foreach ( $wgAdvertisedFeedTypes as $format ) {
2936 $tags[] = $this->feedLink(
2937 $format,
2938 $rctitle->getLocalURL( "feed={$format}" ),
2939 wfMsg( "site-{$format}-feed", $wgSitename ) # For grep: 'site-rss-feed', 'site-atom-feed'.
2940 );
2941 }
2942 }
2943 }
2944 return implode( "\n", $tags );
2945 }
2946
2947 /**
2948 * Generate a <link rel/> for a feed.
2949 *
2950 * @param $type String: feed type
2951 * @param $url String: URL to the feed
2952 * @param $text String: value of the "title" attribute
2953 * @return String: HTML fragment
2954 */
2955 private function feedLink( $type, $url, $text ) {
2956 return Html::element( 'link', array(
2957 'rel' => 'alternate',
2958 'type' => "application/$type+xml",
2959 'title' => $text,
2960 'href' => $url )
2961 );
2962 }
2963
2964 /**
2965 * Add a local or specified stylesheet, with the given media options.
2966 * Meant primarily for internal use...
2967 *
2968 * @param $style String: URL to the file
2969 * @param $media String: to specify a media type, 'screen', 'printable', 'handheld' or any.
2970 * @param $condition String: for IE conditional comments, specifying an IE version
2971 * @param $dir String: set to 'rtl' or 'ltr' for direction-specific sheets
2972 */
2973 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
2974 $options = array();
2975 // Even though we expect the media type to be lowercase, but here we
2976 // force it to lowercase to be safe.
2977 if( $media ) {
2978 $options['media'] = $media;
2979 }
2980 if( $condition ) {
2981 $options['condition'] = $condition;
2982 }
2983 if( $dir ) {
2984 $options['dir'] = $dir;
2985 }
2986 $this->styles[$style] = $options;
2987 }
2988
2989 /**
2990 * Adds inline CSS styles
2991 * @param $style_css Mixed: inline CSS
2992 * @param $flip String: Set to 'flip' to flip the CSS if needed
2993 */
2994 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
2995 if( $flip === 'flip' && $this->getLang()->isRTL() ) {
2996 # If wanted, and the interface is right-to-left, flip the CSS
2997 $style_css = CSSJanus::transform( $style_css, true, false );
2998 }
2999 $this->mInlineStyles .= Html::inlineStyle( $style_css );
3000 }
3001
3002 /**
3003 * Build a set of <link>s for the stylesheets specified in the $this->styles array.
3004 * These will be applied to various media & IE conditionals.
3005 *
3006 * @return string
3007 */
3008 public function buildCssLinks() {
3009 global $wgUseSiteCss, $wgAllowUserCss, $wgAllowUserCssPrefs;
3010
3011 $this->getSkin()->setupSkinUserCss( $this );
3012
3013 // Add ResourceLoader styles
3014 // Split the styles into four groups
3015 $styles = array( 'other' => array(), 'user' => array(), 'site' => array(), 'private' => array(), 'noscript' => array() );
3016 $otherTags = ''; // Tags to append after the normal <link> tags
3017 $resourceLoader = $this->getResourceLoader();
3018
3019 $moduleStyles = $this->getModuleStyles();
3020
3021 // Per-site custom styles
3022 if ( $wgUseSiteCss ) {
3023 $moduleStyles[] = 'site';
3024 $moduleStyles[] = 'noscript';
3025 if( $this->getUser()->isLoggedIn() ){
3026 $moduleStyles[] = 'user.groups';
3027 }
3028 }
3029
3030 // Per-user custom styles
3031 if ( $wgAllowUserCss ) {
3032 if ( $this->getTitle()->isCssSubpage() && $this->userCanPreview() ) {
3033 // We're on a preview of a CSS subpage
3034 // Exclude this page from the user module in case it's in there (bug 26283)
3035 $otherTags .= $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3036 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3037 );
3038 // Load the previewed CSS
3039 $otherTags .= Html::inlineStyle( $this->getRequest()->getText( 'wpTextbox1' ) );
3040 } else {
3041 // Load the user styles normally
3042 $moduleStyles[] = 'user';
3043 }
3044 }
3045
3046 // Per-user preference styles
3047 if ( $wgAllowUserCssPrefs ) {
3048 $moduleStyles[] = 'user.options';
3049 }
3050
3051 foreach ( $moduleStyles as $name ) {
3052 $group = $resourceLoader->getModule( $name )->getGroup();
3053 // Modules in groups named "other" or anything different than "user", "site" or "private"
3054 // will be placed in the "other" group
3055 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3056 }
3057
3058 // We want site, private and user styles to override dynamically added styles from modules, but we want
3059 // dynamically added styles to override statically added styles from other modules. So the order
3060 // has to be other, dynamic, site, private, user
3061 // Add statically added styles for other modules
3062 $ret = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3063 // Add normal styles added through addStyle()/addInlineStyle() here
3064 $ret .= implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3065 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3066 // We use a <meta> tag with a made-up name for this because that's valid HTML
3067 $ret .= Html::element( 'meta', array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ) ) . "\n";
3068
3069 // Add site, private and user styles
3070 // 'private' at present only contains user.options, so put that before 'user'
3071 // Any future private modules will likely have a similar user-specific character
3072 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3073 $ret .= $this->makeResourceLoaderLink( $styles[$group],
3074 ResourceLoaderModule::TYPE_STYLES
3075 );
3076 }
3077
3078 // Add stuff in $otherTags (previewed user CSS if applicable)
3079 $ret .= $otherTags;
3080 return $ret;
3081 }
3082
3083 /**
3084 * @return Array
3085 */
3086 public function buildCssLinksArray() {
3087 $links = array();
3088
3089 // Add any extension CSS
3090 foreach ( $this->mExtStyles as $url ) {
3091 $this->addStyle( $url );
3092 }
3093 $this->mExtStyles = array();
3094
3095 foreach( $this->styles as $file => $options ) {
3096 $link = $this->styleLink( $file, $options );
3097 if( $link ) {
3098 $links[$file] = $link;
3099 }
3100 }
3101 return $links;
3102 }
3103
3104 /**
3105 * Generate \<link\> tags for stylesheets
3106 *
3107 * @param $style String: URL to the file
3108 * @param $options Array: option, can contain 'condition', 'dir', 'media'
3109 * keys
3110 * @return String: HTML fragment
3111 */
3112 protected function styleLink( $style, $options ) {
3113 if( isset( $options['dir'] ) ) {
3114 if( $this->getLang()->getDir() != $options['dir'] ) {
3115 return '';
3116 }
3117 }
3118
3119 if( isset( $options['media'] ) ) {
3120 $media = self::transformCssMedia( $options['media'] );
3121 if( is_null( $media ) ) {
3122 return '';
3123 }
3124 } else {
3125 $media = 'all';
3126 }
3127
3128 if( substr( $style, 0, 1 ) == '/' ||
3129 substr( $style, 0, 5 ) == 'http:' ||
3130 substr( $style, 0, 6 ) == 'https:' ) {
3131 $url = $style;
3132 } else {
3133 global $wgStylePath, $wgStyleVersion;
3134 $url = $wgStylePath . '/' . $style . '?' . $wgStyleVersion;
3135 }
3136
3137 $link = Html::linkedStyle( $url, $media );
3138
3139 if( isset( $options['condition'] ) ) {
3140 $condition = htmlspecialchars( $options['condition'] );
3141 $link = "<!--[if $condition]>$link<![endif]-->";
3142 }
3143 return $link;
3144 }
3145
3146 /**
3147 * Transform "media" attribute based on request parameters
3148 *
3149 * @param $media String: current value of the "media" attribute
3150 * @return String: modified value of the "media" attribute
3151 */
3152 public static function transformCssMedia( $media ) {
3153 global $wgRequest, $wgHandheldForIPhone;
3154
3155 // Switch in on-screen display for media testing
3156 $switches = array(
3157 'printable' => 'print',
3158 'handheld' => 'handheld',
3159 );
3160 foreach( $switches as $switch => $targetMedia ) {
3161 if( $wgRequest->getBool( $switch ) ) {
3162 if( $media == $targetMedia ) {
3163 $media = '';
3164 } elseif( $media == 'screen' ) {
3165 return null;
3166 }
3167 }
3168 }
3169
3170 // Expand longer media queries as iPhone doesn't grok 'handheld'
3171 if( $wgHandheldForIPhone ) {
3172 $mediaAliases = array(
3173 'screen' => 'screen and (min-device-width: 481px)',
3174 'handheld' => 'handheld, only screen and (max-device-width: 480px)',
3175 );
3176
3177 if( isset( $mediaAliases[$media] ) ) {
3178 $media = $mediaAliases[$media];
3179 }
3180 }
3181
3182 return $media;
3183 }
3184
3185 /**
3186 * Add a wikitext-formatted message to the output.
3187 * This is equivalent to:
3188 *
3189 * $wgOut->addWikiText( wfMsgNoTrans( ... ) )
3190 */
3191 public function addWikiMsg( /*...*/ ) {
3192 $args = func_get_args();
3193 $name = array_shift( $args );
3194 $this->addWikiMsgArray( $name, $args );
3195 }
3196
3197 /**
3198 * Add a wikitext-formatted message to the output.
3199 * Like addWikiMsg() except the parameters are taken as an array
3200 * instead of a variable argument list.
3201 *
3202 * $options is passed through to wfMsgExt(), see that function for details.
3203 *
3204 * @param $name string
3205 * @param $args array
3206 * @param $options array
3207 */
3208 public function addWikiMsgArray( $name, $args, $options = array() ) {
3209 $options[] = 'parse';
3210 $text = wfMsgExt( $name, $options, $args );
3211 $this->addHTML( $text );
3212 }
3213
3214 /**
3215 * This function takes a number of message/argument specifications, wraps them in
3216 * some overall structure, and then parses the result and adds it to the output.
3217 *
3218 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3219 * on. The subsequent arguments may either be strings, in which case they are the
3220 * message names, or arrays, in which case the first element is the message name,
3221 * and subsequent elements are the parameters to that message.
3222 *
3223 * The special named parameter 'options' in a message specification array is passed
3224 * through to the $options parameter of wfMsgExt().
3225 *
3226 * Don't use this for messages that are not in users interface language.
3227 *
3228 * For example:
3229 *
3230 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3231 *
3232 * Is equivalent to:
3233 *
3234 * $wgOut->addWikiText( "<div class='error'>\n" . wfMsgNoTrans( 'some-error' ) . "\n</div>" );
3235 *
3236 * The newline after opening div is needed in some wikitext. See bug 19226.
3237 *
3238 * @param $wrap string
3239 */
3240 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3241 $msgSpecs = func_get_args();
3242 array_shift( $msgSpecs );
3243 $msgSpecs = array_values( $msgSpecs );
3244 $s = $wrap;
3245 foreach ( $msgSpecs as $n => $spec ) {
3246 $options = array();
3247 if ( is_array( $spec ) ) {
3248 $args = $spec;
3249 $name = array_shift( $args );
3250 if ( isset( $args['options'] ) ) {
3251 $options = $args['options'];
3252 unset( $args['options'] );
3253 }
3254 } else {
3255 $args = array();
3256 $name = $spec;
3257 }
3258 $s = str_replace( '$' . ( $n + 1 ), wfMsgExt( $name, $options, $args ), $s );
3259 }
3260 $this->addWikiText( $s );
3261 }
3262
3263 /**
3264 * Include jQuery core. Use this to avoid loading it multiple times
3265 * before we get a usable script loader.
3266 *
3267 * @param $modules Array: list of jQuery modules which should be loaded
3268 * @return Array: the list of modules which were not loaded.
3269 * @since 1.16
3270 * @deprecated since 1.17
3271 */
3272 public function includeJQuery( $modules = array() ) {
3273 return array();
3274 }
3275
3276 }