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