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