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