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