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