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