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