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