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