Merge "ApiMessage: Improve documentation"
[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 int 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( 'match=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 = 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 $request = $this->getRequest();
2006 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2007 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2008 wfDebug( __METHOD__ . ": found $cookieName\n" );
2009 return true;
2010 }
2011 }
2012 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2013 return false;
2014 }
2015
2016 /**
2017 * Add an HTTP header that will influence on the cache
2018 *
2019 * @param string $header Header name
2020 * @param string[]|null $option Options for the Key header. See
2021 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2022 * for the list of valid options.
2023 */
2024 public function addVaryHeader( $header, array $option = null ) {
2025 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2026 $this->mVaryHeader[$header] = array();
2027 }
2028 if ( !is_array( $option ) ) {
2029 $option = array();
2030 }
2031 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2032 }
2033
2034 /**
2035 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2036 * such as Accept-Encoding or Cookie
2037 *
2038 * @return string
2039 */
2040 public function getVaryHeader() {
2041 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2042 }
2043
2044 /**
2045 * Get a complete Key header
2046 *
2047 * @return string
2048 */
2049 public function getKeyHeader() {
2050 $cvCookies = $this->getCacheVaryCookies();
2051
2052 $cookiesOption = array();
2053 foreach ( $cvCookies as $cookieName ) {
2054 $cookiesOption[] = 'param=' . $cookieName;
2055 }
2056 $this->addVaryHeader( 'Cookie', $cookiesOption );
2057
2058 $headers = array();
2059 foreach ( $this->mVaryHeader as $header => $option ) {
2060 $newheader = $header;
2061 if ( is_array( $option ) && count( $option ) > 0 ) {
2062 $newheader .= ';' . implode( ';', $option );
2063 }
2064 $headers[] = $newheader;
2065 }
2066 $key = 'Key: ' . implode( ',', $headers );
2067
2068 return $key;
2069 }
2070
2071 /**
2072 * T23672: Add Accept-Language to Vary and Key headers
2073 * if there's no 'variant' parameter existed in GET.
2074 *
2075 * For example:
2076 * /w/index.php?title=Main_page should always be served; but
2077 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2078 */
2079 function addAcceptLanguage() {
2080 $title = $this->getTitle();
2081 if ( !$title instanceof Title ) {
2082 return;
2083 }
2084
2085 $lang = $title->getPageLanguage();
2086 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2087 $variants = $lang->getVariants();
2088 $aloption = array();
2089 foreach ( $variants as $variant ) {
2090 if ( $variant === $lang->getCode() ) {
2091 continue;
2092 } else {
2093 $aloption[] = 'substr=' . $variant;
2094
2095 // IE and some other browsers use BCP 47 standards in
2096 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2097 // We should handle these too.
2098 $variantBCP47 = wfBCP47( $variant );
2099 if ( $variantBCP47 !== $variant ) {
2100 $aloption[] = 'substr=' . $variantBCP47;
2101 }
2102 }
2103 }
2104 $this->addVaryHeader( 'Accept-Language', $aloption );
2105 }
2106 }
2107
2108 /**
2109 * Set a flag which will cause an X-Frame-Options header appropriate for
2110 * edit pages to be sent. The header value is controlled by
2111 * $wgEditPageFrameOptions.
2112 *
2113 * This is the default for special pages. If you display a CSRF-protected
2114 * form on an ordinary view page, then you need to call this function.
2115 *
2116 * @param bool $enable
2117 */
2118 public function preventClickjacking( $enable = true ) {
2119 $this->mPreventClickjacking = $enable;
2120 }
2121
2122 /**
2123 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2124 * This can be called from pages which do not contain any CSRF-protected
2125 * HTML form.
2126 */
2127 public function allowClickjacking() {
2128 $this->mPreventClickjacking = false;
2129 }
2130
2131 /**
2132 * Get the prevent-clickjacking flag
2133 *
2134 * @since 1.24
2135 * @return bool
2136 */
2137 public function getPreventClickjacking() {
2138 return $this->mPreventClickjacking;
2139 }
2140
2141 /**
2142 * Get the X-Frame-Options header value (without the name part), or false
2143 * if there isn't one. This is used by Skin to determine whether to enable
2144 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2145 *
2146 * @return string
2147 */
2148 public function getFrameOptions() {
2149 $config = $this->getConfig();
2150 if ( $config->get( 'BreakFrames' ) ) {
2151 return 'DENY';
2152 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2153 return $config->get( 'EditPageFrameOptions' );
2154 }
2155 return false;
2156 }
2157
2158 /**
2159 * Send cache control HTTP headers
2160 */
2161 public function sendCacheControl() {
2162 $response = $this->getRequest()->response();
2163 $config = $this->getConfig();
2164 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2165 $response->header( "ETag: $this->mETag" );
2166 }
2167
2168 $this->addVaryHeader( 'Cookie' );
2169 $this->addAcceptLanguage();
2170
2171 # don't serve compressed data to clients who can't handle it
2172 # maintain different caches for logged-in users and non-logged in ones
2173 $response->header( $this->getVaryHeader() );
2174
2175 if ( $config->get( 'UseKeyHeader' ) ) {
2176 $response->header( $this->getKeyHeader() );
2177 }
2178
2179 if ( $this->mEnableClientCache ) {
2180 if (
2181 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2182 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2183 ) {
2184 if ( $config->get( 'UseESI' ) ) {
2185 # We'll purge the proxy cache explicitly, but require end user agents
2186 # to revalidate against the proxy on each visit.
2187 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2188 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2189 # start with a shorter timeout for initial testing
2190 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2191 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2192 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2193 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2194 } else {
2195 # We'll purge the proxy cache for anons explicitly, but require end user agents
2196 # to revalidate against the proxy on each visit.
2197 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2198 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2199 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2200 # start with a shorter timeout for initial testing
2201 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2202 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2203 . ', must-revalidate, max-age=0' );
2204 }
2205 } else {
2206 # We do want clients to cache if they can, but they *must* check for updates
2207 # on revisiting the page.
2208 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2209 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2210 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2211 }
2212 if ( $this->mLastModified ) {
2213 $response->header( "Last-Modified: {$this->mLastModified}" );
2214 }
2215 } else {
2216 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2217
2218 # In general, the absence of a last modified header should be enough to prevent
2219 # the client from using its cache. We send a few other things just to make sure.
2220 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2221 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2222 $response->header( 'Pragma: no-cache' );
2223 }
2224 }
2225
2226 /**
2227 * Finally, all the text has been munged and accumulated into
2228 * the object, let's actually output it:
2229 */
2230 public function output() {
2231 if ( $this->mDoNothing ) {
2232 return;
2233 }
2234
2235 $response = $this->getRequest()->response();
2236 $config = $this->getConfig();
2237
2238 if ( $this->mRedirect != '' ) {
2239 # Standards require redirect URLs to be absolute
2240 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2241
2242 $redirect = $this->mRedirect;
2243 $code = $this->mRedirectCode;
2244
2245 if ( Hooks::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2246 if ( $code == '301' || $code == '303' ) {
2247 if ( !$config->get( 'DebugRedirects' ) ) {
2248 $response->statusHeader( $code );
2249 }
2250 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2251 }
2252 if ( $config->get( 'VaryOnXFP' ) ) {
2253 $this->addVaryHeader( 'X-Forwarded-Proto' );
2254 }
2255 $this->sendCacheControl();
2256
2257 $response->header( "Content-Type: text/html; charset=utf-8" );
2258 if ( $config->get( 'DebugRedirects' ) ) {
2259 $url = htmlspecialchars( $redirect );
2260 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2261 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2262 print "</body>\n</html>\n";
2263 } else {
2264 $response->header( 'Location: ' . $redirect );
2265 }
2266 }
2267
2268 return;
2269 } elseif ( $this->mStatusCode ) {
2270 $response->statusHeader( $this->mStatusCode );
2271 }
2272
2273 # Buffer output; final headers may depend on later processing
2274 ob_start();
2275
2276 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2277 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2278
2279 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2280 // jQuery etc. can work correctly.
2281 $response->header( 'X-UA-Compatible: IE=Edge' );
2282
2283 // Prevent framing, if requested
2284 $frameOptions = $this->getFrameOptions();
2285 if ( $frameOptions ) {
2286 $response->header( "X-Frame-Options: $frameOptions" );
2287 }
2288
2289 if ( $this->mArticleBodyOnly ) {
2290 echo $this->mBodytext;
2291 } else {
2292 $sk = $this->getSkin();
2293 // add skin specific modules
2294 $modules = $sk->getDefaultModules();
2295
2296 // Enforce various default modules for all skins
2297 $coreModules = array(
2298 // Keep this list as small as possible
2299 'site',
2300 'mediawiki.page.startup',
2301 'mediawiki.user',
2302 );
2303
2304 // Support for high-density display images if enabled
2305 if ( $config->get( 'ResponsiveImages' ) ) {
2306 $coreModules[] = 'mediawiki.hidpi';
2307 }
2308
2309 $this->addModules( $coreModules );
2310 foreach ( $modules as $group ) {
2311 $this->addModules( $group );
2312 }
2313 MWDebug::addModules( $this );
2314
2315 // Hook that allows last minute changes to the output page, e.g.
2316 // adding of CSS or Javascript by extensions.
2317 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2318
2319 $sk->outputPage();
2320 }
2321
2322 // This hook allows last minute changes to final overall output by modifying output buffer
2323 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2324
2325 $this->sendCacheControl();
2326
2327 ob_end_flush();
2328
2329 }
2330
2331 /**
2332 * Actually output something with print.
2333 *
2334 * @param string $ins The string to output
2335 * @deprecated since 1.22 Use echo yourself.
2336 */
2337 public function out( $ins ) {
2338 wfDeprecated( __METHOD__, '1.22' );
2339 print $ins;
2340 }
2341
2342 /**
2343 * Produce a "user is blocked" page.
2344 * @deprecated since 1.18
2345 */
2346 function blockedPage() {
2347 throw new UserBlockedError( $this->getUser()->mBlock );
2348 }
2349
2350 /**
2351 * Prepare this object to display an error page; disable caching and
2352 * indexing, clear the current text and redirect, set the page's title
2353 * and optionally an custom HTML title (content of the "<title>" tag).
2354 *
2355 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2356 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2357 * optional, if not passed the "<title>" attribute will be
2358 * based on $pageTitle
2359 */
2360 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2361 $this->setPageTitle( $pageTitle );
2362 if ( $htmlTitle !== false ) {
2363 $this->setHTMLTitle( $htmlTitle );
2364 }
2365 $this->setRobotPolicy( 'noindex,nofollow' );
2366 $this->setArticleRelated( false );
2367 $this->enableClientCache( false );
2368 $this->mRedirect = '';
2369 $this->clearSubtitle();
2370 $this->clearHTML();
2371 }
2372
2373 /**
2374 * Output a standard error page
2375 *
2376 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2377 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2378 * showErrorPage( 'titlemsg', $messageObject );
2379 * showErrorPage( $titleMessageObject, $messageObject );
2380 *
2381 * @param string|Message $title Message key (string) for page title, or a Message object
2382 * @param string|Message $msg Message key (string) for page text, or a Message object
2383 * @param array $params Message parameters; ignored if $msg is a Message object
2384 */
2385 public function showErrorPage( $title, $msg, $params = array() ) {
2386 if ( !$title instanceof Message ) {
2387 $title = $this->msg( $title );
2388 }
2389
2390 $this->prepareErrorPage( $title );
2391
2392 if ( $msg instanceof Message ) {
2393 if ( $params !== array() ) {
2394 trigger_error( 'Argument ignored: $params. The message parameters argument '
2395 . 'is discarded when the $msg argument is a Message object instead of '
2396 . 'a string.', E_USER_NOTICE );
2397 }
2398 $this->addHTML( $msg->parseAsBlock() );
2399 } else {
2400 $this->addWikiMsgArray( $msg, $params );
2401 }
2402
2403 $this->returnToMain();
2404 }
2405
2406 /**
2407 * Output a standard permission error page
2408 *
2409 * @param array $errors Error message keys
2410 * @param string $action Action that was denied or null if unknown
2411 */
2412 public function showPermissionsErrorPage( array $errors, $action = null ) {
2413 // For some action (read, edit, create and upload), display a "login to do this action"
2414 // error if all of the following conditions are met:
2415 // 1. the user is not logged in
2416 // 2. the only error is insufficient permissions (i.e. no block or something else)
2417 // 3. the error can be avoided simply by logging in
2418 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2419 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2420 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2421 && ( User::groupHasPermission( 'user', $action )
2422 || User::groupHasPermission( 'autoconfirmed', $action ) )
2423 ) {
2424 $displayReturnto = null;
2425
2426 # Due to bug 32276, if a user does not have read permissions,
2427 # $this->getTitle() will just give Special:Badtitle, which is
2428 # not especially useful as a returnto parameter. Use the title
2429 # from the request instead, if there was one.
2430 $request = $this->getRequest();
2431 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2432 if ( $action == 'edit' ) {
2433 $msg = 'whitelistedittext';
2434 $displayReturnto = $returnto;
2435 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2436 $msg = 'nocreatetext';
2437 } elseif ( $action == 'upload' ) {
2438 $msg = 'uploadnologintext';
2439 } else { # Read
2440 $msg = 'loginreqpagetext';
2441 $displayReturnto = Title::newMainPage();
2442 }
2443
2444 $query = array();
2445
2446 if ( $returnto ) {
2447 $query['returnto'] = $returnto->getPrefixedText();
2448
2449 if ( !$request->wasPosted() ) {
2450 $returntoquery = $request->getValues();
2451 unset( $returntoquery['title'] );
2452 unset( $returntoquery['returnto'] );
2453 unset( $returntoquery['returntoquery'] );
2454 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2455 }
2456 }
2457 $loginLink = Linker::linkKnown(
2458 SpecialPage::getTitleFor( 'Userlogin' ),
2459 $this->msg( 'loginreqlink' )->escaped(),
2460 array(),
2461 $query
2462 );
2463
2464 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2465 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2466
2467 # Don't return to a page the user can't read otherwise
2468 # we'll end up in a pointless loop
2469 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2470 $this->returnToMain( null, $displayReturnto );
2471 }
2472 } else {
2473 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2474 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2475 }
2476 }
2477
2478 /**
2479 * Display an error page indicating that a given version of MediaWiki is
2480 * required to use it
2481 *
2482 * @param mixed $version The version of MediaWiki needed to use the page
2483 */
2484 public function versionRequired( $version ) {
2485 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2486
2487 $this->addWikiMsg( 'versionrequiredtext', $version );
2488 $this->returnToMain();
2489 }
2490
2491 /**
2492 * Display an error page noting that a given permission bit is required.
2493 * @deprecated since 1.18, just throw the exception directly
2494 * @param string $permission Key required
2495 * @throws PermissionsError
2496 */
2497 public function permissionRequired( $permission ) {
2498 throw new PermissionsError( $permission );
2499 }
2500
2501 /**
2502 * Produce the stock "please login to use the wiki" page
2503 *
2504 * @deprecated since 1.19; throw the exception directly
2505 */
2506 public function loginToUse() {
2507 throw new PermissionsError( 'read' );
2508 }
2509
2510 /**
2511 * Format a list of error messages
2512 *
2513 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2514 * @param string $action Action that was denied or null if unknown
2515 * @return string The wikitext error-messages, formatted into a list.
2516 */
2517 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2518 if ( $action == null ) {
2519 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2520 } else {
2521 $action_desc = $this->msg( "action-$action" )->plain();
2522 $text = $this->msg(
2523 'permissionserrorstext-withaction',
2524 count( $errors ),
2525 $action_desc
2526 )->plain() . "\n\n";
2527 }
2528
2529 if ( count( $errors ) > 1 ) {
2530 $text .= '<ul class="permissions-errors">' . "\n";
2531
2532 foreach ( $errors as $error ) {
2533 $text .= '<li>';
2534 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2535 $text .= "</li>\n";
2536 }
2537 $text .= '</ul>';
2538 } else {
2539 $text .= "<div class=\"permissions-errors\">\n" .
2540 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2541 "\n</div>";
2542 }
2543
2544 return $text;
2545 }
2546
2547 /**
2548 * Display a page stating that the Wiki is in read-only mode.
2549 * Should only be called after wfReadOnly() has returned true.
2550 *
2551 * Historically, this function was used to show the source of the page that the user
2552 * was trying to edit and _also_ permissions error messages. The relevant code was
2553 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2554 *
2555 * @deprecated since 1.25; throw the exception directly
2556 * @throws ReadOnlyError
2557 */
2558 public function readOnlyPage() {
2559 if ( func_num_args() > 0 ) {
2560 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2561 }
2562
2563 throw new ReadOnlyError;
2564 }
2565
2566 /**
2567 * Turn off regular page output and return an error response
2568 * for when rate limiting has triggered.
2569 *
2570 * @deprecated since 1.25; throw the exception directly
2571 */
2572 public function rateLimited() {
2573 wfDeprecated( __METHOD__, '1.25' );
2574 throw new ThrottledError;
2575 }
2576
2577 /**
2578 * Show a warning about slave lag
2579 *
2580 * If the lag is higher than $wgSlaveLagCritical seconds,
2581 * then the warning is a bit more obvious. If the lag is
2582 * lower than $wgSlaveLagWarning, then no warning is shown.
2583 *
2584 * @param int $lag Slave lag
2585 */
2586 public function showLagWarning( $lag ) {
2587 $config = $this->getConfig();
2588 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2589 $message = $lag < $config->get( 'SlaveLagCritical' )
2590 ? 'lag-warn-normal'
2591 : 'lag-warn-high';
2592 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2593 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2594 }
2595 }
2596
2597 public function showFatalError( $message ) {
2598 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2599
2600 $this->addHTML( $message );
2601 }
2602
2603 public function showUnexpectedValueError( $name, $val ) {
2604 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2605 }
2606
2607 public function showFileCopyError( $old, $new ) {
2608 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2609 }
2610
2611 public function showFileRenameError( $old, $new ) {
2612 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2613 }
2614
2615 public function showFileDeleteError( $name ) {
2616 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2617 }
2618
2619 public function showFileNotFoundError( $name ) {
2620 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2621 }
2622
2623 /**
2624 * Add a "return to" link pointing to a specified title
2625 *
2626 * @param Title $title Title to link
2627 * @param array $query Query string parameters
2628 * @param string $text Text of the link (input is not escaped)
2629 * @param array $options Options array to pass to Linker
2630 */
2631 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2632 $link = $this->msg( 'returnto' )->rawParams(
2633 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2634 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2635 }
2636
2637 /**
2638 * Add a "return to" link pointing to a specified title,
2639 * or the title indicated in the request, or else the main page
2640 *
2641 * @param mixed $unused
2642 * @param Title|string $returnto Title or String to return to
2643 * @param string $returntoquery Query string for the return to link
2644 */
2645 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2646 if ( $returnto == null ) {
2647 $returnto = $this->getRequest()->getText( 'returnto' );
2648 }
2649
2650 if ( $returntoquery == null ) {
2651 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2652 }
2653
2654 if ( $returnto === '' ) {
2655 $returnto = Title::newMainPage();
2656 }
2657
2658 if ( is_object( $returnto ) ) {
2659 $titleObj = $returnto;
2660 } else {
2661 $titleObj = Title::newFromText( $returnto );
2662 }
2663 if ( !is_object( $titleObj ) ) {
2664 $titleObj = Title::newMainPage();
2665 }
2666
2667 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2668 }
2669
2670 /**
2671 * @param Skin $sk The given Skin
2672 * @param bool $includeStyle Unused
2673 * @return string The doctype, opening "<html>", and head element.
2674 */
2675 public function headElement( Skin $sk, $includeStyle = true ) {
2676 global $wgContLang;
2677
2678 $userdir = $this->getLanguage()->getDir();
2679 $sitedir = $wgContLang->getDir();
2680
2681 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2682
2683 if ( $this->getHTMLTitle() == '' ) {
2684 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2685 }
2686
2687 $openHead = Html::openElement( 'head' );
2688 if ( $openHead ) {
2689 # Don't bother with the newline if $head == ''
2690 $ret .= "$openHead\n";
2691 }
2692
2693 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2694 // Add <meta charset="UTF-8">
2695 // This should be before <title> since it defines the charset used by
2696 // text including the text inside <title>.
2697 // The spec recommends defining XHTML5's charset using the XML declaration
2698 // instead of meta.
2699 // Our XML declaration is output by Html::htmlHeader.
2700 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2701 // http://www.whatwg.org/html/semantics.html#charset
2702 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2703 }
2704
2705 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2706 $ret .= $this->getInlineHeadScripts() . "\n";
2707 $ret .= $this->buildCssLinks() . "\n";
2708 $ret .= $this->getExternalHeadScripts() . "\n";
2709
2710 foreach ( $this->getHeadLinksArray() as $item ) {
2711 $ret .= $item . "\n";
2712 }
2713
2714 foreach ( $this->mHeadItems as $item ) {
2715 $ret .= $item . "\n";
2716 }
2717
2718 $closeHead = Html::closeElement( 'head' );
2719 if ( $closeHead ) {
2720 $ret .= "$closeHead\n";
2721 }
2722
2723 $bodyClasses = array();
2724 $bodyClasses[] = 'mediawiki';
2725
2726 # Classes for LTR/RTL directionality support
2727 $bodyClasses[] = $userdir;
2728 $bodyClasses[] = "sitedir-$sitedir";
2729
2730 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2731 # A <body> class is probably not the best way to do this . . .
2732 $bodyClasses[] = 'capitalize-all-nouns';
2733 }
2734
2735 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2736 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2737 $bodyClasses[] =
2738 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2739
2740 $bodyAttrs = array();
2741 // While the implode() is not strictly needed, it's used for backwards compatibility
2742 // (this used to be built as a string and hooks likely still expect that).
2743 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2744
2745 // Allow skins and extensions to add body attributes they need
2746 $sk->addToBodyAttributes( $this, $bodyAttrs );
2747 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2748
2749 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2750
2751 return $ret;
2752 }
2753
2754 /**
2755 * Get a ResourceLoader object associated with this OutputPage
2756 *
2757 * @return ResourceLoader
2758 */
2759 public function getResourceLoader() {
2760 if ( is_null( $this->mResourceLoader ) ) {
2761 $this->mResourceLoader = new ResourceLoader(
2762 $this->getConfig(),
2763 LoggerFactory::getInstance( 'resourceloader' )
2764 );
2765 }
2766 return $this->mResourceLoader;
2767 }
2768
2769 /**
2770 * Construct neccecary html and loader preset states to load modules on a page.
2771 *
2772 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2773 *
2774 * @param array|string $modules One or more module names
2775 * @param string $only ResourceLoaderModule TYPE_ class constant
2776 * @param array $extraQuery [optional] Array with extra query parameters for the request
2777 * @return array A list of HTML strings and array of client loader preset states
2778 */
2779 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2780 $modules = (array)$modules;
2781
2782 $links = array(
2783 // List of html strings
2784 'html' => array(),
2785 // Associative array of module names and their states
2786 'states' => array(),
2787 );
2788
2789 if ( !count( $modules ) ) {
2790 return $links;
2791 }
2792
2793 if ( count( $modules ) > 1 ) {
2794 // Remove duplicate module requests
2795 $modules = array_unique( $modules );
2796 // Sort module names so requests are more uniform
2797 sort( $modules );
2798
2799 if ( ResourceLoader::inDebugMode() ) {
2800 // Recursively call us for every item
2801 foreach ( $modules as $name ) {
2802 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2803 $links['html'] = array_merge( $links['html'], $link['html'] );
2804 $links['states'] += $link['states'];
2805 }
2806 return $links;
2807 }
2808 }
2809
2810 if ( !is_null( $this->mTarget ) ) {
2811 $extraQuery['target'] = $this->mTarget;
2812 }
2813
2814 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2815 $sortedModules = array();
2816 $resourceLoader = $this->getResourceLoader();
2817 foreach ( $modules as $name ) {
2818 $module = $resourceLoader->getModule( $name );
2819 # Check that we're allowed to include this module on this page
2820 if ( !$module
2821 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2822 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2823 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2824 && $only == ResourceLoaderModule::TYPE_STYLES )
2825 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2826 && $only == ResourceLoaderModule::TYPE_COMBINED )
2827 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2828 ) {
2829 continue;
2830 }
2831
2832 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2833 }
2834
2835 foreach ( $sortedModules as $source => $groups ) {
2836 foreach ( $groups as $group => $grpModules ) {
2837 // Special handling for user-specific groups
2838 $user = null;
2839 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2840 $user = $this->getUser()->getName();
2841 }
2842
2843 // Create a fake request based on the one we are about to make so modules return
2844 // correct timestamp and emptiness data
2845 $query = ResourceLoader::makeLoaderQuery(
2846 array(), // modules; not determined yet
2847 $this->getLanguage()->getCode(),
2848 $this->getSkin()->getSkinName(),
2849 $user,
2850 null, // version; not determined yet
2851 ResourceLoader::inDebugMode(),
2852 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2853 $this->isPrintable(),
2854 $this->getRequest()->getBool( 'handheld' ),
2855 $extraQuery
2856 );
2857 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2858
2859 // Extract modules that know they're empty and see if we have one or more
2860 // raw modules
2861 $isRaw = false;
2862 foreach ( $grpModules as $key => $module ) {
2863 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2864 // If we're only getting the styles, we don't need to do anything for empty modules.
2865 if ( $module->isKnownEmpty( $context ) ) {
2866 unset( $grpModules[$key] );
2867 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2868 $links['states'][$key] = 'ready';
2869 }
2870 }
2871
2872 $isRaw |= $module->isRaw();
2873 }
2874
2875 // If there are no non-empty modules, skip this group
2876 if ( count( $grpModules ) === 0 ) {
2877 continue;
2878 }
2879
2880 // Inline private modules. These can't be loaded through load.php for security
2881 // reasons, see bug 34907. Note that these modules should be loaded from
2882 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2883 // properly use them as dependencies (bug 30914)
2884 if ( $group === 'private' ) {
2885 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2886 $links['html'][] = Html::inlineStyle(
2887 $resourceLoader->makeModuleResponse( $context, $grpModules )
2888 );
2889 } else {
2890 $links['html'][] = ResourceLoader::makeInlineScript(
2891 $resourceLoader->makeModuleResponse( $context, $grpModules )
2892 );
2893 }
2894 continue;
2895 }
2896
2897 // Special handling for the user group; because users might change their stuff
2898 // on-wiki like user pages, or user preferences; we need to find the highest
2899 // timestamp of these user-changeable modules so we can ensure cache misses on change
2900 // This should NOT be done for the site group (bug 27564) because anons get that too
2901 // and we shouldn't be putting timestamps in Squid-cached HTML
2902 $version = null;
2903 if ( $group === 'user' ) {
2904 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2905 }
2906
2907 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2908 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2909 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2910
2911 // Automatically select style/script elements
2912 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2913 $link = Html::linkedStyle( $url );
2914 } else {
2915 if ( $context->getRaw() || $isRaw ) {
2916 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2917 $link = Html::element( 'script', array(
2918 // In SpecialJavaScriptTest, QUnit must load synchronous
2919 'async' => !isset( $extraQuery['sync'] ),
2920 'src' => $url
2921 ) );
2922 } else {
2923 $link = ResourceLoader::makeInlineScript(
2924 Xml::encodeJsCall( 'mw.loader.load', array( $url ) )
2925 );
2926 }
2927
2928 // For modules requested directly in the html via <script> or mw.loader.load
2929 // tell mw.loader they are being loading to prevent duplicate requests.
2930 foreach ( $grpModules as $key => $module ) {
2931 // Don't output state=loading for the startup module.
2932 if ( $key !== 'startup' ) {
2933 $links['states'][$key] = 'loading';
2934 }
2935 }
2936 }
2937
2938 if ( $group == 'noscript' ) {
2939 $links['html'][] = Html::rawElement( 'noscript', array(), $link );
2940 } else {
2941 $links['html'][] = $link;
2942 }
2943 }
2944 }
2945
2946 return $links;
2947 }
2948
2949 /**
2950 * Build html output from an array of links from makeResourceLoaderLink.
2951 * @param array $links
2952 * @return string HTML
2953 */
2954 protected static function getHtmlFromLoaderLinks( array $links ) {
2955 $html = array();
2956 $states = array();
2957 foreach ( $links as $link ) {
2958 if ( !is_array( $link ) ) {
2959 $html[] = $link;
2960 } else {
2961 $html = array_merge( $html, $link['html'] );
2962 $states += $link['states'];
2963 }
2964 }
2965 // Filter out empty values
2966 $html = array_filter( $html, 'strlen' );
2967
2968 if ( count( $states ) ) {
2969 array_unshift( $html, ResourceLoader::makeInlineScript(
2970 ResourceLoader::makeLoaderStateScript( $states )
2971 ) );
2972 }
2973
2974 return WrappedString::join( "\n", $html );
2975 }
2976
2977 /**
2978 * JS stuff to put in the "<head>". This is the startup module, config
2979 * vars and modules marked with position 'top'
2980 *
2981 * @return string HTML fragment
2982 */
2983 function getHeadScripts() {
2984 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2985 }
2986
2987 /**
2988 * <script src="..."> tags for "<head>". This is the startup module
2989 * and other modules marked with position 'top'.
2990 *
2991 * @return string HTML fragment
2992 */
2993 function getExternalHeadScripts() {
2994 $links = array();
2995
2996 // Startup - this provides the client with the module
2997 // manifest and loads jquery and mediawiki base modules
2998 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS );
2999
3000 return self::getHtmlFromLoaderLinks( $links );
3001 }
3002
3003 /**
3004 * <script>...</script> tags to put in "<head>".
3005 *
3006 * @return string HTML fragment
3007 */
3008 function getInlineHeadScripts() {
3009 $links = array();
3010
3011 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
3012 // Must be done synchronously on every page to avoid flashes of wrong content.
3013 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
3014 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
3015 // For the performance benefit of the majority, this is added unconditionally here and is
3016 // then fixed up by the startup module for unsupported browsers.
3017 $links[] = Html::inlineScript(
3018 'document.documentElement.className = document.documentElement.className'
3019 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3020 );
3021
3022 // Load config before anything else
3023 $links[] = ResourceLoader::makeInlineScript(
3024 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
3025 );
3026
3027 // Load embeddable private modules before any loader links
3028 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3029 // in mw.loader.implement() calls and deferred until mw.user is available
3030 $embedScripts = array( 'user.options' );
3031 $links[] = $this->makeResourceLoaderLink(
3032 $embedScripts,
3033 ResourceLoaderModule::TYPE_COMBINED
3034 );
3035 // Separate user.tokens as otherwise caching will be allowed (T84960)
3036 $links[] = $this->makeResourceLoaderLink(
3037 'user.tokens',
3038 ResourceLoaderModule::TYPE_COMBINED
3039 );
3040
3041 // Modules requests - let the client calculate dependencies and batch requests as it likes
3042 // Only load modules that have marked themselves for loading at the top
3043 $modules = $this->getModules( true, 'top' );
3044 if ( $modules ) {
3045 $links[] = ResourceLoader::makeInlineScript(
3046 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3047 );
3048 }
3049
3050 // "Scripts only" modules marked for top inclusion
3051 $links[] = $this->makeResourceLoaderLink(
3052 $this->getModuleScripts( true, 'top' ),
3053 ResourceLoaderModule::TYPE_SCRIPTS
3054 );
3055
3056 return self::getHtmlFromLoaderLinks( $links );
3057 }
3058
3059 /**
3060 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3061 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3062 * site JS, and user JS.
3063 *
3064 * @param bool $unused Previously used to let this method change its output based
3065 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3066 * @return string
3067 */
3068 function getScriptsForBottomQueue( $unused = null ) {
3069 // Scripts "only" requests marked for bottom inclusion
3070 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3071 $links = array();
3072
3073 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3074 ResourceLoaderModule::TYPE_SCRIPTS
3075 );
3076
3077 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3078 ResourceLoaderModule::TYPE_STYLES
3079 );
3080
3081 // Modules requests - let the client calculate dependencies and batch requests as it likes
3082 // Only load modules that have marked themselves for loading at the bottom
3083 $modules = $this->getModules( true, 'bottom' );
3084 if ( $modules ) {
3085 $links[] = ResourceLoader::makeInlineScript(
3086 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3087 );
3088 }
3089
3090 // Legacy Scripts
3091 $links[] = $this->mScripts;
3092
3093 // Add user JS if enabled
3094 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3095 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3096 if ( $this->getConfig()->get( 'AllowUserJs' )
3097 && $this->getUser()->isLoggedIn()
3098 && $this->getTitle()
3099 && $this->getTitle()->isJsSubpage()
3100 && $this->userCanPreview()
3101 ) {
3102 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3103 // and include the draft contents as a raw script instead.
3104 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3105 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3106 );
3107 // Load the previewed JS
3108 $links[] = ResourceLoader::makeInlineScript(
3109 Xml::encodeJsCall( 'mw.loader.using', array(
3110 array( 'user', 'site' ),
3111 new XmlJsCode(
3112 'function () {'
3113 . Xml::encodeJsCall( '$.globalEval', array(
3114 $this->getRequest()->getText( 'wpTextbox1' )
3115 ) )
3116 . '}'
3117 )
3118 ) )
3119 );
3120
3121 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3122 // asynchronously and may arrive *after* the inline script here. So the previewed code
3123 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3124 // Similarly, when previewing ./common.js and the user module does arrive first,
3125 // it will arrive without common.js and the inline script runs after.
3126 // Thus running common after the excluded subpage.
3127 } else {
3128 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3129 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3130 }
3131
3132 // Group JS is only enabled if site JS is enabled.
3133 $links[] = $this->makeResourceLoaderLink(
3134 'user.groups',
3135 ResourceLoaderModule::TYPE_COMBINED
3136 );
3137
3138 return self::getHtmlFromLoaderLinks( $links );
3139 }
3140
3141 /**
3142 * JS stuff to put at the bottom of the "<body>"
3143 * @return string
3144 */
3145 function getBottomScripts() {
3146 // In case the skin wants to add bottom CSS
3147 $this->getSkin()->setupSkinUserCss( $this );
3148
3149 return $this->getScriptsForBottomQueue();
3150 }
3151
3152 /**
3153 * Get the javascript config vars to include on this page
3154 *
3155 * @return array Array of javascript config vars
3156 * @since 1.23
3157 */
3158 public function getJsConfigVars() {
3159 return $this->mJsConfigVars;
3160 }
3161
3162 /**
3163 * Add one or more variables to be set in mw.config in JavaScript
3164 *
3165 * @param string|array $keys Key or array of key/value pairs
3166 * @param mixed $value [optional] Value of the configuration variable
3167 */
3168 public function addJsConfigVars( $keys, $value = null ) {
3169 if ( is_array( $keys ) ) {
3170 foreach ( $keys as $key => $value ) {
3171 $this->mJsConfigVars[$key] = $value;
3172 }
3173 return;
3174 }
3175
3176 $this->mJsConfigVars[$keys] = $value;
3177 }
3178
3179 /**
3180 * Get an array containing the variables to be set in mw.config in JavaScript.
3181 *
3182 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3183 * - in other words, page-independent/site-wide variables (without state).
3184 * You will only be adding bloat to the html page and causing page caches to
3185 * have to be purged on configuration changes.
3186 * @return array
3187 */
3188 public function getJSVars() {
3189 global $wgContLang;
3190
3191 $curRevisionId = 0;
3192 $articleId = 0;
3193 $canonicalSpecialPageName = false; # bug 21115
3194
3195 $title = $this->getTitle();
3196 $ns = $title->getNamespace();
3197 $canonicalNamespace = MWNamespace::exists( $ns )
3198 ? MWNamespace::getCanonicalName( $ns )
3199 : $title->getNsText();
3200
3201 $sk = $this->getSkin();
3202 // Get the relevant title so that AJAX features can use the correct page name
3203 // when making API requests from certain special pages (bug 34972).
3204 $relevantTitle = $sk->getRelevantTitle();
3205 $relevantUser = $sk->getRelevantUser();
3206
3207 if ( $ns == NS_SPECIAL ) {
3208 list( $canonicalSpecialPageName, /*...*/ ) =
3209 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3210 } elseif ( $this->canUseWikiPage() ) {
3211 $wikiPage = $this->getWikiPage();
3212 $curRevisionId = $wikiPage->getLatest();
3213 $articleId = $wikiPage->getId();
3214 }
3215
3216 $lang = $title->getPageLanguage();
3217
3218 // Pre-process information
3219 $separatorTransTable = $lang->separatorTransformTable();
3220 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3221 $compactSeparatorTransTable = array(
3222 implode( "\t", array_keys( $separatorTransTable ) ),
3223 implode( "\t", $separatorTransTable ),
3224 );
3225 $digitTransTable = $lang->digitTransformTable();
3226 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3227 $compactDigitTransTable = array(
3228 implode( "\t", array_keys( $digitTransTable ) ),
3229 implode( "\t", $digitTransTable ),
3230 );
3231
3232 $user = $this->getUser();
3233
3234 $vars = array(
3235 'wgCanonicalNamespace' => $canonicalNamespace,
3236 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3237 'wgNamespaceNumber' => $title->getNamespace(),
3238 'wgPageName' => $title->getPrefixedDBkey(),
3239 'wgTitle' => $title->getText(),
3240 'wgCurRevisionId' => $curRevisionId,
3241 'wgRevisionId' => (int)$this->getRevisionId(),
3242 'wgArticleId' => $articleId,
3243 'wgIsArticle' => $this->isArticle(),
3244 'wgIsRedirect' => $title->isRedirect(),
3245 'wgAction' => Action::getActionName( $this->getContext() ),
3246 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3247 'wgUserGroups' => $user->getEffectiveGroups(),
3248 'wgCategories' => $this->getCategories(),
3249 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3250 'wgPageContentLanguage' => $lang->getCode(),
3251 'wgPageContentModel' => $title->getContentModel(),
3252 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3253 'wgDigitTransformTable' => $compactDigitTransTable,
3254 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3255 'wgMonthNames' => $lang->getMonthNamesArray(),
3256 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3257 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3258 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3259 );
3260
3261 if ( $user->isLoggedIn() ) {
3262 $vars['wgUserId'] = $user->getId();
3263 $vars['wgUserEditCount'] = $user->getEditCount();
3264 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3265 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3266 // Get the revision ID of the oldest new message on the user's talk
3267 // page. This can be used for constructing new message alerts on
3268 // the client side.
3269 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3270 }
3271
3272 if ( $wgContLang->hasVariants() ) {
3273 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3274 }
3275 // Same test as SkinTemplate
3276 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3277 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3278
3279 foreach ( $title->getRestrictionTypes() as $type ) {
3280 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3281 }
3282
3283 if ( $title->isMainPage() ) {
3284 $vars['wgIsMainPage'] = true;
3285 }
3286
3287 if ( $this->mRedirectedFrom ) {
3288 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3289 }
3290
3291 if ( $relevantUser ) {
3292 $vars['wgRelevantUserName'] = $relevantUser->getName();
3293 }
3294
3295 // Allow extensions to add their custom variables to the mw.config map.
3296 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3297 // page-dependant but site-wide (without state).
3298 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3299 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3300
3301 // Merge in variables from addJsConfigVars last
3302 return array_merge( $vars, $this->getJsConfigVars() );
3303 }
3304
3305 /**
3306 * To make it harder for someone to slip a user a fake
3307 * user-JavaScript or user-CSS preview, a random token
3308 * is associated with the login session. If it's not
3309 * passed back with the preview request, we won't render
3310 * the code.
3311 *
3312 * @return bool
3313 */
3314 public function userCanPreview() {
3315 $request = $this->getRequest();
3316 if ( $request->getVal( 'action' ) !== 'submit' || !$request->wasPosted() ) {
3317 return false;
3318 }
3319
3320 $user = $this->getUser();
3321 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3322 return false;
3323 }
3324
3325 $title = $this->getTitle();
3326 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3327 return false;
3328 }
3329 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3330 // Don't execute another user's CSS or JS on preview (T85855)
3331 return false;
3332 }
3333
3334 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3335 if ( count( $errors ) !== 0 ) {
3336 return false;
3337 }
3338
3339 return true;
3340 }
3341
3342 /**
3343 * @return array Array in format "link name or number => 'link html'".
3344 */
3345 public function getHeadLinksArray() {
3346 global $wgVersion;
3347
3348 $tags = array();
3349 $config = $this->getConfig();
3350
3351 $canonicalUrl = $this->mCanonicalUrl;
3352
3353 $tags['meta-generator'] = Html::element( 'meta', array(
3354 'name' => 'generator',
3355 'content' => "MediaWiki $wgVersion",
3356 ) );
3357
3358 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3359 $tags['meta-referrer'] = Html::element( 'meta', array(
3360 'name' => 'referrer',
3361 'content' => $config->get( 'ReferrerPolicy' )
3362 ) );
3363 }
3364
3365 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3366 if ( $p !== 'index,follow' ) {
3367 // http://www.robotstxt.org/wc/meta-user.html
3368 // Only show if it's different from the default robots policy
3369 $tags['meta-robots'] = Html::element( 'meta', array(
3370 'name' => 'robots',
3371 'content' => $p,
3372 ) );
3373 }
3374
3375 foreach ( $this->mMetatags as $tag ) {
3376 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3377 $a = 'http-equiv';
3378 $tag[0] = substr( $tag[0], 5 );
3379 } else {
3380 $a = 'name';
3381 }
3382 $tagName = "meta-{$tag[0]}";
3383 if ( isset( $tags[$tagName] ) ) {
3384 $tagName .= $tag[1];
3385 }
3386 $tags[$tagName] = Html::element( 'meta',
3387 array(
3388 $a => $tag[0],
3389 'content' => $tag[1]
3390 )
3391 );
3392 }
3393
3394 foreach ( $this->mLinktags as $tag ) {
3395 $tags[] = Html::element( 'link', $tag );
3396 }
3397
3398 # Universal edit button
3399 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3400 $user = $this->getUser();
3401 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3402 && ( $this->getTitle()->exists() ||
3403 $this->getTitle()->quickUserCan( 'create', $user ) )
3404 ) {
3405 // Original UniversalEditButton
3406 $msg = $this->msg( 'edit' )->text();
3407 $tags['universal-edit-button'] = Html::element( 'link', array(
3408 'rel' => 'alternate',
3409 'type' => 'application/x-wiki',
3410 'title' => $msg,
3411 'href' => $this->getTitle()->getEditURL(),
3412 ) );
3413 // Alternate edit link
3414 $tags['alternative-edit'] = Html::element( 'link', array(
3415 'rel' => 'edit',
3416 'title' => $msg,
3417 'href' => $this->getTitle()->getEditURL(),
3418 ) );
3419 }
3420 }
3421
3422 # Generally the order of the favicon and apple-touch-icon links
3423 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3424 # uses whichever one appears later in the HTML source. Make sure
3425 # apple-touch-icon is specified first to avoid this.
3426 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3427 $tags['apple-touch-icon'] = Html::element( 'link', array(
3428 'rel' => 'apple-touch-icon',
3429 'href' => $config->get( 'AppleTouchIcon' )
3430 ) );
3431 }
3432
3433 if ( $config->get( 'Favicon' ) !== false ) {
3434 $tags['favicon'] = Html::element( 'link', array(
3435 'rel' => 'shortcut icon',
3436 'href' => $config->get( 'Favicon' )
3437 ) );
3438 }
3439
3440 # OpenSearch description link
3441 $tags['opensearch'] = Html::element( 'link', array(
3442 'rel' => 'search',
3443 'type' => 'application/opensearchdescription+xml',
3444 'href' => wfScript( 'opensearch_desc' ),
3445 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3446 ) );
3447
3448 if ( $config->get( 'EnableAPI' ) ) {
3449 # Real Simple Discovery link, provides auto-discovery information
3450 # for the MediaWiki API (and potentially additional custom API
3451 # support such as WordPress or Twitter-compatible APIs for a
3452 # blogging extension, etc)
3453 $tags['rsd'] = Html::element( 'link', array(
3454 'rel' => 'EditURI',
3455 'type' => 'application/rsd+xml',
3456 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3457 // Whether RSD accepts relative or protocol-relative URLs is completely
3458 // undocumented, though.
3459 'href' => wfExpandUrl( wfAppendQuery(
3460 wfScript( 'api' ),
3461 array( 'action' => 'rsd' ) ),
3462 PROTO_RELATIVE
3463 ),
3464 ) );
3465 }
3466
3467 # Language variants
3468 if ( !$config->get( 'DisableLangConversion' ) ) {
3469 $lang = $this->getTitle()->getPageLanguage();
3470 if ( $lang->hasVariants() ) {
3471 $variants = $lang->getVariants();
3472 foreach ( $variants as $variant ) {
3473 $tags["variant-$variant"] = Html::element( 'link', array(
3474 'rel' => 'alternate',
3475 'hreflang' => wfBCP47( $variant ),
3476 'href' => $this->getTitle()->getLocalURL(
3477 array( 'variant' => $variant ) )
3478 )
3479 );
3480 }
3481 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3482 $tags["variant-x-default"] = Html::element( 'link', array(
3483 'rel' => 'alternate',
3484 'hreflang' => 'x-default',
3485 'href' => $this->getTitle()->getLocalURL() ) );
3486 }
3487 }
3488
3489 # Copyright
3490 if ( $this->copyrightUrl !== null ) {
3491 $copyright = $this->copyrightUrl;
3492 } else {
3493 $copyright = '';
3494 if ( $config->get( 'RightsPage' ) ) {
3495 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3496
3497 if ( $copy ) {
3498 $copyright = $copy->getLocalURL();
3499 }
3500 }
3501
3502 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3503 $copyright = $config->get( 'RightsUrl' );
3504 }
3505 }
3506
3507 if ( $copyright ) {
3508 $tags['copyright'] = Html::element( 'link', array(
3509 'rel' => 'copyright',
3510 'href' => $copyright )
3511 );
3512 }
3513
3514 # Feeds
3515 if ( $config->get( 'Feed' ) ) {
3516 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3517 # Use the page name for the title. In principle, this could
3518 # lead to issues with having the same name for different feeds
3519 # corresponding to the same page, but we can't avoid that at
3520 # this low a level.
3521
3522 $tags[] = $this->feedLink(
3523 $format,
3524 $link,
3525 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3526 $this->msg(
3527 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3528 )->text()
3529 );
3530 }
3531
3532 # Recent changes feed should appear on every page (except recentchanges,
3533 # that would be redundant). Put it after the per-page feed to avoid
3534 # changing existing behavior. It's still available, probably via a
3535 # menu in your browser. Some sites might have a different feed they'd
3536 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3537 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3538 # If so, use it instead.
3539 $sitename = $config->get( 'Sitename' );
3540 if ( $config->get( 'OverrideSiteFeed' ) ) {
3541 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3542 // Note, this->feedLink escapes the url.
3543 $tags[] = $this->feedLink(
3544 $type,
3545 $feedUrl,
3546 $this->msg( "site-{$type}-feed", $sitename )->text()
3547 );
3548 }
3549 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3550 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3551 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3552 $tags[] = $this->feedLink(
3553 $format,
3554 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3555 # For grep: 'site-rss-feed', 'site-atom-feed'
3556 $this->msg( "site-{$format}-feed", $sitename )->text()
3557 );
3558 }
3559 }
3560 }
3561
3562 # Canonical URL
3563 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3564 if ( $canonicalUrl !== false ) {
3565 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3566 } else {
3567 if ( $this->isArticleRelated() ) {
3568 // This affects all requests where "setArticleRelated" is true. This is
3569 // typically all requests that show content (query title, curid, oldid, diff),
3570 // and all wikipage actions (edit, delete, purge, info, history etc.).
3571 // It does not apply to File pages and Special pages.
3572 // 'history' and 'info' actions address page metadata rather than the page
3573 // content itself, so they may not be canonicalized to the view page url.
3574 // TODO: this ought to be better encapsulated in the Action class.
3575 $action = Action::getActionName( $this->getContext() );
3576 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3577 $query = "action={$action}";
3578 } else {
3579 $query = '';
3580 }
3581 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3582 } else {
3583 $reqUrl = $this->getRequest()->getRequestURL();
3584 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3585 }
3586 }
3587 }
3588 if ( $canonicalUrl !== false ) {
3589 $tags[] = Html::element( 'link', array(
3590 'rel' => 'canonical',
3591 'href' => $canonicalUrl
3592 ) );
3593 }
3594
3595 return $tags;
3596 }
3597
3598 /**
3599 * @return string HTML tag links to be put in the header.
3600 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3601 * OutputPage::getHeadLinksArray directly.
3602 */
3603 public function getHeadLinks() {
3604 wfDeprecated( __METHOD__, '1.24' );
3605 return implode( "\n", $this->getHeadLinksArray() );
3606 }
3607
3608 /**
3609 * Generate a "<link rel/>" for a feed.
3610 *
3611 * @param string $type Feed type
3612 * @param string $url URL to the feed
3613 * @param string $text Value of the "title" attribute
3614 * @return string HTML fragment
3615 */
3616 private function feedLink( $type, $url, $text ) {
3617 return Html::element( 'link', array(
3618 'rel' => 'alternate',
3619 'type' => "application/$type+xml",
3620 'title' => $text,
3621 'href' => $url )
3622 );
3623 }
3624
3625 /**
3626 * Add a local or specified stylesheet, with the given media options.
3627 * Meant primarily for internal use...
3628 *
3629 * @param string $style URL to the file
3630 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3631 * @param string $condition For IE conditional comments, specifying an IE version
3632 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3633 */
3634 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3635 $options = array();
3636 // Even though we expect the media type to be lowercase, but here we
3637 // force it to lowercase to be safe.
3638 if ( $media ) {
3639 $options['media'] = $media;
3640 }
3641 if ( $condition ) {
3642 $options['condition'] = $condition;
3643 }
3644 if ( $dir ) {
3645 $options['dir'] = $dir;
3646 }
3647 $this->styles[$style] = $options;
3648 }
3649
3650 /**
3651 * Adds inline CSS styles
3652 * @param mixed $style_css Inline CSS
3653 * @param string $flip Set to 'flip' to flip the CSS if needed
3654 */
3655 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3656 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3657 # If wanted, and the interface is right-to-left, flip the CSS
3658 $style_css = CSSJanus::transform( $style_css, true, false );
3659 }
3660 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3661 }
3662
3663 /**
3664 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3665 * These will be applied to various media & IE conditionals.
3666 *
3667 * @return string
3668 */
3669 public function buildCssLinks() {
3670 global $wgContLang;
3671
3672 $this->getSkin()->setupSkinUserCss( $this );
3673
3674 // Add ResourceLoader styles
3675 // Split the styles into these groups
3676 $styles = array(
3677 'other' => array(),
3678 'user' => array(),
3679 'site' => array(),
3680 'private' => array(),
3681 'noscript' => array()
3682 );
3683 $links = array();
3684 $otherTags = array(); // Tags to append after the normal <link> tags
3685 $resourceLoader = $this->getResourceLoader();
3686
3687 $moduleStyles = $this->getModuleStyles( true, 'top' );
3688
3689 // Per-site custom styles
3690 $moduleStyles[] = 'site';
3691 $moduleStyles[] = 'noscript';
3692 $moduleStyles[] = 'user.groups';
3693
3694 // Per-user custom styles
3695 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3696 && $this->userCanPreview()
3697 ) {
3698 // We're on a preview of a CSS subpage
3699 // Exclude this page from the user module in case it's in there (bug 26283)
3700 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES,
3701 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3702 );
3703 $otherTags = array_merge( $otherTags, $link['html'] );
3704
3705 // Load the previewed CSS
3706 // If needed, Janus it first. This is user-supplied CSS, so it's
3707 // assumed to be right for the content language directionality.
3708 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3709 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3710 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3711 }
3712 $otherTags[] = Html::inlineStyle( $previewedCSS ) . "\n";
3713 } else {
3714 // Load the user styles normally
3715 $moduleStyles[] = 'user';
3716 }
3717
3718 // Per-user preference styles
3719 $moduleStyles[] = 'user.cssprefs';
3720
3721 foreach ( $moduleStyles as $name ) {
3722 $module = $resourceLoader->getModule( $name );
3723 if ( !$module ) {
3724 continue;
3725 }
3726 if ( $name === 'site' ) {
3727 // HACK: The site module shouldn't be fragmented with a cache group and
3728 // http request. But in order to ensure its styles are separated and after the
3729 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3730 // The scripts remain ungrouped and rides the bottom queue.
3731 $styles['site'][] = $name;
3732 continue;
3733 }
3734 $group = $module->getGroup();
3735 // Modules in groups other than the ones needing special treatment
3736 // (see $styles assignment)
3737 // will be placed in the "other" style category.
3738 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3739 }
3740
3741 // We want site, private and user styles to override dynamically added
3742 // styles from modules, but we want dynamically added styles to override
3743 // statically added styles from other modules. So the order has to be
3744 // other, dynamic, site, private, user. Add statically added styles for
3745 // other modules
3746 $links[] = $this->makeResourceLoaderLink(
3747 $styles['other'],
3748 ResourceLoaderModule::TYPE_STYLES
3749 );
3750 // Add normal styles added through addStyle()/addInlineStyle() here
3751 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3752 // Add marker tag to mark the place where the client-side
3753 // loader should inject dynamic styles
3754 // We use a <meta> tag with a made-up name for this because that's valid HTML
3755 $links[] = Html::element(
3756 'meta',
3757 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3758 );
3759
3760 // Add site-specific and user-specific styles
3761 // 'private' at present only contains user.options, so put that before 'user'
3762 // Any future private modules will likely have a similar user-specific character
3763 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3764 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3765 ResourceLoaderModule::TYPE_STYLES
3766 );
3767 }
3768
3769 // Add stuff in $otherTags (previewed user CSS if applicable)
3770 return self::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3771 }
3772
3773 /**
3774 * @return array
3775 */
3776 public function buildCssLinksArray() {
3777 $links = array();
3778
3779 // Add any extension CSS
3780 foreach ( $this->mExtStyles as $url ) {
3781 $this->addStyle( $url );
3782 }
3783 $this->mExtStyles = array();
3784
3785 foreach ( $this->styles as $file => $options ) {
3786 $link = $this->styleLink( $file, $options );
3787 if ( $link ) {
3788 $links[$file] = $link;
3789 }
3790 }
3791 return $links;
3792 }
3793
3794 /**
3795 * Generate \<link\> tags for stylesheets
3796 *
3797 * @param string $style URL to the file
3798 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3799 * @return string HTML fragment
3800 */
3801 protected function styleLink( $style, array $options ) {
3802 if ( isset( $options['dir'] ) ) {
3803 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3804 return '';
3805 }
3806 }
3807
3808 if ( isset( $options['media'] ) ) {
3809 $media = self::transformCssMedia( $options['media'] );
3810 if ( is_null( $media ) ) {
3811 return '';
3812 }
3813 } else {
3814 $media = 'all';
3815 }
3816
3817 if ( substr( $style, 0, 1 ) == '/' ||
3818 substr( $style, 0, 5 ) == 'http:' ||
3819 substr( $style, 0, 6 ) == 'https:' ) {
3820 $url = $style;
3821 } else {
3822 $config = $this->getConfig();
3823 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3824 $config->get( 'StyleVersion' );
3825 }
3826
3827 $link = Html::linkedStyle( $url, $media );
3828
3829 if ( isset( $options['condition'] ) ) {
3830 $condition = htmlspecialchars( $options['condition'] );
3831 $link = "<!--[if $condition]>$link<![endif]-->";
3832 }
3833 return $link;
3834 }
3835
3836 /**
3837 * Transform "media" attribute based on request parameters
3838 *
3839 * @param string $media Current value of the "media" attribute
3840 * @return string Modified value of the "media" attribute, or null to skip
3841 * this stylesheet
3842 */
3843 public static function transformCssMedia( $media ) {
3844 global $wgRequest;
3845
3846 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3847 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3848
3849 // Switch in on-screen display for media testing
3850 $switches = array(
3851 'printable' => 'print',
3852 'handheld' => 'handheld',
3853 );
3854 foreach ( $switches as $switch => $targetMedia ) {
3855 if ( $wgRequest->getBool( $switch ) ) {
3856 if ( $media == $targetMedia ) {
3857 $media = '';
3858 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3859 /* This regex will not attempt to understand a comma-separated media_query_list
3860 *
3861 * Example supported values for $media:
3862 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3863 * Example NOT supported value for $media:
3864 * '3d-glasses, screen, print and resolution > 90dpi'
3865 *
3866 * If it's a print request, we never want any kind of screen stylesheets
3867 * If it's a handheld request (currently the only other choice with a switch),
3868 * we don't want simple 'screen' but we might want screen queries that
3869 * have a max-width or something, so we'll pass all others on and let the
3870 * client do the query.
3871 */
3872 if ( $targetMedia == 'print' || $media == 'screen' ) {
3873 return null;
3874 }
3875 }
3876 }
3877 }
3878
3879 return $media;
3880 }
3881
3882 /**
3883 * Add a wikitext-formatted message to the output.
3884 * This is equivalent to:
3885 *
3886 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3887 */
3888 public function addWikiMsg( /*...*/ ) {
3889 $args = func_get_args();
3890 $name = array_shift( $args );
3891 $this->addWikiMsgArray( $name, $args );
3892 }
3893
3894 /**
3895 * Add a wikitext-formatted message to the output.
3896 * Like addWikiMsg() except the parameters are taken as an array
3897 * instead of a variable argument list.
3898 *
3899 * @param string $name
3900 * @param array $args
3901 */
3902 public function addWikiMsgArray( $name, $args ) {
3903 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3904 }
3905
3906 /**
3907 * This function takes a number of message/argument specifications, wraps them in
3908 * some overall structure, and then parses the result and adds it to the output.
3909 *
3910 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3911 * and so on. The subsequent arguments may be either
3912 * 1) strings, in which case they are message names, or
3913 * 2) arrays, in which case, within each array, the first element is the message
3914 * name, and subsequent elements are the parameters to that message.
3915 *
3916 * Don't use this for messages that are not in the user's interface language.
3917 *
3918 * For example:
3919 *
3920 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3921 *
3922 * Is equivalent to:
3923 *
3924 * $wgOut->addWikiText( "<div class='error'>\n"
3925 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3926 *
3927 * The newline after the opening div is needed in some wikitext. See bug 19226.
3928 *
3929 * @param string $wrap
3930 */
3931 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3932 $msgSpecs = func_get_args();
3933 array_shift( $msgSpecs );
3934 $msgSpecs = array_values( $msgSpecs );
3935 $s = $wrap;
3936 foreach ( $msgSpecs as $n => $spec ) {
3937 if ( is_array( $spec ) ) {
3938 $args = $spec;
3939 $name = array_shift( $args );
3940 if ( isset( $args['options'] ) ) {
3941 unset( $args['options'] );
3942 wfDeprecated(
3943 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3944 '1.20'
3945 );
3946 }
3947 } else {
3948 $args = array();
3949 $name = $spec;
3950 }
3951 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3952 }
3953 $this->addWikiText( $s );
3954 }
3955
3956 /**
3957 * Include jQuery core. Use this to avoid loading it multiple times
3958 * before we get a usable script loader.
3959 *
3960 * @param array $modules List of jQuery modules which should be loaded
3961 * @return array The list of modules which were not loaded.
3962 * @since 1.16
3963 * @deprecated since 1.17
3964 */
3965 public function includeJQuery( array $modules = array() ) {
3966 return array();
3967 }
3968
3969 /**
3970 * Enables/disables TOC, doesn't override __NOTOC__
3971 * @param bool $flag
3972 * @since 1.22
3973 */
3974 public function enableTOC( $flag = true ) {
3975 $this->mEnableTOC = $flag;
3976 }
3977
3978 /**
3979 * @return bool
3980 * @since 1.22
3981 */
3982 public function isTOCEnabled() {
3983 return $this->mEnableTOC;
3984 }
3985
3986 /**
3987 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3988 * @param bool $flag
3989 * @since 1.23
3990 */
3991 public function enableSectionEditLinks( $flag = true ) {
3992 $this->mEnableSectionEditLinks = $flag;
3993 }
3994
3995 /**
3996 * @return bool
3997 * @since 1.23
3998 */
3999 public function sectionEditLinksEnabled() {
4000 return $this->mEnableSectionEditLinks;
4001 }
4002
4003 /**
4004 * Helper function to setup the PHP implementation of OOUI to use in this request.
4005 *
4006 * @since 1.26
4007 * @param String $skinName The Skin name to determine the correct OOUI theme
4008 * @param String $dir Language direction
4009 */
4010 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4011 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
4012 // Make keys (skin names) lowercase for case-insensitive matching.
4013 $themes = array_change_key_case( $themes, CASE_LOWER );
4014 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
4015 // For example, 'OOUI\MediaWikiTheme'.
4016 $themeClass = "OOUI\\{$theme}Theme";
4017 OOUI\Theme::setSingleton( new $themeClass() );
4018 OOUI\Element::setDefaultDir( $dir );
4019 }
4020
4021 /**
4022 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4023 * MediaWiki and this OutputPage instance.
4024 *
4025 * @since 1.25
4026 */
4027 public function enableOOUI() {
4028 self::setupOOUI(
4029 strtolower( $this->getSkin()->getSkinName() ),
4030 $this->getLanguage()->getDir()
4031 );
4032 $this->addModuleStyles( array(
4033 'oojs-ui.styles',
4034 'oojs-ui.styles.icons',
4035 'oojs-ui.styles.indicators',
4036 'oojs-ui.styles.textures',
4037 'mediawiki.widgets.styles',
4038 ) );
4039 }
4040 }