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