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