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