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