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