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