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