Merge "tests: Remove unused TableCleanupTest class"
[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 $mSquidMaxage = 0;
237 /** @var int Upper limit on mSquidMaxage */
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 * @deprecated since 1.19; use addSubtitle() instead
1039 * @param string|Message $str String or Message to add to the subtitle
1040 */
1041 public function appendSubtitle( $str ) {
1042 wfDeprecated( __METHOD__, '1.19' );
1043 $this->addSubtitle( $str );
1044 }
1045
1046 /**
1047 * Add $str to the subtitle
1048 *
1049 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1050 */
1051 public function addSubtitle( $str ) {
1052 if ( $str instanceof Message ) {
1053 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1054 } else {
1055 $this->mSubtitle[] = $str;
1056 }
1057 }
1058
1059 /**
1060 * Build message object for a subtitle containing a backlink to a page
1061 *
1062 * @param Title $title Title to link to
1063 * @param array $query Array of additional parameters to include in the link
1064 * @return Message
1065 * @since 1.25
1066 */
1067 public static function buildBacklinkSubtitle( Title $title, $query = array() ) {
1068 if ( $title->isRedirect() ) {
1069 $query['redirect'] = 'no';
1070 }
1071 return wfMessage( 'backlinksubtitle' )
1072 ->rawParams( Linker::link( $title, null, array(), $query ) );
1073 }
1074
1075 /**
1076 * Add a subtitle containing a backlink to a page
1077 *
1078 * @param Title $title Title to link to
1079 * @param array $query Array of additional parameters to include in the link
1080 */
1081 public function addBacklinkSubtitle( Title $title, $query = array() ) {
1082 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1083 }
1084
1085 /**
1086 * Clear the subtitles
1087 */
1088 public function clearSubtitle() {
1089 $this->mSubtitle = array();
1090 }
1091
1092 /**
1093 * Get the subtitle
1094 *
1095 * @return string
1096 */
1097 public function getSubtitle() {
1098 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1099 }
1100
1101 /**
1102 * Set the page as printable, i.e. it'll be displayed with all
1103 * print styles included
1104 */
1105 public function setPrintable() {
1106 $this->mPrintable = true;
1107 }
1108
1109 /**
1110 * Return whether the page is "printable"
1111 *
1112 * @return bool
1113 */
1114 public function isPrintable() {
1115 return $this->mPrintable;
1116 }
1117
1118 /**
1119 * Disable output completely, i.e. calling output() will have no effect
1120 */
1121 public function disable() {
1122 $this->mDoNothing = true;
1123 }
1124
1125 /**
1126 * Return whether the output will be completely disabled
1127 *
1128 * @return bool
1129 */
1130 public function isDisabled() {
1131 return $this->mDoNothing;
1132 }
1133
1134 /**
1135 * Show an "add new section" link?
1136 *
1137 * @return bool
1138 */
1139 public function showNewSectionLink() {
1140 return $this->mNewSectionLink;
1141 }
1142
1143 /**
1144 * Forcibly hide the new section link?
1145 *
1146 * @return bool
1147 */
1148 public function forceHideNewSectionLink() {
1149 return $this->mHideNewSectionLink;
1150 }
1151
1152 /**
1153 * Add or remove feed links in the page header
1154 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1155 * for the new version
1156 * @see addFeedLink()
1157 *
1158 * @param bool $show True: add default feeds, false: remove all feeds
1159 */
1160 public function setSyndicated( $show = true ) {
1161 if ( $show ) {
1162 $this->setFeedAppendQuery( false );
1163 } else {
1164 $this->mFeedLinks = array();
1165 }
1166 }
1167
1168 /**
1169 * Add default feeds to the page header
1170 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1171 * for the new version
1172 * @see addFeedLink()
1173 *
1174 * @param string $val Query to append to feed links or false to output
1175 * default links
1176 */
1177 public function setFeedAppendQuery( $val ) {
1178 $this->mFeedLinks = array();
1179
1180 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1181 $query = "feed=$type";
1182 if ( is_string( $val ) ) {
1183 $query .= '&' . $val;
1184 }
1185 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1186 }
1187 }
1188
1189 /**
1190 * Add a feed link to the page header
1191 *
1192 * @param string $format Feed type, should be a key of $wgFeedClasses
1193 * @param string $href URL
1194 */
1195 public function addFeedLink( $format, $href ) {
1196 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1197 $this->mFeedLinks[$format] = $href;
1198 }
1199 }
1200
1201 /**
1202 * Should we output feed links for this page?
1203 * @return bool
1204 */
1205 public function isSyndicated() {
1206 return count( $this->mFeedLinks ) > 0;
1207 }
1208
1209 /**
1210 * Return URLs for each supported syndication format for this page.
1211 * @return array Associating format keys with URLs
1212 */
1213 public function getSyndicationLinks() {
1214 return $this->mFeedLinks;
1215 }
1216
1217 /**
1218 * Will currently always return null
1219 *
1220 * @return null
1221 */
1222 public function getFeedAppendQuery() {
1223 return $this->mFeedLinksAppendQuery;
1224 }
1225
1226 /**
1227 * Set whether the displayed content is related to the source of the
1228 * corresponding article on the wiki
1229 * Setting true will cause the change "article related" toggle to true
1230 *
1231 * @param bool $v
1232 */
1233 public function setArticleFlag( $v ) {
1234 $this->mIsarticle = $v;
1235 if ( $v ) {
1236 $this->mIsArticleRelated = $v;
1237 }
1238 }
1239
1240 /**
1241 * Return whether the content displayed page is related to the source of
1242 * the corresponding article on the wiki
1243 *
1244 * @return bool
1245 */
1246 public function isArticle() {
1247 return $this->mIsarticle;
1248 }
1249
1250 /**
1251 * Set whether this page is related an article on the wiki
1252 * Setting false will cause the change of "article flag" toggle to false
1253 *
1254 * @param bool $v
1255 */
1256 public function setArticleRelated( $v ) {
1257 $this->mIsArticleRelated = $v;
1258 if ( !$v ) {
1259 $this->mIsarticle = false;
1260 }
1261 }
1262
1263 /**
1264 * Return whether this page is related an article on the wiki
1265 *
1266 * @return bool
1267 */
1268 public function isArticleRelated() {
1269 return $this->mIsArticleRelated;
1270 }
1271
1272 /**
1273 * Add new language links
1274 *
1275 * @param array $newLinkArray Associative array mapping language code to the page
1276 * name
1277 */
1278 public function addLanguageLinks( array $newLinkArray ) {
1279 $this->mLanguageLinks += $newLinkArray;
1280 }
1281
1282 /**
1283 * Reset the language links and add new language links
1284 *
1285 * @param array $newLinkArray Associative array mapping language code to the page
1286 * name
1287 */
1288 public function setLanguageLinks( array $newLinkArray ) {
1289 $this->mLanguageLinks = $newLinkArray;
1290 }
1291
1292 /**
1293 * Get the list of language links
1294 *
1295 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1296 */
1297 public function getLanguageLinks() {
1298 return $this->mLanguageLinks;
1299 }
1300
1301 /**
1302 * Add an array of categories, with names in the keys
1303 *
1304 * @param array $categories Mapping category name => sort key
1305 */
1306 public function addCategoryLinks( array $categories ) {
1307 global $wgContLang;
1308
1309 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1310 return;
1311 }
1312
1313 # Add the links to a LinkBatch
1314 $arr = array( NS_CATEGORY => $categories );
1315 $lb = new LinkBatch;
1316 $lb->setArray( $arr );
1317
1318 # Fetch existence plus the hiddencat property
1319 $dbr = wfGetDB( DB_SLAVE );
1320 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1321 'page_is_redirect', 'page_latest', 'pp_value' );
1322
1323 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1324 $fields[] = 'page_content_model';
1325 }
1326
1327 $res = $dbr->select( array( 'page', 'page_props' ),
1328 $fields,
1329 $lb->constructSet( 'page', $dbr ),
1330 __METHOD__,
1331 array(),
1332 array( 'page_props' => array( 'LEFT JOIN', array(
1333 'pp_propname' => 'hiddencat',
1334 'pp_page = page_id'
1335 ) ) )
1336 );
1337
1338 # Add the results to the link cache
1339 $lb->addResultToCache( LinkCache::singleton(), $res );
1340
1341 # Set all the values to 'normal'.
1342 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1343
1344 # Mark hidden categories
1345 foreach ( $res as $row ) {
1346 if ( isset( $row->pp_value ) ) {
1347 $categories[$row->page_title] = 'hidden';
1348 }
1349 }
1350
1351 # Add the remaining categories to the skin
1352 if ( Hooks::run(
1353 'OutputPageMakeCategoryLinks',
1354 array( &$this, $categories, &$this->mCategoryLinks ) )
1355 ) {
1356 foreach ( $categories as $category => $type ) {
1357 // array keys will cast numeric category names to ints, so cast back to string
1358 $category = (string)$category;
1359 $origcategory = $category;
1360 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1361 if ( !$title ) {
1362 continue;
1363 }
1364 $wgContLang->findVariantLink( $category, $title, true );
1365 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1366 continue;
1367 }
1368 $text = $wgContLang->convertHtml( $title->getText() );
1369 $this->mCategories[] = $title->getText();
1370 $this->mCategoryLinks[$type][] = Linker::link( $title, $text );
1371 }
1372 }
1373 }
1374
1375 /**
1376 * Reset the category links (but not the category list) and add $categories
1377 *
1378 * @param array $categories Mapping category name => sort key
1379 */
1380 public function setCategoryLinks( array $categories ) {
1381 $this->mCategoryLinks = array();
1382 $this->addCategoryLinks( $categories );
1383 }
1384
1385 /**
1386 * Get the list of category links, in a 2-D array with the following format:
1387 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1388 * hidden categories) and $link a HTML fragment with a link to the category
1389 * page
1390 *
1391 * @return array
1392 */
1393 public function getCategoryLinks() {
1394 return $this->mCategoryLinks;
1395 }
1396
1397 /**
1398 * Get the list of category names this page belongs to
1399 *
1400 * @return array Array of strings
1401 */
1402 public function getCategories() {
1403 return $this->mCategories;
1404 }
1405
1406 /**
1407 * Add an array of indicators, with their identifiers as array
1408 * keys and HTML contents as values.
1409 *
1410 * In case of duplicate keys, existing values are overwritten.
1411 *
1412 * @param array $indicators
1413 * @since 1.25
1414 */
1415 public function setIndicators( array $indicators ) {
1416 $this->mIndicators = $indicators + $this->mIndicators;
1417 // Keep ordered by key
1418 ksort( $this->mIndicators );
1419 }
1420
1421 /**
1422 * Get the indicators associated with this page.
1423 *
1424 * The array will be internally ordered by item keys.
1425 *
1426 * @return array Keys: identifiers, values: HTML contents
1427 * @since 1.25
1428 */
1429 public function getIndicators() {
1430 return $this->mIndicators;
1431 }
1432
1433 /**
1434 * Adds help link with an icon via page indicators.
1435 * Link target can be overridden by a local message containing a wikilink:
1436 * the message key is: lowercase action or special page name + '-helppage'.
1437 * @param string $to Target MediaWiki.org page title or encoded URL.
1438 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1439 * @since 1.25
1440 */
1441 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1442 $this->addModuleStyles( 'mediawiki.helplink' );
1443 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1444
1445 if ( $overrideBaseUrl ) {
1446 $helpUrl = $to;
1447 } else {
1448 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1449 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1450 }
1451
1452 $link = Html::rawElement(
1453 'a',
1454 array(
1455 'href' => $helpUrl,
1456 'target' => '_blank',
1457 'class' => 'mw-helplink',
1458 ),
1459 $text
1460 );
1461
1462 $this->setIndicators( array( 'mw-helplink' => $link ) );
1463 }
1464
1465 /**
1466 * Do not allow scripts which can be modified by wiki users to load on this page;
1467 * only allow scripts bundled with, or generated by, the software.
1468 * Site-wide styles are controlled by a config setting, since they can be
1469 * used to create a custom skin/theme, but not user-specific ones.
1470 *
1471 * @todo this should be given a more accurate name
1472 */
1473 public function disallowUserJs() {
1474 $this->reduceAllowedModules(
1475 ResourceLoaderModule::TYPE_SCRIPTS,
1476 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1477 );
1478
1479 // Site-wide styles are controlled by a config setting, see bug 71621
1480 // for background on why. User styles are never allowed.
1481 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1482 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1483 } else {
1484 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1485 }
1486 $this->reduceAllowedModules(
1487 ResourceLoaderModule::TYPE_STYLES,
1488 $styleOrigin
1489 );
1490 }
1491
1492 /**
1493 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1494 * @see ResourceLoaderModule::$origin
1495 * @param string $type ResourceLoaderModule TYPE_ constant
1496 * @return int ResourceLoaderModule ORIGIN_ class constant
1497 */
1498 public function getAllowedModules( $type ) {
1499 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1500 return min( array_values( $this->mAllowedModules ) );
1501 } else {
1502 return isset( $this->mAllowedModules[$type] )
1503 ? $this->mAllowedModules[$type]
1504 : ResourceLoaderModule::ORIGIN_ALL;
1505 }
1506 }
1507
1508 /**
1509 * Set the highest level of CSS/JS untrustworthiness allowed
1510 *
1511 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1512 * Use reduceAllowedModules() instead
1513 * @param string $type ResourceLoaderModule TYPE_ constant
1514 * @param int $level ResourceLoaderModule class constant
1515 */
1516 public function setAllowedModules( $type, $level ) {
1517 wfDeprecated( __METHOD__, '1.24' );
1518 $this->reduceAllowedModules( $type, $level );
1519 }
1520
1521 /**
1522 * Limit the highest level of CSS/JS untrustworthiness allowed.
1523 *
1524 * If passed the same or a higher level than the current level of untrustworthiness set, the
1525 * level will remain unchanged.
1526 *
1527 * @param string $type
1528 * @param int $level ResourceLoaderModule class constant
1529 */
1530 public function reduceAllowedModules( $type, $level ) {
1531 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1532 }
1533
1534 /**
1535 * Prepend $text to the body HTML
1536 *
1537 * @param string $text HTML
1538 */
1539 public function prependHTML( $text ) {
1540 $this->mBodytext = $text . $this->mBodytext;
1541 }
1542
1543 /**
1544 * Append $text to the body HTML
1545 *
1546 * @param string $text HTML
1547 */
1548 public function addHTML( $text ) {
1549 $this->mBodytext .= $text;
1550 }
1551
1552 /**
1553 * Shortcut for adding an Html::element via addHTML.
1554 *
1555 * @since 1.19
1556 *
1557 * @param string $element
1558 * @param array $attribs
1559 * @param string $contents
1560 */
1561 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1562 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1563 }
1564
1565 /**
1566 * Clear the body HTML
1567 */
1568 public function clearHTML() {
1569 $this->mBodytext = '';
1570 }
1571
1572 /**
1573 * Get the body HTML
1574 *
1575 * @return string HTML
1576 */
1577 public function getHTML() {
1578 return $this->mBodytext;
1579 }
1580
1581 /**
1582 * Get/set the ParserOptions object to use for wikitext parsing
1583 *
1584 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1585 * current ParserOption object
1586 * @return ParserOptions
1587 */
1588 public function parserOptions( $options = null ) {
1589 if ( !$this->mParserOptions ) {
1590 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1591 $this->mParserOptions->setEditSection( false );
1592 }
1593 return wfSetVar( $this->mParserOptions, $options );
1594 }
1595
1596 /**
1597 * Set the revision ID which will be seen by the wiki text parser
1598 * for things such as embedded {{REVISIONID}} variable use.
1599 *
1600 * @param int|null $revid An positive integer, or null
1601 * @return mixed Previous value
1602 */
1603 public function setRevisionId( $revid ) {
1604 $val = is_null( $revid ) ? null : intval( $revid );
1605 return wfSetVar( $this->mRevisionId, $val );
1606 }
1607
1608 /**
1609 * Get the displayed revision ID
1610 *
1611 * @return int
1612 */
1613 public function getRevisionId() {
1614 return $this->mRevisionId;
1615 }
1616
1617 /**
1618 * Set the timestamp of the revision which will be displayed. This is used
1619 * to avoid a extra DB call in Skin::lastModified().
1620 *
1621 * @param string|null $timestamp
1622 * @return mixed Previous value
1623 */
1624 public function setRevisionTimestamp( $timestamp ) {
1625 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1626 }
1627
1628 /**
1629 * Get the timestamp of displayed revision.
1630 * This will be null if not filled by setRevisionTimestamp().
1631 *
1632 * @return string|null
1633 */
1634 public function getRevisionTimestamp() {
1635 return $this->mRevisionTimestamp;
1636 }
1637
1638 /**
1639 * Set the displayed file version
1640 *
1641 * @param File|bool $file
1642 * @return mixed Previous value
1643 */
1644 public function setFileVersion( $file ) {
1645 $val = null;
1646 if ( $file instanceof File && $file->exists() ) {
1647 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1648 }
1649 return wfSetVar( $this->mFileVersion, $val, true );
1650 }
1651
1652 /**
1653 * Get the displayed file version
1654 *
1655 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1656 */
1657 public function getFileVersion() {
1658 return $this->mFileVersion;
1659 }
1660
1661 /**
1662 * Get the templates used on this page
1663 *
1664 * @return array (namespace => dbKey => revId)
1665 * @since 1.18
1666 */
1667 public function getTemplateIds() {
1668 return $this->mTemplateIds;
1669 }
1670
1671 /**
1672 * Get the files used on this page
1673 *
1674 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1675 * @since 1.18
1676 */
1677 public function getFileSearchOptions() {
1678 return $this->mImageTimeKeys;
1679 }
1680
1681 /**
1682 * Convert wikitext to HTML and add it to the buffer
1683 * Default assumes that the current page title will be used.
1684 *
1685 * @param string $text
1686 * @param bool $linestart Is this the start of a line?
1687 * @param bool $interface Is this text in the user interface language?
1688 * @throws MWException
1689 */
1690 public function addWikiText( $text, $linestart = true, $interface = true ) {
1691 $title = $this->getTitle(); // Work around E_STRICT
1692 if ( !$title ) {
1693 throw new MWException( 'Title is null' );
1694 }
1695 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1696 }
1697
1698 /**
1699 * Add wikitext with a custom Title object
1700 *
1701 * @param string $text Wikitext
1702 * @param Title $title
1703 * @param bool $linestart Is this the start of a line?
1704 */
1705 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1706 $this->addWikiTextTitle( $text, $title, $linestart );
1707 }
1708
1709 /**
1710 * Add wikitext with a custom Title object and tidy enabled.
1711 *
1712 * @param string $text Wikitext
1713 * @param Title $title
1714 * @param bool $linestart Is this the start of a line?
1715 */
1716 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1717 $this->addWikiTextTitle( $text, $title, $linestart, true );
1718 }
1719
1720 /**
1721 * Add wikitext with tidy enabled
1722 *
1723 * @param string $text Wikitext
1724 * @param bool $linestart Is this the start of a line?
1725 */
1726 public function addWikiTextTidy( $text, $linestart = true ) {
1727 $title = $this->getTitle();
1728 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1729 }
1730
1731 /**
1732 * Add wikitext with a custom Title object
1733 *
1734 * @param string $text Wikitext
1735 * @param Title $title
1736 * @param bool $linestart Is this the start of a line?
1737 * @param bool $tidy Whether to use tidy
1738 * @param bool $interface Whether it is an interface message
1739 * (for example disables conversion)
1740 */
1741 public function addWikiTextTitle( $text, Title $title, $linestart,
1742 $tidy = false, $interface = false
1743 ) {
1744 global $wgParser;
1745
1746 $popts = $this->parserOptions();
1747 $oldTidy = $popts->setTidy( $tidy );
1748 $popts->setInterfaceMessage( (bool)$interface );
1749
1750 $parserOutput = $wgParser->getFreshParser()->parse(
1751 $text, $title, $popts,
1752 $linestart, true, $this->mRevisionId
1753 );
1754
1755 $popts->setTidy( $oldTidy );
1756
1757 $this->addParserOutput( $parserOutput );
1758
1759 }
1760
1761 /**
1762 * Add a ParserOutput object, but without Html.
1763 *
1764 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1765 * @param ParserOutput $parserOutput
1766 */
1767 public function addParserOutputNoText( $parserOutput ) {
1768 wfDeprecated( __METHOD__, '1.24' );
1769 $this->addParserOutputMetadata( $parserOutput );
1770 }
1771
1772 /**
1773 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1774 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1775 * and so on.
1776 *
1777 * @since 1.24
1778 * @param ParserOutput $parserOutput
1779 */
1780 public function addParserOutputMetadata( $parserOutput ) {
1781 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1782 $this->addCategoryLinks( $parserOutput->getCategories() );
1783 $this->setIndicators( $parserOutput->getIndicators() );
1784 $this->mNewSectionLink = $parserOutput->getNewSection();
1785 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1786
1787 $this->mParseWarnings = $parserOutput->getWarnings();
1788 if ( !$parserOutput->isCacheable() ) {
1789 $this->enableClientCache( false );
1790 }
1791 $this->mNoGallery = $parserOutput->getNoGallery();
1792 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1793 $this->addModules( $parserOutput->getModules() );
1794 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1795 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1796 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1797 $this->mPreventClickjacking = $this->mPreventClickjacking
1798 || $parserOutput->preventClickjacking();
1799
1800 // Template versioning...
1801 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1802 if ( isset( $this->mTemplateIds[$ns] ) ) {
1803 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1804 } else {
1805 $this->mTemplateIds[$ns] = $dbks;
1806 }
1807 }
1808 // File versioning...
1809 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1810 $this->mImageTimeKeys[$dbk] = $data;
1811 }
1812
1813 // Hooks registered in the object
1814 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1815 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1816 list( $hookName, $data ) = $hookInfo;
1817 if ( isset( $parserOutputHooks[$hookName] ) ) {
1818 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1819 }
1820 }
1821
1822 // enable OOUI if requested via ParserOutput
1823 if ( $parserOutput->getEnableOOUI() ) {
1824 $this->enableOOUI();
1825 }
1826
1827 // Link flags are ignored for now, but may in the future be
1828 // used to mark individual language links.
1829 $linkFlags = array();
1830 Hooks::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1831 Hooks::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1832 }
1833
1834 /**
1835 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1836 * ParserOutput object, without any other metadata.
1837 *
1838 * @since 1.24
1839 * @param ParserOutput $parserOutput
1840 */
1841 public function addParserOutputContent( $parserOutput ) {
1842 $this->addParserOutputText( $parserOutput );
1843
1844 $this->addModules( $parserOutput->getModules() );
1845 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1846 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1847
1848 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1849 }
1850
1851 /**
1852 * Add the HTML associated with a ParserOutput object, without any metadata.
1853 *
1854 * @since 1.24
1855 * @param ParserOutput $parserOutput
1856 */
1857 public function addParserOutputText( $parserOutput ) {
1858 $text = $parserOutput->getText();
1859 Hooks::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1860 $this->addHTML( $text );
1861 }
1862
1863 /**
1864 * Add everything from a ParserOutput object.
1865 *
1866 * @param ParserOutput $parserOutput
1867 */
1868 function addParserOutput( $parserOutput ) {
1869 $this->addParserOutputMetadata( $parserOutput );
1870 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1871
1872 // Touch section edit links only if not previously disabled
1873 if ( $parserOutput->getEditSectionTokens() ) {
1874 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1875 }
1876
1877 $this->addParserOutputText( $parserOutput );
1878 }
1879
1880 /**
1881 * Add the output of a QuickTemplate to the output buffer
1882 *
1883 * @param QuickTemplate $template
1884 */
1885 public function addTemplate( &$template ) {
1886 $this->addHTML( $template->getHTML() );
1887 }
1888
1889 /**
1890 * Parse wikitext and return the HTML.
1891 *
1892 * @param string $text
1893 * @param bool $linestart Is this the start of a line?
1894 * @param bool $interface Use interface language ($wgLang instead of
1895 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1896 * This also disables LanguageConverter.
1897 * @param Language $language Target language object, will override $interface
1898 * @throws MWException
1899 * @return string HTML
1900 */
1901 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1902 global $wgParser;
1903
1904 if ( is_null( $this->getTitle() ) ) {
1905 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1906 }
1907
1908 $popts = $this->parserOptions();
1909 if ( $interface ) {
1910 $popts->setInterfaceMessage( true );
1911 }
1912 if ( $language !== null ) {
1913 $oldLang = $popts->setTargetLanguage( $language );
1914 }
1915
1916 $parserOutput = $wgParser->getFreshParser()->parse(
1917 $text, $this->getTitle(), $popts,
1918 $linestart, true, $this->mRevisionId
1919 );
1920
1921 if ( $interface ) {
1922 $popts->setInterfaceMessage( false );
1923 }
1924 if ( $language !== null ) {
1925 $popts->setTargetLanguage( $oldLang );
1926 }
1927
1928 return $parserOutput->getText();
1929 }
1930
1931 /**
1932 * Parse wikitext, strip paragraphs, and return the HTML.
1933 *
1934 * @param string $text
1935 * @param bool $linestart Is this the start of a line?
1936 * @param bool $interface Use interface language ($wgLang instead of
1937 * $wgContLang) while parsing language sensitive magic
1938 * words like GRAMMAR and PLURAL
1939 * @return string HTML
1940 */
1941 public function parseInline( $text, $linestart = true, $interface = false ) {
1942 $parsed = $this->parse( $text, $linestart, $interface );
1943 return Parser::stripOuterParagraph( $parsed );
1944 }
1945
1946 /**
1947 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1948 *
1949 * @param int $maxage Maximum cache time on the Squid, in seconds.
1950 */
1951 public function setSquidMaxage( $maxage ) {
1952 $this->mSquidMaxage = min( $maxage, $this->mCdnMaxageLimit );
1953 }
1954
1955 /**
1956 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1957 *
1958 * @param int $maxage Maximum cache time on the Squid, in seconds
1959 * @since 1.27
1960 */
1961 public function lowerCdnMaxage( $maxage ) {
1962 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
1963 $this->setSquidMaxage( $this->mSquidMaxage );
1964 }
1965
1966 /**
1967 * Use enableClientCache(false) to force it to send nocache headers
1968 *
1969 * @param bool $state
1970 *
1971 * @return bool
1972 */
1973 public function enableClientCache( $state ) {
1974 return wfSetVar( $this->mEnableClientCache, $state );
1975 }
1976
1977 /**
1978 * Get the list of cookies that will influence on the cache
1979 *
1980 * @return array
1981 */
1982 function getCacheVaryCookies() {
1983 static $cookies;
1984 if ( $cookies === null ) {
1985 $config = $this->getConfig();
1986 $cookies = array_merge(
1987 array(
1988 $config->get( 'CookiePrefix' ) . 'Token',
1989 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1990 "forceHTTPS",
1991 session_name()
1992 ),
1993 $config->get( 'CacheVaryCookies' )
1994 );
1995 Hooks::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1996 }
1997 return $cookies;
1998 }
1999
2000 /**
2001 * Check if the request has a cache-varying cookie header
2002 * If it does, it's very important that we don't allow public caching
2003 *
2004 * @return bool
2005 */
2006 function haveCacheVaryCookies() {
2007 $request = $this->getRequest();
2008 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2009 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2010 wfDebug( __METHOD__ . ": found $cookieName\n" );
2011 return true;
2012 }
2013 }
2014 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2015 return false;
2016 }
2017
2018 /**
2019 * Add an HTTP header that will influence on the cache
2020 *
2021 * @param string $header Header name
2022 * @param string[]|null $option Options for the Key header. See
2023 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2024 * for the list of valid options.
2025 */
2026 public function addVaryHeader( $header, array $option = null ) {
2027 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2028 $this->mVaryHeader[$header] = array();
2029 }
2030 if ( !is_array( $option ) ) {
2031 $option = array();
2032 }
2033 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2034 }
2035
2036 /**
2037 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2038 * such as Accept-Encoding or Cookie
2039 *
2040 * @return string
2041 */
2042 public function getVaryHeader() {
2043 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2044 }
2045
2046 /**
2047 * Get a complete Key header
2048 *
2049 * @return string
2050 */
2051 public function getKeyHeader() {
2052 $cvCookies = $this->getCacheVaryCookies();
2053
2054 $cookiesOption = array();
2055 foreach ( $cvCookies as $cookieName ) {
2056 $cookiesOption[] = 'param=' . $cookieName;
2057 }
2058 $this->addVaryHeader( 'Cookie', $cookiesOption );
2059
2060 $headers = array();
2061 foreach ( $this->mVaryHeader as $header => $option ) {
2062 $newheader = $header;
2063 if ( is_array( $option ) && count( $option ) > 0 ) {
2064 $newheader .= ';' . implode( ';', $option );
2065 }
2066 $headers[] = $newheader;
2067 }
2068 $key = 'Key: ' . implode( ',', $headers );
2069
2070 return $key;
2071 }
2072
2073 /**
2074 * T23672: Add Accept-Language to Vary and Key headers
2075 * if there's no 'variant' parameter existed in GET.
2076 *
2077 * For example:
2078 * /w/index.php?title=Main_page should always be served; but
2079 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2080 */
2081 function addAcceptLanguage() {
2082 $title = $this->getTitle();
2083 if ( !$title instanceof Title ) {
2084 return;
2085 }
2086
2087 $lang = $title->getPageLanguage();
2088 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2089 $variants = $lang->getVariants();
2090 $aloption = array();
2091 foreach ( $variants as $variant ) {
2092 if ( $variant === $lang->getCode() ) {
2093 continue;
2094 } else {
2095 $aloption[] = 'substr=' . $variant;
2096
2097 // IE and some other browsers use BCP 47 standards in
2098 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2099 // We should handle these too.
2100 $variantBCP47 = wfBCP47( $variant );
2101 if ( $variantBCP47 !== $variant ) {
2102 $aloption[] = 'substr=' . $variantBCP47;
2103 }
2104 }
2105 }
2106 $this->addVaryHeader( 'Accept-Language', $aloption );
2107 }
2108 }
2109
2110 /**
2111 * Set a flag which will cause an X-Frame-Options header appropriate for
2112 * edit pages to be sent. The header value is controlled by
2113 * $wgEditPageFrameOptions.
2114 *
2115 * This is the default for special pages. If you display a CSRF-protected
2116 * form on an ordinary view page, then you need to call this function.
2117 *
2118 * @param bool $enable
2119 */
2120 public function preventClickjacking( $enable = true ) {
2121 $this->mPreventClickjacking = $enable;
2122 }
2123
2124 /**
2125 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2126 * This can be called from pages which do not contain any CSRF-protected
2127 * HTML form.
2128 */
2129 public function allowClickjacking() {
2130 $this->mPreventClickjacking = false;
2131 }
2132
2133 /**
2134 * Get the prevent-clickjacking flag
2135 *
2136 * @since 1.24
2137 * @return bool
2138 */
2139 public function getPreventClickjacking() {
2140 return $this->mPreventClickjacking;
2141 }
2142
2143 /**
2144 * Get the X-Frame-Options header value (without the name part), or false
2145 * if there isn't one. This is used by Skin to determine whether to enable
2146 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2147 *
2148 * @return string
2149 */
2150 public function getFrameOptions() {
2151 $config = $this->getConfig();
2152 if ( $config->get( 'BreakFrames' ) ) {
2153 return 'DENY';
2154 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2155 return $config->get( 'EditPageFrameOptions' );
2156 }
2157 return false;
2158 }
2159
2160 /**
2161 * Send cache control HTTP headers
2162 */
2163 public function sendCacheControl() {
2164 $response = $this->getRequest()->response();
2165 $config = $this->getConfig();
2166 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2167 $response->header( "ETag: $this->mETag" );
2168 }
2169
2170 $this->addVaryHeader( 'Cookie' );
2171 $this->addAcceptLanguage();
2172
2173 # don't serve compressed data to clients who can't handle it
2174 # maintain different caches for logged-in users and non-logged in ones
2175 $response->header( $this->getVaryHeader() );
2176
2177 if ( $config->get( 'UseKeyHeader' ) ) {
2178 $response->header( $this->getKeyHeader() );
2179 }
2180
2181 if ( $this->mEnableClientCache ) {
2182 if (
2183 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2184 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2185 ) {
2186 if ( $config->get( 'UseESI' ) ) {
2187 # We'll purge the proxy cache explicitly, but require end user agents
2188 # to revalidate against the proxy on each visit.
2189 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2190 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2191 # start with a shorter timeout for initial testing
2192 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2193 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2194 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2195 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2196 } else {
2197 # We'll purge the proxy cache for anons explicitly, but require end user agents
2198 # to revalidate against the proxy on each visit.
2199 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2200 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2201 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2202 # start with a shorter timeout for initial testing
2203 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2204 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2205 . ', must-revalidate, max-age=0' );
2206 }
2207 } else {
2208 # We do want clients to cache if they can, but they *must* check for updates
2209 # on revisiting the page.
2210 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2211 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2212 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2213 }
2214 if ( $this->mLastModified ) {
2215 $response->header( "Last-Modified: {$this->mLastModified}" );
2216 }
2217 } else {
2218 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2219
2220 # In general, the absence of a last modified header should be enough to prevent
2221 # the client from using its cache. We send a few other things just to make sure.
2222 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2223 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2224 $response->header( 'Pragma: no-cache' );
2225 }
2226 }
2227
2228 /**
2229 * Finally, all the text has been munged and accumulated into
2230 * the object, let's actually output it:
2231 */
2232 public function output() {
2233 if ( $this->mDoNothing ) {
2234 return;
2235 }
2236
2237 $response = $this->getRequest()->response();
2238 $config = $this->getConfig();
2239
2240 if ( $this->mRedirect != '' ) {
2241 # Standards require redirect URLs to be absolute
2242 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2243
2244 $redirect = $this->mRedirect;
2245 $code = $this->mRedirectCode;
2246
2247 if ( Hooks::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2248 if ( $code == '301' || $code == '303' ) {
2249 if ( !$config->get( 'DebugRedirects' ) ) {
2250 $response->statusHeader( $code );
2251 }
2252 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2253 }
2254 if ( $config->get( 'VaryOnXFP' ) ) {
2255 $this->addVaryHeader( 'X-Forwarded-Proto' );
2256 }
2257 $this->sendCacheControl();
2258
2259 $response->header( "Content-Type: text/html; charset=utf-8" );
2260 if ( $config->get( 'DebugRedirects' ) ) {
2261 $url = htmlspecialchars( $redirect );
2262 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2263 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2264 print "</body>\n</html>\n";
2265 } else {
2266 $response->header( 'Location: ' . $redirect );
2267 }
2268 }
2269
2270 return;
2271 } elseif ( $this->mStatusCode ) {
2272 $response->statusHeader( $this->mStatusCode );
2273 }
2274
2275 # Buffer output; final headers may depend on later processing
2276 ob_start();
2277
2278 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2279 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2280
2281 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2282 // jQuery etc. can work correctly.
2283 $response->header( 'X-UA-Compatible: IE=Edge' );
2284
2285 // Prevent framing, if requested
2286 $frameOptions = $this->getFrameOptions();
2287 if ( $frameOptions ) {
2288 $response->header( "X-Frame-Options: $frameOptions" );
2289 }
2290
2291 if ( $this->mArticleBodyOnly ) {
2292 echo $this->mBodytext;
2293 } else {
2294 $sk = $this->getSkin();
2295 // add skin specific modules
2296 $modules = $sk->getDefaultModules();
2297
2298 // Enforce various default modules for all skins
2299 $coreModules = array(
2300 // Keep this list as small as possible
2301 'site',
2302 'mediawiki.page.startup',
2303 'mediawiki.user',
2304 );
2305
2306 // Support for high-density display images if enabled
2307 if ( $config->get( 'ResponsiveImages' ) ) {
2308 $coreModules[] = 'mediawiki.hidpi';
2309 }
2310
2311 $this->addModules( $coreModules );
2312 foreach ( $modules as $group ) {
2313 $this->addModules( $group );
2314 }
2315 MWDebug::addModules( $this );
2316
2317 // Hook that allows last minute changes to the output page, e.g.
2318 // adding of CSS or Javascript by extensions.
2319 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2320
2321 $sk->outputPage();
2322 }
2323
2324 // This hook allows last minute changes to final overall output by modifying output buffer
2325 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2326
2327 $this->sendCacheControl();
2328
2329 ob_end_flush();
2330
2331 }
2332
2333 /**
2334 * Actually output something with print.
2335 *
2336 * @param string $ins The string to output
2337 * @deprecated since 1.22 Use echo yourself.
2338 */
2339 public function out( $ins ) {
2340 wfDeprecated( __METHOD__, '1.22' );
2341 print $ins;
2342 }
2343
2344 /**
2345 * Produce a "user is blocked" page.
2346 * @deprecated since 1.18
2347 */
2348 function blockedPage() {
2349 wfDeprecated( __METHOD__, '1.18' );
2350 throw new UserBlockedError( $this->getUser()->mBlock );
2351 }
2352
2353 /**
2354 * Prepare this object to display an error page; disable caching and
2355 * indexing, clear the current text and redirect, set the page's title
2356 * and optionally an custom HTML title (content of the "<title>" tag).
2357 *
2358 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2359 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2360 * optional, if not passed the "<title>" attribute will be
2361 * based on $pageTitle
2362 */
2363 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2364 $this->setPageTitle( $pageTitle );
2365 if ( $htmlTitle !== false ) {
2366 $this->setHTMLTitle( $htmlTitle );
2367 }
2368 $this->setRobotPolicy( 'noindex,nofollow' );
2369 $this->setArticleRelated( false );
2370 $this->enableClientCache( false );
2371 $this->mRedirect = '';
2372 $this->clearSubtitle();
2373 $this->clearHTML();
2374 }
2375
2376 /**
2377 * Output a standard error page
2378 *
2379 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2380 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2381 * showErrorPage( 'titlemsg', $messageObject );
2382 * showErrorPage( $titleMessageObject, $messageObject );
2383 *
2384 * @param string|Message $title Message key (string) for page title, or a Message object
2385 * @param string|Message $msg Message key (string) for page text, or a Message object
2386 * @param array $params Message parameters; ignored if $msg is a Message object
2387 */
2388 public function showErrorPage( $title, $msg, $params = array() ) {
2389 if ( !$title instanceof Message ) {
2390 $title = $this->msg( $title );
2391 }
2392
2393 $this->prepareErrorPage( $title );
2394
2395 if ( $msg instanceof Message ) {
2396 if ( $params !== array() ) {
2397 trigger_error( 'Argument ignored: $params. The message parameters argument '
2398 . 'is discarded when the $msg argument is a Message object instead of '
2399 . 'a string.', E_USER_NOTICE );
2400 }
2401 $this->addHTML( $msg->parseAsBlock() );
2402 } else {
2403 $this->addWikiMsgArray( $msg, $params );
2404 }
2405
2406 $this->returnToMain();
2407 }
2408
2409 /**
2410 * Output a standard permission error page
2411 *
2412 * @param array $errors Error message keys
2413 * @param string $action Action that was denied or null if unknown
2414 */
2415 public function showPermissionsErrorPage( array $errors, $action = null ) {
2416 // For some action (read, edit, create and upload), display a "login to do this action"
2417 // error if all of the following conditions are met:
2418 // 1. the user is not logged in
2419 // 2. the only error is insufficient permissions (i.e. no block or something else)
2420 // 3. the error can be avoided simply by logging in
2421 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2422 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2423 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2424 && ( User::groupHasPermission( 'user', $action )
2425 || User::groupHasPermission( 'autoconfirmed', $action ) )
2426 ) {
2427 $displayReturnto = null;
2428
2429 # Due to bug 32276, if a user does not have read permissions,
2430 # $this->getTitle() will just give Special:Badtitle, which is
2431 # not especially useful as a returnto parameter. Use the title
2432 # from the request instead, if there was one.
2433 $request = $this->getRequest();
2434 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2435 if ( $action == 'edit' ) {
2436 $msg = 'whitelistedittext';
2437 $displayReturnto = $returnto;
2438 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2439 $msg = 'nocreatetext';
2440 } elseif ( $action == 'upload' ) {
2441 $msg = 'uploadnologintext';
2442 } else { # Read
2443 $msg = 'loginreqpagetext';
2444 $displayReturnto = Title::newMainPage();
2445 }
2446
2447 $query = array();
2448
2449 if ( $returnto ) {
2450 $query['returnto'] = $returnto->getPrefixedText();
2451
2452 if ( !$request->wasPosted() ) {
2453 $returntoquery = $request->getValues();
2454 unset( $returntoquery['title'] );
2455 unset( $returntoquery['returnto'] );
2456 unset( $returntoquery['returntoquery'] );
2457 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2458 }
2459 }
2460 $loginLink = Linker::linkKnown(
2461 SpecialPage::getTitleFor( 'Userlogin' ),
2462 $this->msg( 'loginreqlink' )->escaped(),
2463 array(),
2464 $query
2465 );
2466
2467 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2468 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2469
2470 # Don't return to a page the user can't read otherwise
2471 # we'll end up in a pointless loop
2472 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2473 $this->returnToMain( null, $displayReturnto );
2474 }
2475 } else {
2476 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2477 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2478 }
2479 }
2480
2481 /**
2482 * Display an error page indicating that a given version of MediaWiki is
2483 * required to use it
2484 *
2485 * @param mixed $version The version of MediaWiki needed to use the page
2486 */
2487 public function versionRequired( $version ) {
2488 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2489
2490 $this->addWikiMsg( 'versionrequiredtext', $version );
2491 $this->returnToMain();
2492 }
2493
2494 /**
2495 * Display an error page noting that a given permission bit is required.
2496 * @deprecated since 1.18, just throw the exception directly
2497 * @param string $permission Key required
2498 * @throws PermissionsError
2499 */
2500 public function permissionRequired( $permission ) {
2501 wfDeprecated( __METHOD__, '1.18' );
2502 throw new PermissionsError( $permission );
2503 }
2504
2505 /**
2506 * Produce the stock "please login to use the wiki" page
2507 *
2508 * @deprecated since 1.19; throw the exception directly
2509 */
2510 public function loginToUse() {
2511 wfDeprecated( __METHOD__, '1.19' );
2512 throw new PermissionsError( 'read' );
2513 }
2514
2515 /**
2516 * Format a list of error messages
2517 *
2518 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2519 * @param string $action Action that was denied or null if unknown
2520 * @return string The wikitext error-messages, formatted into a list.
2521 */
2522 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2523 if ( $action == null ) {
2524 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2525 } else {
2526 $action_desc = $this->msg( "action-$action" )->plain();
2527 $text = $this->msg(
2528 'permissionserrorstext-withaction',
2529 count( $errors ),
2530 $action_desc
2531 )->plain() . "\n\n";
2532 }
2533
2534 if ( count( $errors ) > 1 ) {
2535 $text .= '<ul class="permissions-errors">' . "\n";
2536
2537 foreach ( $errors as $error ) {
2538 $text .= '<li>';
2539 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2540 $text .= "</li>\n";
2541 }
2542 $text .= '</ul>';
2543 } else {
2544 $text .= "<div class=\"permissions-errors\">\n" .
2545 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2546 "\n</div>";
2547 }
2548
2549 return $text;
2550 }
2551
2552 /**
2553 * Display a page stating that the Wiki is in read-only mode.
2554 * Should only be called after wfReadOnly() has returned true.
2555 *
2556 * Historically, this function was used to show the source of the page that the user
2557 * was trying to edit and _also_ permissions error messages. The relevant code was
2558 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2559 *
2560 * @deprecated since 1.25; throw the exception directly
2561 * @throws ReadOnlyError
2562 */
2563 public function readOnlyPage() {
2564 if ( func_num_args() > 0 ) {
2565 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2566 }
2567
2568 throw new ReadOnlyError;
2569 }
2570
2571 /**
2572 * Turn off regular page output and return an error response
2573 * for when rate limiting has triggered.
2574 *
2575 * @deprecated since 1.25; throw the exception directly
2576 */
2577 public function rateLimited() {
2578 wfDeprecated( __METHOD__, '1.25' );
2579 throw new ThrottledError;
2580 }
2581
2582 /**
2583 * Show a warning about slave lag
2584 *
2585 * If the lag is higher than $wgSlaveLagCritical seconds,
2586 * then the warning is a bit more obvious. If the lag is
2587 * lower than $wgSlaveLagWarning, then no warning is shown.
2588 *
2589 * @param int $lag Slave lag
2590 */
2591 public function showLagWarning( $lag ) {
2592 $config = $this->getConfig();
2593 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2594 $message = $lag < $config->get( 'SlaveLagCritical' )
2595 ? 'lag-warn-normal'
2596 : 'lag-warn-high';
2597 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2598 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2599 }
2600 }
2601
2602 public function showFatalError( $message ) {
2603 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2604
2605 $this->addHTML( $message );
2606 }
2607
2608 public function showUnexpectedValueError( $name, $val ) {
2609 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2610 }
2611
2612 public function showFileCopyError( $old, $new ) {
2613 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2614 }
2615
2616 public function showFileRenameError( $old, $new ) {
2617 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2618 }
2619
2620 public function showFileDeleteError( $name ) {
2621 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2622 }
2623
2624 public function showFileNotFoundError( $name ) {
2625 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2626 }
2627
2628 /**
2629 * Add a "return to" link pointing to a specified title
2630 *
2631 * @param Title $title Title to link
2632 * @param array $query Query string parameters
2633 * @param string $text Text of the link (input is not escaped)
2634 * @param array $options Options array to pass to Linker
2635 */
2636 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2637 $link = $this->msg( 'returnto' )->rawParams(
2638 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2639 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2640 }
2641
2642 /**
2643 * Add a "return to" link pointing to a specified title,
2644 * or the title indicated in the request, or else the main page
2645 *
2646 * @param mixed $unused
2647 * @param Title|string $returnto Title or String to return to
2648 * @param string $returntoquery Query string for the return to link
2649 */
2650 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2651 if ( $returnto == null ) {
2652 $returnto = $this->getRequest()->getText( 'returnto' );
2653 }
2654
2655 if ( $returntoquery == null ) {
2656 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2657 }
2658
2659 if ( $returnto === '' ) {
2660 $returnto = Title::newMainPage();
2661 }
2662
2663 if ( is_object( $returnto ) ) {
2664 $titleObj = $returnto;
2665 } else {
2666 $titleObj = Title::newFromText( $returnto );
2667 }
2668 if ( !is_object( $titleObj ) ) {
2669 $titleObj = Title::newMainPage();
2670 }
2671
2672 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2673 }
2674
2675 /**
2676 * @param Skin $sk The given Skin
2677 * @param bool $includeStyle Unused
2678 * @return string The doctype, opening "<html>", and head element.
2679 */
2680 public function headElement( Skin $sk, $includeStyle = true ) {
2681 global $wgContLang;
2682
2683 $userdir = $this->getLanguage()->getDir();
2684 $sitedir = $wgContLang->getDir();
2685
2686 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2687
2688 if ( $this->getHTMLTitle() == '' ) {
2689 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2690 }
2691
2692 $openHead = Html::openElement( 'head' );
2693 if ( $openHead ) {
2694 # Don't bother with the newline if $head == ''
2695 $ret .= "$openHead\n";
2696 }
2697
2698 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2699 // Add <meta charset="UTF-8">
2700 // This should be before <title> since it defines the charset used by
2701 // text including the text inside <title>.
2702 // The spec recommends defining XHTML5's charset using the XML declaration
2703 // instead of meta.
2704 // Our XML declaration is output by Html::htmlHeader.
2705 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2706 // http://www.whatwg.org/html/semantics.html#charset
2707 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2708 }
2709
2710 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2711 $ret .= $this->getInlineHeadScripts() . "\n";
2712 $ret .= $this->buildCssLinks() . "\n";
2713 $ret .= $this->getExternalHeadScripts() . "\n";
2714
2715 foreach ( $this->getHeadLinksArray() as $item ) {
2716 $ret .= $item . "\n";
2717 }
2718
2719 foreach ( $this->mHeadItems as $item ) {
2720 $ret .= $item . "\n";
2721 }
2722
2723 $closeHead = Html::closeElement( 'head' );
2724 if ( $closeHead ) {
2725 $ret .= "$closeHead\n";
2726 }
2727
2728 $bodyClasses = array();
2729 $bodyClasses[] = 'mediawiki';
2730
2731 # Classes for LTR/RTL directionality support
2732 $bodyClasses[] = $userdir;
2733 $bodyClasses[] = "sitedir-$sitedir";
2734
2735 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2736 # A <body> class is probably not the best way to do this . . .
2737 $bodyClasses[] = 'capitalize-all-nouns';
2738 }
2739
2740 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2741 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2742 $bodyClasses[] =
2743 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2744
2745 $bodyAttrs = array();
2746 // While the implode() is not strictly needed, it's used for backwards compatibility
2747 // (this used to be built as a string and hooks likely still expect that).
2748 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2749
2750 // Allow skins and extensions to add body attributes they need
2751 $sk->addToBodyAttributes( $this, $bodyAttrs );
2752 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2753
2754 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2755
2756 return $ret;
2757 }
2758
2759 /**
2760 * Get a ResourceLoader object associated with this OutputPage
2761 *
2762 * @return ResourceLoader
2763 */
2764 public function getResourceLoader() {
2765 if ( is_null( $this->mResourceLoader ) ) {
2766 $this->mResourceLoader = new ResourceLoader(
2767 $this->getConfig(),
2768 LoggerFactory::getInstance( 'resourceloader' )
2769 );
2770 }
2771 return $this->mResourceLoader;
2772 }
2773
2774 /**
2775 * Construct neccecary html and loader preset states to load modules on a page.
2776 *
2777 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2778 *
2779 * @param array|string $modules One or more module names
2780 * @param string $only ResourceLoaderModule TYPE_ class constant
2781 * @param array $extraQuery [optional] Array with extra query parameters for the request
2782 * @return array A list of HTML strings and array of client loader preset states
2783 */
2784 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array() ) {
2785 $modules = (array)$modules;
2786
2787 $links = array(
2788 // List of html strings
2789 'html' => array(),
2790 // Associative array of module names and their states
2791 'states' => array(),
2792 );
2793
2794 if ( !count( $modules ) ) {
2795 return $links;
2796 }
2797
2798 if ( count( $modules ) > 1 ) {
2799 // Remove duplicate module requests
2800 $modules = array_unique( $modules );
2801 // Sort module names so requests are more uniform
2802 sort( $modules );
2803
2804 if ( ResourceLoader::inDebugMode() ) {
2805 // Recursively call us for every item
2806 foreach ( $modules as $name ) {
2807 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2808 $links['html'] = array_merge( $links['html'], $link['html'] );
2809 $links['states'] += $link['states'];
2810 }
2811 return $links;
2812 }
2813 }
2814
2815 if ( !is_null( $this->mTarget ) ) {
2816 $extraQuery['target'] = $this->mTarget;
2817 }
2818
2819 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2820 $sortedModules = array();
2821 $resourceLoader = $this->getResourceLoader();
2822 foreach ( $modules as $name ) {
2823 $module = $resourceLoader->getModule( $name );
2824 # Check that we're allowed to include this module on this page
2825 if ( !$module
2826 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2827 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2828 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2829 && $only == ResourceLoaderModule::TYPE_STYLES )
2830 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2831 && $only == ResourceLoaderModule::TYPE_COMBINED )
2832 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2833 ) {
2834 continue;
2835 }
2836
2837 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2838 }
2839
2840 foreach ( $sortedModules as $source => $groups ) {
2841 foreach ( $groups as $group => $grpModules ) {
2842 // Special handling for user-specific groups
2843 $user = null;
2844 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2845 $user = $this->getUser()->getName();
2846 }
2847
2848 // Create a fake request based on the one we are about to make so modules return
2849 // correct timestamp and emptiness data
2850 $query = ResourceLoader::makeLoaderQuery(
2851 array(), // modules; not determined yet
2852 $this->getLanguage()->getCode(),
2853 $this->getSkin()->getSkinName(),
2854 $user,
2855 null, // version; not determined yet
2856 ResourceLoader::inDebugMode(),
2857 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2858 $this->isPrintable(),
2859 $this->getRequest()->getBool( 'handheld' ),
2860 $extraQuery
2861 );
2862 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2863
2864 // Extract modules that know they're empty and see if we have one or more
2865 // raw modules
2866 $isRaw = false;
2867 foreach ( $grpModules as $key => $module ) {
2868 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2869 // If we're only getting the styles, we don't need to do anything for empty modules.
2870 if ( $module->isKnownEmpty( $context ) ) {
2871 unset( $grpModules[$key] );
2872 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2873 $links['states'][$key] = 'ready';
2874 }
2875 }
2876
2877 $isRaw |= $module->isRaw();
2878 }
2879
2880 // If there are no non-empty modules, skip this group
2881 if ( count( $grpModules ) === 0 ) {
2882 continue;
2883 }
2884
2885 // Inline private modules. These can't be loaded through load.php for security
2886 // reasons, see bug 34907. Note that these modules should be loaded from
2887 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2888 // properly use them as dependencies (bug 30914)
2889 if ( $group === 'private' ) {
2890 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2891 $links['html'][] = Html::inlineStyle(
2892 $resourceLoader->makeModuleResponse( $context, $grpModules )
2893 );
2894 } else {
2895 $links['html'][] = ResourceLoader::makeInlineScript(
2896 $resourceLoader->makeModuleResponse( $context, $grpModules )
2897 );
2898 }
2899 continue;
2900 }
2901
2902 // Special handling for the user group; because users might change their stuff
2903 // on-wiki like user pages, or user preferences; we need to find the highest
2904 // timestamp of these user-changeable modules so we can ensure cache misses on change
2905 // This should NOT be done for the site group (bug 27564) because anons get that too
2906 // and we shouldn't be putting timestamps in Squid-cached HTML
2907 $version = null;
2908 if ( $group === 'user' ) {
2909 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2910 }
2911
2912 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2913 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2914 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2915
2916 // Automatically select style/script elements
2917 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2918 $link = Html::linkedStyle( $url );
2919 } else {
2920 if ( $context->getRaw() || $isRaw ) {
2921 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2922 $link = Html::element( 'script', array(
2923 // In SpecialJavaScriptTest, QUnit must load synchronous
2924 'async' => !isset( $extraQuery['sync'] ),
2925 'src' => $url
2926 ) );
2927 } else {
2928 $link = ResourceLoader::makeInlineScript(
2929 Xml::encodeJsCall( 'mw.loader.load', array( $url ) )
2930 );
2931 }
2932
2933 // For modules requested directly in the html via <script> or mw.loader.load
2934 // tell mw.loader they are being loading to prevent duplicate requests.
2935 foreach ( $grpModules as $key => $module ) {
2936 // Don't output state=loading for the startup module.
2937 if ( $key !== 'startup' ) {
2938 $links['states'][$key] = 'loading';
2939 }
2940 }
2941 }
2942
2943 if ( $group == 'noscript' ) {
2944 $links['html'][] = Html::rawElement( 'noscript', array(), $link );
2945 } else {
2946 $links['html'][] = $link;
2947 }
2948 }
2949 }
2950
2951 return $links;
2952 }
2953
2954 /**
2955 * Build html output from an array of links from makeResourceLoaderLink.
2956 * @param array $links
2957 * @return string HTML
2958 */
2959 protected static function getHtmlFromLoaderLinks( array $links ) {
2960 $html = array();
2961 $states = array();
2962 foreach ( $links as $link ) {
2963 if ( !is_array( $link ) ) {
2964 $html[] = $link;
2965 } else {
2966 $html = array_merge( $html, $link['html'] );
2967 $states += $link['states'];
2968 }
2969 }
2970 // Filter out empty values
2971 $html = array_filter( $html, 'strlen' );
2972
2973 if ( count( $states ) ) {
2974 array_unshift( $html, ResourceLoader::makeInlineScript(
2975 ResourceLoader::makeLoaderStateScript( $states )
2976 ) );
2977 }
2978
2979 return WrappedString::join( "\n", $html );
2980 }
2981
2982 /**
2983 * JS stuff to put in the "<head>". This is the startup module, config
2984 * vars and modules marked with position 'top'
2985 *
2986 * @return string HTML fragment
2987 */
2988 function getHeadScripts() {
2989 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2990 }
2991
2992 /**
2993 * <script src="..."> tags for "<head>". This is the startup module
2994 * and other modules marked with position 'top'.
2995 *
2996 * @return string HTML fragment
2997 */
2998 function getExternalHeadScripts() {
2999 $links = array();
3000
3001 // Startup - this provides the client with the module
3002 // manifest and loads jquery and mediawiki base modules
3003 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS );
3004
3005 return self::getHtmlFromLoaderLinks( $links );
3006 }
3007
3008 /**
3009 * <script>...</script> tags to put in "<head>".
3010 *
3011 * @return string HTML fragment
3012 */
3013 function getInlineHeadScripts() {
3014 $links = array();
3015
3016 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
3017 // Must be done synchronously on every page to avoid flashes of wrong content.
3018 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
3019 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
3020 // For the performance benefit of the majority, this is added unconditionally here and is
3021 // then fixed up by the startup module for unsupported browsers.
3022 $links[] = Html::inlineScript(
3023 'document.documentElement.className = document.documentElement.className'
3024 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3025 );
3026
3027 // Load config before anything else
3028 $links[] = ResourceLoader::makeInlineScript(
3029 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
3030 );
3031
3032 // Load embeddable private modules before any loader links
3033 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3034 // in mw.loader.implement() calls and deferred until mw.user is available
3035 $embedScripts = array( 'user.options' );
3036 $links[] = $this->makeResourceLoaderLink(
3037 $embedScripts,
3038 ResourceLoaderModule::TYPE_COMBINED
3039 );
3040 // Separate user.tokens as otherwise caching will be allowed (T84960)
3041 $links[] = $this->makeResourceLoaderLink(
3042 'user.tokens',
3043 ResourceLoaderModule::TYPE_COMBINED
3044 );
3045
3046 // Modules requests - let the client calculate dependencies and batch requests as it likes
3047 // Only load modules that have marked themselves for loading at the top
3048 $modules = $this->getModules( true, 'top' );
3049 if ( $modules ) {
3050 $links[] = ResourceLoader::makeInlineScript(
3051 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3052 );
3053 }
3054
3055 // "Scripts only" modules marked for top inclusion
3056 $links[] = $this->makeResourceLoaderLink(
3057 $this->getModuleScripts( true, 'top' ),
3058 ResourceLoaderModule::TYPE_SCRIPTS
3059 );
3060
3061 return self::getHtmlFromLoaderLinks( $links );
3062 }
3063
3064 /**
3065 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3066 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3067 * site JS, and user JS.
3068 *
3069 * @param bool $unused Previously used to let this method change its output based
3070 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3071 * @return string
3072 */
3073 function getScriptsForBottomQueue( $unused = null ) {
3074 // Scripts "only" requests marked for bottom inclusion
3075 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3076 $links = array();
3077
3078 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3079 ResourceLoaderModule::TYPE_SCRIPTS
3080 );
3081
3082 // Modules requests - let the client calculate dependencies and batch requests as it likes
3083 // Only load modules that have marked themselves for loading at the bottom
3084 $modules = $this->getModules( true, 'bottom' );
3085 if ( $modules ) {
3086 $links[] = ResourceLoader::makeInlineScript(
3087 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3088 );
3089 }
3090
3091 // Legacy Scripts
3092 $links[] = $this->mScripts;
3093
3094 // Add user JS if enabled
3095 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3096 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3097 if ( $this->getConfig()->get( 'AllowUserJs' )
3098 && $this->getUser()->isLoggedIn()
3099 && $this->getTitle()
3100 && $this->getTitle()->isJsSubpage()
3101 && $this->userCanPreview()
3102 ) {
3103 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3104 // and include the draft contents as a raw script instead.
3105 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3106 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3107 );
3108 // Load the previewed JS
3109 $links[] = ResourceLoader::makeInlineScript(
3110 Xml::encodeJsCall( 'mw.loader.using', array(
3111 array( 'user', 'site' ),
3112 new XmlJsCode(
3113 'function () {'
3114 . Xml::encodeJsCall( '$.globalEval', array(
3115 $this->getRequest()->getText( 'wpTextbox1' )
3116 ) )
3117 . '}'
3118 )
3119 ) )
3120 );
3121
3122 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3123 // asynchronously and may arrive *after* the inline script here. So the previewed code
3124 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3125 // Similarly, when previewing ./common.js and the user module does arrive first,
3126 // it will arrive without common.js and the inline script runs after.
3127 // Thus running common after the excluded subpage.
3128 } else {
3129 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3130 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3131 }
3132
3133 // Group JS is only enabled if site JS is enabled.
3134 $links[] = $this->makeResourceLoaderLink(
3135 'user.groups',
3136 ResourceLoaderModule::TYPE_COMBINED
3137 );
3138
3139 return self::getHtmlFromLoaderLinks( $links );
3140 }
3141
3142 /**
3143 * JS stuff to put at the bottom of the "<body>"
3144 * @return string
3145 */
3146 function getBottomScripts() {
3147 return $this->getScriptsForBottomQueue();
3148 }
3149
3150 /**
3151 * Get the javascript config vars to include on this page
3152 *
3153 * @return array Array of javascript config vars
3154 * @since 1.23
3155 */
3156 public function getJsConfigVars() {
3157 return $this->mJsConfigVars;
3158 }
3159
3160 /**
3161 * Add one or more variables to be set in mw.config in JavaScript
3162 *
3163 * @param string|array $keys Key or array of key/value pairs
3164 * @param mixed $value [optional] Value of the configuration variable
3165 */
3166 public function addJsConfigVars( $keys, $value = null ) {
3167 if ( is_array( $keys ) ) {
3168 foreach ( $keys as $key => $value ) {
3169 $this->mJsConfigVars[$key] = $value;
3170 }
3171 return;
3172 }
3173
3174 $this->mJsConfigVars[$keys] = $value;
3175 }
3176
3177 /**
3178 * Get an array containing the variables to be set in mw.config in JavaScript.
3179 *
3180 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3181 * - in other words, page-independent/site-wide variables (without state).
3182 * You will only be adding bloat to the html page and causing page caches to
3183 * have to be purged on configuration changes.
3184 * @return array
3185 */
3186 public function getJSVars() {
3187 global $wgContLang;
3188
3189 $curRevisionId = 0;
3190 $articleId = 0;
3191 $canonicalSpecialPageName = false; # bug 21115
3192
3193 $title = $this->getTitle();
3194 $ns = $title->getNamespace();
3195 $canonicalNamespace = MWNamespace::exists( $ns )
3196 ? MWNamespace::getCanonicalName( $ns )
3197 : $title->getNsText();
3198
3199 $sk = $this->getSkin();
3200 // Get the relevant title so that AJAX features can use the correct page name
3201 // when making API requests from certain special pages (bug 34972).
3202 $relevantTitle = $sk->getRelevantTitle();
3203 $relevantUser = $sk->getRelevantUser();
3204
3205 if ( $ns == NS_SPECIAL ) {
3206 list( $canonicalSpecialPageName, /*...*/ ) =
3207 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3208 } elseif ( $this->canUseWikiPage() ) {
3209 $wikiPage = $this->getWikiPage();
3210 $curRevisionId = $wikiPage->getLatest();
3211 $articleId = $wikiPage->getId();
3212 }
3213
3214 $lang = $title->getPageLanguage();
3215
3216 // Pre-process information
3217 $separatorTransTable = $lang->separatorTransformTable();
3218 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3219 $compactSeparatorTransTable = array(
3220 implode( "\t", array_keys( $separatorTransTable ) ),
3221 implode( "\t", $separatorTransTable ),
3222 );
3223 $digitTransTable = $lang->digitTransformTable();
3224 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3225 $compactDigitTransTable = array(
3226 implode( "\t", array_keys( $digitTransTable ) ),
3227 implode( "\t", $digitTransTable ),
3228 );
3229
3230 $user = $this->getUser();
3231
3232 $vars = array(
3233 'wgCanonicalNamespace' => $canonicalNamespace,
3234 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3235 'wgNamespaceNumber' => $title->getNamespace(),
3236 'wgPageName' => $title->getPrefixedDBkey(),
3237 'wgTitle' => $title->getText(),
3238 'wgCurRevisionId' => $curRevisionId,
3239 'wgRevisionId' => (int)$this->getRevisionId(),
3240 'wgArticleId' => $articleId,
3241 'wgIsArticle' => $this->isArticle(),
3242 'wgIsRedirect' => $title->isRedirect(),
3243 'wgAction' => Action::getActionName( $this->getContext() ),
3244 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3245 'wgUserGroups' => $user->getEffectiveGroups(),
3246 'wgCategories' => $this->getCategories(),
3247 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3248 'wgPageContentLanguage' => $lang->getCode(),
3249 'wgPageContentModel' => $title->getContentModel(),
3250 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3251 'wgDigitTransformTable' => $compactDigitTransTable,
3252 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3253 'wgMonthNames' => $lang->getMonthNamesArray(),
3254 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3255 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3256 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3257 );
3258
3259 if ( $user->isLoggedIn() ) {
3260 $vars['wgUserId'] = $user->getId();
3261 $vars['wgUserEditCount'] = $user->getEditCount();
3262 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3263 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3264 // Get the revision ID of the oldest new message on the user's talk
3265 // page. This can be used for constructing new message alerts on
3266 // the client side.
3267 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3268 }
3269
3270 if ( $wgContLang->hasVariants() ) {
3271 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3272 }
3273 // Same test as SkinTemplate
3274 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3275 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3276
3277 foreach ( $title->getRestrictionTypes() as $type ) {
3278 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3279 }
3280
3281 if ( $title->isMainPage() ) {
3282 $vars['wgIsMainPage'] = true;
3283 }
3284
3285 if ( $this->mRedirectedFrom ) {
3286 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3287 }
3288
3289 if ( $relevantUser ) {
3290 $vars['wgRelevantUserName'] = $relevantUser->getName();
3291 }
3292
3293 // Allow extensions to add their custom variables to the mw.config map.
3294 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3295 // page-dependant but site-wide (without state).
3296 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3297 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3298
3299 // Merge in variables from addJsConfigVars last
3300 return array_merge( $vars, $this->getJsConfigVars() );
3301 }
3302
3303 /**
3304 * To make it harder for someone to slip a user a fake
3305 * user-JavaScript or user-CSS preview, a random token
3306 * is associated with the login session. If it's not
3307 * passed back with the preview request, we won't render
3308 * the code.
3309 *
3310 * @return bool
3311 */
3312 public function userCanPreview() {
3313 $request = $this->getRequest();
3314 if (
3315 $request->getVal( 'action' ) !== 'submit' ||
3316 !$request->getCheck( 'wpPreview' ) ||
3317 !$request->wasPosted()
3318 ) {
3319 return false;
3320 }
3321
3322 $user = $this->getUser();
3323 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3324 return false;
3325 }
3326
3327 $title = $this->getTitle();
3328 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3329 return false;
3330 }
3331 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3332 // Don't execute another user's CSS or JS on preview (T85855)
3333 return false;
3334 }
3335
3336 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3337 if ( count( $errors ) !== 0 ) {
3338 return false;
3339 }
3340
3341 return true;
3342 }
3343
3344 /**
3345 * @return array Array in format "link name or number => 'link html'".
3346 */
3347 public function getHeadLinksArray() {
3348 global $wgVersion;
3349
3350 $tags = array();
3351 $config = $this->getConfig();
3352
3353 $canonicalUrl = $this->mCanonicalUrl;
3354
3355 $tags['meta-generator'] = Html::element( 'meta', array(
3356 'name' => 'generator',
3357 'content' => "MediaWiki $wgVersion",
3358 ) );
3359
3360 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3361 $tags['meta-referrer'] = Html::element( 'meta', array(
3362 'name' => 'referrer',
3363 'content' => $config->get( 'ReferrerPolicy' )
3364 ) );
3365 }
3366
3367 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3368 if ( $p !== 'index,follow' ) {
3369 // http://www.robotstxt.org/wc/meta-user.html
3370 // Only show if it's different from the default robots policy
3371 $tags['meta-robots'] = Html::element( 'meta', array(
3372 'name' => 'robots',
3373 'content' => $p,
3374 ) );
3375 }
3376
3377 foreach ( $this->mMetatags as $tag ) {
3378 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3379 $a = 'http-equiv';
3380 $tag[0] = substr( $tag[0], 5 );
3381 } else {
3382 $a = 'name';
3383 }
3384 $tagName = "meta-{$tag[0]}";
3385 if ( isset( $tags[$tagName] ) ) {
3386 $tagName .= $tag[1];
3387 }
3388 $tags[$tagName] = Html::element( 'meta',
3389 array(
3390 $a => $tag[0],
3391 'content' => $tag[1]
3392 )
3393 );
3394 }
3395
3396 foreach ( $this->mLinktags as $tag ) {
3397 $tags[] = Html::element( 'link', $tag );
3398 }
3399
3400 # Universal edit button
3401 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3402 $user = $this->getUser();
3403 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3404 && ( $this->getTitle()->exists() ||
3405 $this->getTitle()->quickUserCan( 'create', $user ) )
3406 ) {
3407 // Original UniversalEditButton
3408 $msg = $this->msg( 'edit' )->text();
3409 $tags['universal-edit-button'] = Html::element( 'link', array(
3410 'rel' => 'alternate',
3411 'type' => 'application/x-wiki',
3412 'title' => $msg,
3413 'href' => $this->getTitle()->getEditURL(),
3414 ) );
3415 // Alternate edit link
3416 $tags['alternative-edit'] = Html::element( 'link', array(
3417 'rel' => 'edit',
3418 'title' => $msg,
3419 'href' => $this->getTitle()->getEditURL(),
3420 ) );
3421 }
3422 }
3423
3424 # Generally the order of the favicon and apple-touch-icon links
3425 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3426 # uses whichever one appears later in the HTML source. Make sure
3427 # apple-touch-icon is specified first to avoid this.
3428 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3429 $tags['apple-touch-icon'] = Html::element( 'link', array(
3430 'rel' => 'apple-touch-icon',
3431 'href' => $config->get( 'AppleTouchIcon' )
3432 ) );
3433 }
3434
3435 if ( $config->get( 'Favicon' ) !== false ) {
3436 $tags['favicon'] = Html::element( 'link', array(
3437 'rel' => 'shortcut icon',
3438 'href' => $config->get( 'Favicon' )
3439 ) );
3440 }
3441
3442 # OpenSearch description link
3443 $tags['opensearch'] = Html::element( 'link', array(
3444 'rel' => 'search',
3445 'type' => 'application/opensearchdescription+xml',
3446 'href' => wfScript( 'opensearch_desc' ),
3447 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3448 ) );
3449
3450 if ( $config->get( 'EnableAPI' ) ) {
3451 # Real Simple Discovery link, provides auto-discovery information
3452 # for the MediaWiki API (and potentially additional custom API
3453 # support such as WordPress or Twitter-compatible APIs for a
3454 # blogging extension, etc)
3455 $tags['rsd'] = Html::element( 'link', array(
3456 'rel' => 'EditURI',
3457 'type' => 'application/rsd+xml',
3458 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3459 // Whether RSD accepts relative or protocol-relative URLs is completely
3460 // undocumented, though.
3461 'href' => wfExpandUrl( wfAppendQuery(
3462 wfScript( 'api' ),
3463 array( 'action' => 'rsd' ) ),
3464 PROTO_RELATIVE
3465 ),
3466 ) );
3467 }
3468
3469 # Language variants
3470 if ( !$config->get( 'DisableLangConversion' ) ) {
3471 $lang = $this->getTitle()->getPageLanguage();
3472 if ( $lang->hasVariants() ) {
3473 $variants = $lang->getVariants();
3474 foreach ( $variants as $variant ) {
3475 $tags["variant-$variant"] = Html::element( 'link', array(
3476 'rel' => 'alternate',
3477 'hreflang' => wfBCP47( $variant ),
3478 'href' => $this->getTitle()->getLocalURL(
3479 array( 'variant' => $variant ) )
3480 )
3481 );
3482 }
3483 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3484 $tags["variant-x-default"] = Html::element( 'link', array(
3485 'rel' => 'alternate',
3486 'hreflang' => 'x-default',
3487 'href' => $this->getTitle()->getLocalURL() ) );
3488 }
3489 }
3490
3491 # Copyright
3492 if ( $this->copyrightUrl !== null ) {
3493 $copyright = $this->copyrightUrl;
3494 } else {
3495 $copyright = '';
3496 if ( $config->get( 'RightsPage' ) ) {
3497 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3498
3499 if ( $copy ) {
3500 $copyright = $copy->getLocalURL();
3501 }
3502 }
3503
3504 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3505 $copyright = $config->get( 'RightsUrl' );
3506 }
3507 }
3508
3509 if ( $copyright ) {
3510 $tags['copyright'] = Html::element( 'link', array(
3511 'rel' => 'copyright',
3512 'href' => $copyright )
3513 );
3514 }
3515
3516 # Feeds
3517 if ( $config->get( 'Feed' ) ) {
3518 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3519 # Use the page name for the title. In principle, this could
3520 # lead to issues with having the same name for different feeds
3521 # corresponding to the same page, but we can't avoid that at
3522 # this low a level.
3523
3524 $tags[] = $this->feedLink(
3525 $format,
3526 $link,
3527 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3528 $this->msg(
3529 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3530 )->text()
3531 );
3532 }
3533
3534 # Recent changes feed should appear on every page (except recentchanges,
3535 # that would be redundant). Put it after the per-page feed to avoid
3536 # changing existing behavior. It's still available, probably via a
3537 # menu in your browser. Some sites might have a different feed they'd
3538 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3539 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3540 # If so, use it instead.
3541 $sitename = $config->get( 'Sitename' );
3542 if ( $config->get( 'OverrideSiteFeed' ) ) {
3543 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3544 // Note, this->feedLink escapes the url.
3545 $tags[] = $this->feedLink(
3546 $type,
3547 $feedUrl,
3548 $this->msg( "site-{$type}-feed", $sitename )->text()
3549 );
3550 }
3551 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3552 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3553 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3554 $tags[] = $this->feedLink(
3555 $format,
3556 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3557 # For grep: 'site-rss-feed', 'site-atom-feed'
3558 $this->msg( "site-{$format}-feed", $sitename )->text()
3559 );
3560 }
3561 }
3562 }
3563
3564 # Canonical URL
3565 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3566 if ( $canonicalUrl !== false ) {
3567 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3568 } else {
3569 if ( $this->isArticleRelated() ) {
3570 // This affects all requests where "setArticleRelated" is true. This is
3571 // typically all requests that show content (query title, curid, oldid, diff),
3572 // and all wikipage actions (edit, delete, purge, info, history etc.).
3573 // It does not apply to File pages and Special pages.
3574 // 'history' and 'info' actions address page metadata rather than the page
3575 // content itself, so they may not be canonicalized to the view page url.
3576 // TODO: this ought to be better encapsulated in the Action class.
3577 $action = Action::getActionName( $this->getContext() );
3578 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3579 $query = "action={$action}";
3580 } else {
3581 $query = '';
3582 }
3583 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3584 } else {
3585 $reqUrl = $this->getRequest()->getRequestURL();
3586 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3587 }
3588 }
3589 }
3590 if ( $canonicalUrl !== false ) {
3591 $tags[] = Html::element( 'link', array(
3592 'rel' => 'canonical',
3593 'href' => $canonicalUrl
3594 ) );
3595 }
3596
3597 return $tags;
3598 }
3599
3600 /**
3601 * @return string HTML tag links to be put in the header.
3602 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3603 * OutputPage::getHeadLinksArray directly.
3604 */
3605 public function getHeadLinks() {
3606 wfDeprecated( __METHOD__, '1.24' );
3607 return implode( "\n", $this->getHeadLinksArray() );
3608 }
3609
3610 /**
3611 * Generate a "<link rel/>" for a feed.
3612 *
3613 * @param string $type Feed type
3614 * @param string $url URL to the feed
3615 * @param string $text Value of the "title" attribute
3616 * @return string HTML fragment
3617 */
3618 private function feedLink( $type, $url, $text ) {
3619 return Html::element( 'link', array(
3620 'rel' => 'alternate',
3621 'type' => "application/$type+xml",
3622 'title' => $text,
3623 'href' => $url )
3624 );
3625 }
3626
3627 /**
3628 * Add a local or specified stylesheet, with the given media options.
3629 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3630 *
3631 * @param string $style URL to the file
3632 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3633 * @param string $condition For IE conditional comments, specifying an IE version
3634 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3635 */
3636 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3637 $options = array();
3638 // Even though we expect the media type to be lowercase, but here we
3639 // force it to lowercase to be safe.
3640 if ( $media ) {
3641 $options['media'] = $media;
3642 }
3643 if ( $condition ) {
3644 $options['condition'] = $condition;
3645 }
3646 if ( $dir ) {
3647 $options['dir'] = $dir;
3648 }
3649 $this->styles[$style] = $options;
3650 }
3651
3652 /**
3653 * Adds inline CSS styles
3654 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3655 *
3656 * @param mixed $style_css Inline CSS
3657 * @param string $flip Set to 'flip' to flip the CSS if needed
3658 */
3659 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3660 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3661 # If wanted, and the interface is right-to-left, flip the CSS
3662 $style_css = CSSJanus::transform( $style_css, true, false );
3663 }
3664 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3665 }
3666
3667 /**
3668 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3669 * These will be applied to various media & IE conditionals.
3670 *
3671 * @return string
3672 */
3673 public function buildCssLinks() {
3674 global $wgContLang;
3675
3676 $this->getSkin()->setupSkinUserCss( $this );
3677
3678 // Add ResourceLoader styles
3679 // Split the styles into these groups
3680 $styles = array(
3681 'other' => array(),
3682 'user' => array(),
3683 'site' => array(),
3684 'private' => array(),
3685 'noscript' => array()
3686 );
3687 $links = array();
3688 $otherTags = array(); // Tags to append after the normal <link> tags
3689 $resourceLoader = $this->getResourceLoader();
3690
3691 $moduleStyles = $this->getModuleStyles();
3692
3693 // Per-site custom styles
3694 $moduleStyles[] = 'site';
3695 $moduleStyles[] = 'noscript';
3696 $moduleStyles[] = 'user.groups';
3697
3698 // Per-user custom styles
3699 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3700 && $this->userCanPreview()
3701 ) {
3702 // We're on a preview of a CSS subpage
3703 // Exclude this page from the user module in case it's in there (bug 26283)
3704 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES,
3705 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3706 );
3707 $otherTags = array_merge( $otherTags, $link['html'] );
3708
3709 // Load the previewed CSS
3710 // If needed, Janus it first. This is user-supplied CSS, so it's
3711 // assumed to be right for the content language directionality.
3712 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3713 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3714 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3715 }
3716 $otherTags[] = Html::inlineStyle( $previewedCSS ) . "\n";
3717 } else {
3718 // Load the user styles normally
3719 $moduleStyles[] = 'user';
3720 }
3721
3722 // Per-user preference styles
3723 $moduleStyles[] = 'user.cssprefs';
3724
3725 foreach ( $moduleStyles as $name ) {
3726 $module = $resourceLoader->getModule( $name );
3727 if ( !$module ) {
3728 continue;
3729 }
3730 if ( $name === 'site' ) {
3731 // HACK: The site module shouldn't be fragmented with a cache group and
3732 // http request. But in order to ensure its styles are separated and after the
3733 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3734 // The scripts remain ungrouped and rides the bottom queue.
3735 $styles['site'][] = $name;
3736 continue;
3737 }
3738 $group = $module->getGroup();
3739 // Modules in groups other than the ones needing special treatment
3740 // (see $styles assignment)
3741 // will be placed in the "other" style category.
3742 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3743 }
3744
3745 // We want site, private and user styles to override dynamically added
3746 // styles from modules, but we want dynamically added styles to override
3747 // statically added styles from other modules. So the order has to be
3748 // other, dynamic, site, private, user. Add statically added styles for
3749 // other modules
3750 $links[] = $this->makeResourceLoaderLink(
3751 $styles['other'],
3752 ResourceLoaderModule::TYPE_STYLES
3753 );
3754 // Add normal styles added through addStyle()/addInlineStyle() here
3755 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3756 // Add marker tag to mark the place where the client-side
3757 // loader should inject dynamic styles
3758 // We use a <meta> tag with a made-up name for this because that's valid HTML
3759 $links[] = Html::element(
3760 'meta',
3761 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3762 );
3763
3764 // Add site-specific and user-specific styles
3765 // 'private' at present only contains user.options, so put that before 'user'
3766 // Any future private modules will likely have a similar user-specific character
3767 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3768 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3769 ResourceLoaderModule::TYPE_STYLES
3770 );
3771 }
3772
3773 // Add stuff in $otherTags (previewed user CSS if applicable)
3774 return self::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3775 }
3776
3777 /**
3778 * @return array
3779 */
3780 public function buildCssLinksArray() {
3781 $links = array();
3782
3783 // Add any extension CSS
3784 foreach ( $this->mExtStyles as $url ) {
3785 $this->addStyle( $url );
3786 }
3787 $this->mExtStyles = array();
3788
3789 foreach ( $this->styles as $file => $options ) {
3790 $link = $this->styleLink( $file, $options );
3791 if ( $link ) {
3792 $links[$file] = $link;
3793 }
3794 }
3795 return $links;
3796 }
3797
3798 /**
3799 * Generate \<link\> tags for stylesheets
3800 *
3801 * @param string $style URL to the file
3802 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3803 * @return string HTML fragment
3804 */
3805 protected function styleLink( $style, array $options ) {
3806 if ( isset( $options['dir'] ) ) {
3807 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3808 return '';
3809 }
3810 }
3811
3812 if ( isset( $options['media'] ) ) {
3813 $media = self::transformCssMedia( $options['media'] );
3814 if ( is_null( $media ) ) {
3815 return '';
3816 }
3817 } else {
3818 $media = 'all';
3819 }
3820
3821 if ( substr( $style, 0, 1 ) == '/' ||
3822 substr( $style, 0, 5 ) == 'http:' ||
3823 substr( $style, 0, 6 ) == 'https:' ) {
3824 $url = $style;
3825 } else {
3826 $config = $this->getConfig();
3827 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3828 $config->get( 'StyleVersion' );
3829 }
3830
3831 $link = Html::linkedStyle( $url, $media );
3832
3833 if ( isset( $options['condition'] ) ) {
3834 $condition = htmlspecialchars( $options['condition'] );
3835 $link = "<!--[if $condition]>$link<![endif]-->";
3836 }
3837 return $link;
3838 }
3839
3840 /**
3841 * Transform "media" attribute based on request parameters
3842 *
3843 * @param string $media Current value of the "media" attribute
3844 * @return string Modified value of the "media" attribute, or null to skip
3845 * this stylesheet
3846 */
3847 public static function transformCssMedia( $media ) {
3848 global $wgRequest;
3849
3850 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3851 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3852
3853 // Switch in on-screen display for media testing
3854 $switches = array(
3855 'printable' => 'print',
3856 'handheld' => 'handheld',
3857 );
3858 foreach ( $switches as $switch => $targetMedia ) {
3859 if ( $wgRequest->getBool( $switch ) ) {
3860 if ( $media == $targetMedia ) {
3861 $media = '';
3862 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3863 /* This regex will not attempt to understand a comma-separated media_query_list
3864 *
3865 * Example supported values for $media:
3866 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3867 * Example NOT supported value for $media:
3868 * '3d-glasses, screen, print and resolution > 90dpi'
3869 *
3870 * If it's a print request, we never want any kind of screen stylesheets
3871 * If it's a handheld request (currently the only other choice with a switch),
3872 * we don't want simple 'screen' but we might want screen queries that
3873 * have a max-width or something, so we'll pass all others on and let the
3874 * client do the query.
3875 */
3876 if ( $targetMedia == 'print' || $media == 'screen' ) {
3877 return null;
3878 }
3879 }
3880 }
3881 }
3882
3883 return $media;
3884 }
3885
3886 /**
3887 * Add a wikitext-formatted message to the output.
3888 * This is equivalent to:
3889 *
3890 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3891 */
3892 public function addWikiMsg( /*...*/ ) {
3893 $args = func_get_args();
3894 $name = array_shift( $args );
3895 $this->addWikiMsgArray( $name, $args );
3896 }
3897
3898 /**
3899 * Add a wikitext-formatted message to the output.
3900 * Like addWikiMsg() except the parameters are taken as an array
3901 * instead of a variable argument list.
3902 *
3903 * @param string $name
3904 * @param array $args
3905 */
3906 public function addWikiMsgArray( $name, $args ) {
3907 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3908 }
3909
3910 /**
3911 * This function takes a number of message/argument specifications, wraps them in
3912 * some overall structure, and then parses the result and adds it to the output.
3913 *
3914 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3915 * and so on. The subsequent arguments may be either
3916 * 1) strings, in which case they are message names, or
3917 * 2) arrays, in which case, within each array, the first element is the message
3918 * name, and subsequent elements are the parameters to that message.
3919 *
3920 * Don't use this for messages that are not in the user's interface language.
3921 *
3922 * For example:
3923 *
3924 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3925 *
3926 * Is equivalent to:
3927 *
3928 * $wgOut->addWikiText( "<div class='error'>\n"
3929 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3930 *
3931 * The newline after the opening div is needed in some wikitext. See bug 19226.
3932 *
3933 * @param string $wrap
3934 */
3935 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3936 $msgSpecs = func_get_args();
3937 array_shift( $msgSpecs );
3938 $msgSpecs = array_values( $msgSpecs );
3939 $s = $wrap;
3940 foreach ( $msgSpecs as $n => $spec ) {
3941 if ( is_array( $spec ) ) {
3942 $args = $spec;
3943 $name = array_shift( $args );
3944 if ( isset( $args['options'] ) ) {
3945 unset( $args['options'] );
3946 wfDeprecated(
3947 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3948 '1.20'
3949 );
3950 }
3951 } else {
3952 $args = array();
3953 $name = $spec;
3954 }
3955 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3956 }
3957 $this->addWikiText( $s );
3958 }
3959
3960 /**
3961 * Include jQuery core. Use this to avoid loading it multiple times
3962 * before we get a usable script loader.
3963 *
3964 * @param array $modules List of jQuery modules which should be loaded
3965 * @return array The list of modules which were not loaded.
3966 * @since 1.16
3967 * @deprecated since 1.17
3968 */
3969 public function includeJQuery( array $modules = array() ) {
3970 wfDeprecated( __METHOD__, '1.17' );
3971 return array();
3972 }
3973
3974 /**
3975 * Enables/disables TOC, doesn't override __NOTOC__
3976 * @param bool $flag
3977 * @since 1.22
3978 */
3979 public function enableTOC( $flag = true ) {
3980 $this->mEnableTOC = $flag;
3981 }
3982
3983 /**
3984 * @return bool
3985 * @since 1.22
3986 */
3987 public function isTOCEnabled() {
3988 return $this->mEnableTOC;
3989 }
3990
3991 /**
3992 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3993 * @param bool $flag
3994 * @since 1.23
3995 */
3996 public function enableSectionEditLinks( $flag = true ) {
3997 $this->mEnableSectionEditLinks = $flag;
3998 }
3999
4000 /**
4001 * @return bool
4002 * @since 1.23
4003 */
4004 public function sectionEditLinksEnabled() {
4005 return $this->mEnableSectionEditLinks;
4006 }
4007
4008 /**
4009 * Helper function to setup the PHP implementation of OOUI to use in this request.
4010 *
4011 * @since 1.26
4012 * @param String $skinName The Skin name to determine the correct OOUI theme
4013 * @param String $dir Language direction
4014 */
4015 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4016 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
4017 // Make keys (skin names) lowercase for case-insensitive matching.
4018 $themes = array_change_key_case( $themes, CASE_LOWER );
4019 $theme = isset( $themes[$skinName] ) ? $themes[$skinName] : 'MediaWiki';
4020 // For example, 'OOUI\MediaWikiTheme'.
4021 $themeClass = "OOUI\\{$theme}Theme";
4022 OOUI\Theme::setSingleton( new $themeClass() );
4023 OOUI\Element::setDefaultDir( $dir );
4024 }
4025
4026 /**
4027 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4028 * MediaWiki and this OutputPage instance.
4029 *
4030 * @since 1.25
4031 */
4032 public function enableOOUI() {
4033 self::setupOOUI(
4034 strtolower( $this->getSkin()->getSkinName() ),
4035 $this->getLanguage()->getDir()
4036 );
4037 $this->addModuleStyles( array(
4038 'oojs-ui.styles',
4039 'oojs-ui.styles.icons',
4040 'oojs-ui.styles.indicators',
4041 'oojs-ui.styles.textures',
4042 'mediawiki.widgets.styles',
4043 ) );
4044 }
4045 }