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