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