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