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