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