Merge "Add image/pjpeg as an alias for image/jpeg"
[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 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
813 $clientHeaderTime = strtotime( $clientHeader );
814 MediaWiki\restoreWarnings();
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 Not Modified 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()->statusHeader( 304 );
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 $response->statusHeader( $code );
2224 }
2225 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2226 }
2227 if ( $config->get( 'VaryOnXFP' ) ) {
2228 $this->addVaryHeader( 'X-Forwarded-Proto' );
2229 }
2230 $this->sendCacheControl();
2231
2232 $response->header( "Content-Type: text/html; charset=utf-8" );
2233 if ( $config->get( 'DebugRedirects' ) ) {
2234 $url = htmlspecialchars( $redirect );
2235 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2236 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2237 print "</body>\n</html>\n";
2238 } else {
2239 $response->header( 'Location: ' . $redirect );
2240 }
2241 }
2242
2243 return;
2244 } elseif ( $this->mStatusCode ) {
2245 $response->statusHeader( $this->mStatusCode );
2246 }
2247
2248 # Buffer output; final headers may depend on later processing
2249 ob_start();
2250
2251 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2252 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2253
2254 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2255 // jQuery etc. can work correctly.
2256 $response->header( 'X-UA-Compatible: IE=Edge' );
2257
2258 // Prevent framing, if requested
2259 $frameOptions = $this->getFrameOptions();
2260 if ( $frameOptions ) {
2261 $response->header( "X-Frame-Options: $frameOptions" );
2262 }
2263
2264 if ( $this->mArticleBodyOnly ) {
2265 echo $this->mBodytext;
2266 } else {
2267
2268 $sk = $this->getSkin();
2269 // add skin specific modules
2270 $modules = $sk->getDefaultModules();
2271
2272 // enforce various default modules for all skins
2273 $coreModules = array(
2274 // keep this list as small as possible
2275 'mediawiki.page.startup',
2276 'mediawiki.user',
2277 );
2278
2279 // Support for high-density display images if enabled
2280 if ( $config->get( 'ResponsiveImages' ) ) {
2281 $coreModules[] = 'mediawiki.hidpi';
2282 }
2283
2284 $this->addModules( $coreModules );
2285 foreach ( $modules as $group ) {
2286 $this->addModules( $group );
2287 }
2288 MWDebug::addModules( $this );
2289
2290 // Hook that allows last minute changes to the output page, e.g.
2291 // adding of CSS or Javascript by extensions.
2292 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2293
2294 $sk->outputPage();
2295 }
2296
2297 // This hook allows last minute changes to final overall output by modifying output buffer
2298 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2299
2300 $this->sendCacheControl();
2301
2302 ob_end_flush();
2303
2304 }
2305
2306 /**
2307 * Actually output something with print.
2308 *
2309 * @param string $ins The string to output
2310 * @deprecated since 1.22 Use echo yourself.
2311 */
2312 public function out( $ins ) {
2313 wfDeprecated( __METHOD__, '1.22' );
2314 print $ins;
2315 }
2316
2317 /**
2318 * Produce a "user is blocked" page.
2319 * @deprecated since 1.18
2320 */
2321 function blockedPage() {
2322 throw new UserBlockedError( $this->getUser()->mBlock );
2323 }
2324
2325 /**
2326 * Prepare this object to display an error page; disable caching and
2327 * indexing, clear the current text and redirect, set the page's title
2328 * and optionally an custom HTML title (content of the "<title>" tag).
2329 *
2330 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2331 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2332 * optional, if not passed the "<title>" attribute will be
2333 * based on $pageTitle
2334 */
2335 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2336 $this->setPageTitle( $pageTitle );
2337 if ( $htmlTitle !== false ) {
2338 $this->setHTMLTitle( $htmlTitle );
2339 }
2340 $this->setRobotPolicy( 'noindex,nofollow' );
2341 $this->setArticleRelated( false );
2342 $this->enableClientCache( false );
2343 $this->mRedirect = '';
2344 $this->clearSubtitle();
2345 $this->clearHTML();
2346 }
2347
2348 /**
2349 * Output a standard error page
2350 *
2351 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2352 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2353 * showErrorPage( 'titlemsg', $messageObject );
2354 * showErrorPage( $titleMessageObject, $messageObject );
2355 *
2356 * @param string|Message $title Message key (string) for page title, or a Message object
2357 * @param string|Message $msg Message key (string) for page text, or a Message object
2358 * @param array $params Message parameters; ignored if $msg is a Message object
2359 */
2360 public function showErrorPage( $title, $msg, $params = array() ) {
2361 if ( !$title instanceof Message ) {
2362 $title = $this->msg( $title );
2363 }
2364
2365 $this->prepareErrorPage( $title );
2366
2367 if ( $msg instanceof Message ) {
2368 if ( $params !== array() ) {
2369 trigger_error( 'Argument ignored: $params. The message parameters argument '
2370 . 'is discarded when the $msg argument is a Message object instead of '
2371 . 'a string.', E_USER_NOTICE );
2372 }
2373 $this->addHTML( $msg->parseAsBlock() );
2374 } else {
2375 $this->addWikiMsgArray( $msg, $params );
2376 }
2377
2378 $this->returnToMain();
2379 }
2380
2381 /**
2382 * Output a standard permission error page
2383 *
2384 * @param array $errors Error message keys
2385 * @param string $action Action that was denied or null if unknown
2386 */
2387 public function showPermissionsErrorPage( array $errors, $action = null ) {
2388 // For some action (read, edit, create and upload), display a "login to do this action"
2389 // error if all of the following conditions are met:
2390 // 1. the user is not logged in
2391 // 2. the only error is insufficient permissions (i.e. no block or something else)
2392 // 3. the error can be avoided simply by logging in
2393 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2394 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2395 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2396 && ( User::groupHasPermission( 'user', $action )
2397 || User::groupHasPermission( 'autoconfirmed', $action ) )
2398 ) {
2399 $displayReturnto = null;
2400
2401 # Due to bug 32276, if a user does not have read permissions,
2402 # $this->getTitle() will just give Special:Badtitle, which is
2403 # not especially useful as a returnto parameter. Use the title
2404 # from the request instead, if there was one.
2405 $request = $this->getRequest();
2406 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2407 if ( $action == 'edit' ) {
2408 $msg = 'whitelistedittext';
2409 $displayReturnto = $returnto;
2410 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2411 $msg = 'nocreatetext';
2412 } elseif ( $action == 'upload' ) {
2413 $msg = 'uploadnologintext';
2414 } else { # Read
2415 $msg = 'loginreqpagetext';
2416 $displayReturnto = Title::newMainPage();
2417 }
2418
2419 $query = array();
2420
2421 if ( $returnto ) {
2422 $query['returnto'] = $returnto->getPrefixedText();
2423
2424 if ( !$request->wasPosted() ) {
2425 $returntoquery = $request->getValues();
2426 unset( $returntoquery['title'] );
2427 unset( $returntoquery['returnto'] );
2428 unset( $returntoquery['returntoquery'] );
2429 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2430 }
2431 }
2432 $loginLink = Linker::linkKnown(
2433 SpecialPage::getTitleFor( 'Userlogin' ),
2434 $this->msg( 'loginreqlink' )->escaped(),
2435 array(),
2436 $query
2437 );
2438
2439 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2440 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2441
2442 # Don't return to a page the user can't read otherwise
2443 # we'll end up in a pointless loop
2444 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2445 $this->returnToMain( null, $displayReturnto );
2446 }
2447 } else {
2448 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2449 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2450 }
2451 }
2452
2453 /**
2454 * Display an error page indicating that a given version of MediaWiki is
2455 * required to use it
2456 *
2457 * @param mixed $version The version of MediaWiki needed to use the page
2458 */
2459 public function versionRequired( $version ) {
2460 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2461
2462 $this->addWikiMsg( 'versionrequiredtext', $version );
2463 $this->returnToMain();
2464 }
2465
2466 /**
2467 * Display an error page noting that a given permission bit is required.
2468 * @deprecated since 1.18, just throw the exception directly
2469 * @param string $permission Key required
2470 * @throws PermissionsError
2471 */
2472 public function permissionRequired( $permission ) {
2473 throw new PermissionsError( $permission );
2474 }
2475
2476 /**
2477 * Produce the stock "please login to use the wiki" page
2478 *
2479 * @deprecated since 1.19; throw the exception directly
2480 */
2481 public function loginToUse() {
2482 throw new PermissionsError( 'read' );
2483 }
2484
2485 /**
2486 * Format a list of error messages
2487 *
2488 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2489 * @param string $action Action that was denied or null if unknown
2490 * @return string The wikitext error-messages, formatted into a list.
2491 */
2492 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2493 if ( $action == null ) {
2494 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2495 } else {
2496 $action_desc = $this->msg( "action-$action" )->plain();
2497 $text = $this->msg(
2498 'permissionserrorstext-withaction',
2499 count( $errors ),
2500 $action_desc
2501 )->plain() . "\n\n";
2502 }
2503
2504 if ( count( $errors ) > 1 ) {
2505 $text .= '<ul class="permissions-errors">' . "\n";
2506
2507 foreach ( $errors as $error ) {
2508 $text .= '<li>';
2509 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2510 $text .= "</li>\n";
2511 }
2512 $text .= '</ul>';
2513 } else {
2514 $text .= "<div class=\"permissions-errors\">\n" .
2515 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2516 "\n</div>";
2517 }
2518
2519 return $text;
2520 }
2521
2522 /**
2523 * Display a page stating that the Wiki is in read-only mode.
2524 * Should only be called after wfReadOnly() has returned true.
2525 *
2526 * Historically, this function was used to show the source of the page that the user
2527 * was trying to edit and _also_ permissions error messages. The relevant code was
2528 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2529 *
2530 * @deprecated since 1.25; throw the exception directly
2531 * @throws ReadOnlyError
2532 */
2533 public function readOnlyPage() {
2534 if ( func_num_args() > 0 ) {
2535 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2536 }
2537
2538 throw new ReadOnlyError;
2539 }
2540
2541 /**
2542 * Turn off regular page output and return an error response
2543 * for when rate limiting has triggered.
2544 *
2545 * @deprecated since 1.25; throw the exception directly
2546 */
2547 public function rateLimited() {
2548 wfDeprecated( __METHOD__, '1.25' );
2549 throw new ThrottledError;
2550 }
2551
2552 /**
2553 * Show a warning about slave lag
2554 *
2555 * If the lag is higher than $wgSlaveLagCritical seconds,
2556 * then the warning is a bit more obvious. If the lag is
2557 * lower than $wgSlaveLagWarning, then no warning is shown.
2558 *
2559 * @param int $lag Slave lag
2560 */
2561 public function showLagWarning( $lag ) {
2562 $config = $this->getConfig();
2563 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2564 $message = $lag < $config->get( 'SlaveLagCritical' )
2565 ? 'lag-warn-normal'
2566 : 'lag-warn-high';
2567 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2568 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2569 }
2570 }
2571
2572 public function showFatalError( $message ) {
2573 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2574
2575 $this->addHTML( $message );
2576 }
2577
2578 public function showUnexpectedValueError( $name, $val ) {
2579 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2580 }
2581
2582 public function showFileCopyError( $old, $new ) {
2583 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2584 }
2585
2586 public function showFileRenameError( $old, $new ) {
2587 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2588 }
2589
2590 public function showFileDeleteError( $name ) {
2591 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2592 }
2593
2594 public function showFileNotFoundError( $name ) {
2595 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2596 }
2597
2598 /**
2599 * Add a "return to" link pointing to a specified title
2600 *
2601 * @param Title $title Title to link
2602 * @param array $query Query string parameters
2603 * @param string $text Text of the link (input is not escaped)
2604 * @param array $options Options array to pass to Linker
2605 */
2606 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2607 $link = $this->msg( 'returnto' )->rawParams(
2608 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2609 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2610 }
2611
2612 /**
2613 * Add a "return to" link pointing to a specified title,
2614 * or the title indicated in the request, or else the main page
2615 *
2616 * @param mixed $unused
2617 * @param Title|string $returnto Title or String to return to
2618 * @param string $returntoquery Query string for the return to link
2619 */
2620 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2621 if ( $returnto == null ) {
2622 $returnto = $this->getRequest()->getText( 'returnto' );
2623 }
2624
2625 if ( $returntoquery == null ) {
2626 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2627 }
2628
2629 if ( $returnto === '' ) {
2630 $returnto = Title::newMainPage();
2631 }
2632
2633 if ( is_object( $returnto ) ) {
2634 $titleObj = $returnto;
2635 } else {
2636 $titleObj = Title::newFromText( $returnto );
2637 }
2638 if ( !is_object( $titleObj ) ) {
2639 $titleObj = Title::newMainPage();
2640 }
2641
2642 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2643 }
2644
2645 /**
2646 * @param Skin $sk The given Skin
2647 * @param bool $includeStyle Unused
2648 * @return string The doctype, opening "<html>", and head element.
2649 */
2650 public function headElement( Skin $sk, $includeStyle = true ) {
2651 global $wgContLang;
2652
2653 $userdir = $this->getLanguage()->getDir();
2654 $sitedir = $wgContLang->getDir();
2655
2656 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2657
2658 if ( $this->getHTMLTitle() == '' ) {
2659 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2660 }
2661
2662 $openHead = Html::openElement( 'head' );
2663 if ( $openHead ) {
2664 # Don't bother with the newline if $head == ''
2665 $ret .= "$openHead\n";
2666 }
2667
2668 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2669 // Add <meta charset="UTF-8">
2670 // This should be before <title> since it defines the charset used by
2671 // text including the text inside <title>.
2672 // The spec recommends defining XHTML5's charset using the XML declaration
2673 // instead of meta.
2674 // Our XML declaration is output by Html::htmlHeader.
2675 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2676 // http://www.whatwg.org/html/semantics.html#charset
2677 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2678 }
2679
2680 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2681
2682 foreach ( $this->getHeadLinksArray() as $item ) {
2683 $ret .= $item . "\n";
2684 }
2685
2686 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2687 $ret .= $this->buildCssLinks();
2688
2689 $ret .= $this->getHeadScripts() . "\n";
2690
2691 foreach ( $this->mHeadItems as $item ) {
2692 $ret .= $item . "\n";
2693 }
2694
2695 $closeHead = Html::closeElement( 'head' );
2696 if ( $closeHead ) {
2697 $ret .= "$closeHead\n";
2698 }
2699
2700 $bodyClasses = array();
2701 $bodyClasses[] = 'mediawiki';
2702
2703 # Classes for LTR/RTL directionality support
2704 $bodyClasses[] = $userdir;
2705 $bodyClasses[] = "sitedir-$sitedir";
2706
2707 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2708 # A <body> class is probably not the best way to do this . . .
2709 $bodyClasses[] = 'capitalize-all-nouns';
2710 }
2711
2712 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2713 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2714 $bodyClasses[] =
2715 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2716
2717 $bodyAttrs = array();
2718 // While the implode() is not strictly needed, it's used for backwards compatibility
2719 // (this used to be built as a string and hooks likely still expect that).
2720 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2721
2722 // Allow skins and extensions to add body attributes they need
2723 $sk->addToBodyAttributes( $this, $bodyAttrs );
2724 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2725
2726 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2727
2728 return $ret;
2729 }
2730
2731 /**
2732 * Get a ResourceLoader object associated with this OutputPage
2733 *
2734 * @return ResourceLoader
2735 */
2736 public function getResourceLoader() {
2737 if ( is_null( $this->mResourceLoader ) ) {
2738 $this->mResourceLoader = new ResourceLoader(
2739 $this->getConfig(),
2740 LoggerFactory::getInstance( 'resourceloader' )
2741 );
2742 }
2743 return $this->mResourceLoader;
2744 }
2745
2746 /**
2747 * @todo Document
2748 * @param array|string $modules One or more module names
2749 * @param string $only ResourceLoaderModule TYPE_ class constant
2750 * @param bool $useESI
2751 * @param array $extraQuery Array with extra query parameters to add to each
2752 * request. array( param => value ).
2753 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2754 * call rather than a "<script src='...'>" tag.
2755 * @return string The html "<script>", "<link>" and "<style>" tags
2756 */
2757 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2758 array $extraQuery = array(), $loadCall = false
2759 ) {
2760 $modules = (array)$modules;
2761
2762 $links = array(
2763 'html' => '',
2764 'states' => array(),
2765 );
2766
2767 if ( !count( $modules ) ) {
2768 return $links;
2769 }
2770
2771 if ( count( $modules ) > 1 ) {
2772 // Remove duplicate module requests
2773 $modules = array_unique( $modules );
2774 // Sort module names so requests are more uniform
2775 sort( $modules );
2776
2777 if ( ResourceLoader::inDebugMode() ) {
2778 // Recursively call us for every item
2779 foreach ( $modules as $name ) {
2780 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2781 $links['html'] .= $link['html'];
2782 $links['states'] += $link['states'];
2783 }
2784 return $links;
2785 }
2786 }
2787
2788 if ( !is_null( $this->mTarget ) ) {
2789 $extraQuery['target'] = $this->mTarget;
2790 }
2791
2792 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2793 $sortedModules = array();
2794 $resourceLoader = $this->getResourceLoader();
2795 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2796 foreach ( $modules as $name ) {
2797 $module = $resourceLoader->getModule( $name );
2798 # Check that we're allowed to include this module on this page
2799 if ( !$module
2800 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2801 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2802 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2803 && $only == ResourceLoaderModule::TYPE_STYLES )
2804 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2805 && $only == ResourceLoaderModule::TYPE_COMBINED )
2806 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2807 ) {
2808 continue;
2809 }
2810
2811 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2812 }
2813
2814 foreach ( $sortedModules as $source => $groups ) {
2815 foreach ( $groups as $group => $grpModules ) {
2816 // Special handling for user-specific groups
2817 $user = null;
2818 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2819 $user = $this->getUser()->getName();
2820 }
2821
2822 // Create a fake request based on the one we are about to make so modules return
2823 // correct timestamp and emptiness data
2824 $query = ResourceLoader::makeLoaderQuery(
2825 array(), // modules; not determined yet
2826 $this->getLanguage()->getCode(),
2827 $this->getSkin()->getSkinName(),
2828 $user,
2829 null, // version; not determined yet
2830 ResourceLoader::inDebugMode(),
2831 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2832 $this->isPrintable(),
2833 $this->getRequest()->getBool( 'handheld' ),
2834 $extraQuery
2835 );
2836 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2837
2838 // Extract modules that know they're empty and see if we have one or more
2839 // raw modules
2840 $isRaw = false;
2841 foreach ( $grpModules as $key => $module ) {
2842 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2843 // If we're only getting the styles, we don't need to do anything for empty modules.
2844 if ( $module->isKnownEmpty( $context ) ) {
2845 unset( $grpModules[$key] );
2846 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2847 $links['states'][$key] = 'ready';
2848 }
2849 }
2850
2851 $isRaw |= $module->isRaw();
2852 }
2853
2854 // If there are no non-empty modules, skip this group
2855 if ( count( $grpModules ) === 0 ) {
2856 continue;
2857 }
2858
2859 // Inline private modules. These can't be loaded through load.php for security
2860 // reasons, see bug 34907. Note that these modules should be loaded from
2861 // getHeadScripts() before the first loader call. Otherwise other modules can't
2862 // properly use them as dependencies (bug 30914)
2863 if ( $group === 'private' ) {
2864 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2865 $links['html'] .= Html::inlineStyle(
2866 $resourceLoader->makeModuleResponse( $context, $grpModules )
2867 );
2868 } else {
2869 $links['html'] .= ResourceLoader::makeInlineScript(
2870 $resourceLoader->makeModuleResponse( $context, $grpModules )
2871 );
2872 }
2873 $links['html'] .= "\n";
2874 continue;
2875 }
2876
2877 // Special handling for the user group; because users might change their stuff
2878 // on-wiki like user pages, or user preferences; we need to find the highest
2879 // timestamp of these user-changeable modules so we can ensure cache misses on change
2880 // This should NOT be done for the site group (bug 27564) because anons get that too
2881 // and we shouldn't be putting timestamps in Squid-cached HTML
2882 $version = null;
2883 if ( $group === 'user' ) {
2884 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2885 }
2886
2887 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2888 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2889 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2890
2891 if ( $useESI && $resourceLoaderUseESI ) {
2892 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2893 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2894 $link = Html::inlineStyle( $esi );
2895 } else {
2896 $link = Html::inlineScript( $esi );
2897 }
2898 } else {
2899 // Automatically select style/script elements
2900 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2901 $link = Html::linkedStyle( $url );
2902 } elseif ( $loadCall ) {
2903 $link = ResourceLoader::makeInlineScript(
2904 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2905 );
2906 } else {
2907 $link = Html::linkedScript( $url );
2908 if ( !$context->getRaw() && !$isRaw ) {
2909 // Wrap only=script / only=combined requests in a conditional as
2910 // browsers not supported by the startup module would unconditionally
2911 // execute this module. Otherwise users will get "ReferenceError: mw is
2912 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2913 $link = ResourceLoader::makeInlineScript(
2914 Xml::encodeJsCall( 'document.write', array( $link ) )
2915 );
2916 }
2917
2918 // For modules requested directly in the html via <link> or <script>,
2919 // tell mw.loader they are being loading to prevent duplicate requests.
2920 foreach ( $grpModules as $key => $module ) {
2921 // Don't output state=loading for the startup module..
2922 if ( $key !== 'startup' ) {
2923 $links['states'][$key] = 'loading';
2924 }
2925 }
2926 }
2927 }
2928
2929 if ( $group == 'noscript' ) {
2930 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2931 } else {
2932 $links['html'] .= $link . "\n";
2933 }
2934 }
2935 }
2936
2937 return $links;
2938 }
2939
2940 /**
2941 * Build html output from an array of links from makeResourceLoaderLink.
2942 * @param array $links
2943 * @return string HTML
2944 */
2945 protected static function getHtmlFromLoaderLinks( array $links ) {
2946 $html = '';
2947 $states = array();
2948 foreach ( $links as $link ) {
2949 if ( !is_array( $link ) ) {
2950 $html .= $link;
2951 } else {
2952 $html .= $link['html'];
2953 $states += $link['states'];
2954 }
2955 }
2956
2957 if ( count( $states ) ) {
2958 $html = ResourceLoader::makeInlineScript(
2959 ResourceLoader::makeLoaderStateScript( $states )
2960 ) . "\n" . $html;
2961 }
2962
2963 return $html;
2964 }
2965
2966 /**
2967 * JS stuff to put in the "<head>". This is the startup module, config
2968 * vars and modules marked with position 'top'
2969 *
2970 * @return string HTML fragment
2971 */
2972 function getHeadScripts() {
2973 // Startup - this will immediately load jquery and mediawiki modules
2974 $links = array();
2975 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2976
2977 // Load config before anything else
2978 $links[] = ResourceLoader::makeInlineScript(
2979 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2980 );
2981
2982 // Load embeddable private modules before any loader links
2983 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2984 // in mw.loader.implement() calls and deferred until mw.user is available
2985 $embedScripts = array( 'user.options' );
2986 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2987 // Separate user.tokens as otherwise caching will be allowed (T84960)
2988 $links[] = $this->makeResourceLoaderLink( 'user.tokens', ResourceLoaderModule::TYPE_COMBINED );
2989
2990 // Scripts and messages "only" requests marked for top inclusion
2991 $links[] = $this->makeResourceLoaderLink(
2992 $this->getModuleScripts( true, 'top' ),
2993 ResourceLoaderModule::TYPE_SCRIPTS
2994 );
2995
2996 // Modules requests - let the client calculate dependencies and batch requests as it likes
2997 // Only load modules that have marked themselves for loading at the top
2998 $modules = $this->getModules( true, 'top' );
2999 if ( $modules ) {
3000 $links[] = ResourceLoader::makeInlineScript(
3001 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3002 );
3003 }
3004
3005 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3006 $links[] = $this->getScriptsForBottomQueue( true );
3007 }
3008
3009 return self::getHtmlFromLoaderLinks( $links );
3010 }
3011
3012 /**
3013 * JS stuff to put at the 'bottom', which can either be the bottom of the
3014 * "<body>" or the bottom of the "<head>" depending on
3015 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3016 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3017 * and user JS.
3018 *
3019 * @param bool $inHead If true, this HTML goes into the "<head>",
3020 * if false it goes into the "<body>".
3021 * @return string
3022 */
3023 function getScriptsForBottomQueue( $inHead ) {
3024 // Scripts "only" requests marked for bottom inclusion
3025 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3026 $links = array();
3027
3028 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3029 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
3030 /* $loadCall = */ $inHead
3031 );
3032
3033 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3034 ResourceLoaderModule::TYPE_STYLES, /* $useESI = */ false, /* $extraQuery = */ array(),
3035 /* $loadCall = */ $inHead
3036 );
3037
3038 // Modules requests - let the client calculate dependencies and batch requests as it likes
3039 // Only load modules that have marked themselves for loading at the bottom
3040 $modules = $this->getModules( true, 'bottom' );
3041 if ( $modules ) {
3042 $links[] = ResourceLoader::makeInlineScript(
3043 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3044 );
3045 }
3046
3047 // Legacy Scripts
3048 $links[] = "\n" . $this->mScripts;
3049
3050 // Add site JS if enabled
3051 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
3052 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3053 );
3054
3055 // Add user JS if enabled
3056 if ( $this->getConfig()->get( 'AllowUserJs' )
3057 && $this->getUser()->isLoggedIn()
3058 && $this->getTitle()
3059 && $this->getTitle()->isJsSubpage()
3060 && $this->userCanPreview()
3061 ) {
3062 # XXX: additional security check/prompt?
3063 // We're on a preview of a JS subpage
3064 // Exclude this page from the user module in case it's in there (bug 26283)
3065 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3066 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3067 );
3068 // Load the previewed JS
3069 $links[] = Html::inlineScript( "\n"
3070 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3071
3072 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3073 // asynchronously and may arrive *after* the inline script here. So the previewed code
3074 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3075 } else {
3076 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3077 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3078 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3079 );
3080 }
3081
3082 // Group JS is only enabled if site JS is enabled.
3083 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3084 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3085 );
3086
3087 return self::getHtmlFromLoaderLinks( $links );
3088 }
3089
3090 /**
3091 * JS stuff to put at the bottom of the "<body>"
3092 * @return string
3093 */
3094 function getBottomScripts() {
3095 // In case the skin wants to add bottom CSS
3096 $this->getSkin()->setupSkinUserCss( $this );
3097
3098 // Optimise jQuery ready event cross-browser.
3099 // This also enforces $.isReady to be true at </body> which fixes the
3100 // mw.loader bug in Firefox with using document.write between </body>
3101 // and the DOMContentReady event (bug 47457).
3102 $html = Html::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3103
3104 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3105 $html .= $this->getScriptsForBottomQueue( false );
3106 }
3107
3108 return $html;
3109 }
3110
3111 /**
3112 * Get the javascript config vars to include on this page
3113 *
3114 * @return array Array of javascript config vars
3115 * @since 1.23
3116 */
3117 public function getJsConfigVars() {
3118 return $this->mJsConfigVars;
3119 }
3120
3121 /**
3122 * Add one or more variables to be set in mw.config in JavaScript
3123 *
3124 * @param string|array $keys Key or array of key/value pairs
3125 * @param mixed $value [optional] Value of the configuration variable
3126 */
3127 public function addJsConfigVars( $keys, $value = null ) {
3128 if ( is_array( $keys ) ) {
3129 foreach ( $keys as $key => $value ) {
3130 $this->mJsConfigVars[$key] = $value;
3131 }
3132 return;
3133 }
3134
3135 $this->mJsConfigVars[$keys] = $value;
3136 }
3137
3138 /**
3139 * Get an array containing the variables to be set in mw.config in JavaScript.
3140 *
3141 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3142 * - in other words, page-independent/site-wide variables (without state).
3143 * You will only be adding bloat to the html page and causing page caches to
3144 * have to be purged on configuration changes.
3145 * @return array
3146 */
3147 public function getJSVars() {
3148 global $wgContLang;
3149
3150 $curRevisionId = 0;
3151 $articleId = 0;
3152 $canonicalSpecialPageName = false; # bug 21115
3153
3154 $title = $this->getTitle();
3155 $ns = $title->getNamespace();
3156 $canonicalNamespace = MWNamespace::exists( $ns )
3157 ? MWNamespace::getCanonicalName( $ns )
3158 : $title->getNsText();
3159
3160 $sk = $this->getSkin();
3161 // Get the relevant title so that AJAX features can use the correct page name
3162 // when making API requests from certain special pages (bug 34972).
3163 $relevantTitle = $sk->getRelevantTitle();
3164 $relevantUser = $sk->getRelevantUser();
3165
3166 if ( $ns == NS_SPECIAL ) {
3167 list( $canonicalSpecialPageName, /*...*/ ) =
3168 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3169 } elseif ( $this->canUseWikiPage() ) {
3170 $wikiPage = $this->getWikiPage();
3171 $curRevisionId = $wikiPage->getLatest();
3172 $articleId = $wikiPage->getId();
3173 }
3174
3175 $lang = $title->getPageLanguage();
3176
3177 // Pre-process information
3178 $separatorTransTable = $lang->separatorTransformTable();
3179 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3180 $compactSeparatorTransTable = array(
3181 implode( "\t", array_keys( $separatorTransTable ) ),
3182 implode( "\t", $separatorTransTable ),
3183 );
3184 $digitTransTable = $lang->digitTransformTable();
3185 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3186 $compactDigitTransTable = array(
3187 implode( "\t", array_keys( $digitTransTable ) ),
3188 implode( "\t", $digitTransTable ),
3189 );
3190
3191 $user = $this->getUser();
3192
3193 $vars = array(
3194 'wgCanonicalNamespace' => $canonicalNamespace,
3195 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3196 'wgNamespaceNumber' => $title->getNamespace(),
3197 'wgPageName' => $title->getPrefixedDBkey(),
3198 'wgTitle' => $title->getText(),
3199 'wgCurRevisionId' => $curRevisionId,
3200 'wgRevisionId' => (int)$this->getRevisionId(),
3201 'wgArticleId' => $articleId,
3202 'wgIsArticle' => $this->isArticle(),
3203 'wgIsRedirect' => $title->isRedirect(),
3204 'wgAction' => Action::getActionName( $this->getContext() ),
3205 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3206 'wgUserGroups' => $user->getEffectiveGroups(),
3207 'wgCategories' => $this->getCategories(),
3208 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3209 'wgPageContentLanguage' => $lang->getCode(),
3210 'wgPageContentModel' => $title->getContentModel(),
3211 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3212 'wgDigitTransformTable' => $compactDigitTransTable,
3213 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3214 'wgMonthNames' => $lang->getMonthNamesArray(),
3215 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3216 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3217 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3218 );
3219
3220 if ( $user->isLoggedIn() ) {
3221 $vars['wgUserId'] = $user->getId();
3222 $vars['wgUserEditCount'] = $user->getEditCount();
3223 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3224 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3225 // Get the revision ID of the oldest new message on the user's talk
3226 // page. This can be used for constructing new message alerts on
3227 // the client side.
3228 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3229 }
3230
3231 if ( $wgContLang->hasVariants() ) {
3232 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3233 }
3234 // Same test as SkinTemplate
3235 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3236 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3237
3238 foreach ( $title->getRestrictionTypes() as $type ) {
3239 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3240 }
3241
3242 if ( $title->isMainPage() ) {
3243 $vars['wgIsMainPage'] = true;
3244 }
3245
3246 if ( $this->mRedirectedFrom ) {
3247 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3248 }
3249
3250 if ( $relevantUser ) {
3251 $vars['wgRelevantUserName'] = $relevantUser->getName();
3252 }
3253
3254 // Allow extensions to add their custom variables to the mw.config map.
3255 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3256 // page-dependant but site-wide (without state).
3257 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3258 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3259
3260 // Merge in variables from addJsConfigVars last
3261 return array_merge( $vars, $this->getJsConfigVars() );
3262 }
3263
3264 /**
3265 * To make it harder for someone to slip a user a fake
3266 * user-JavaScript or user-CSS preview, a random token
3267 * is associated with the login session. If it's not
3268 * passed back with the preview request, we won't render
3269 * the code.
3270 *
3271 * @return bool
3272 */
3273 public function userCanPreview() {
3274 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3275 || !$this->getRequest()->wasPosted()
3276 || !$this->getUser()->matchEditToken(
3277 $this->getRequest()->getVal( 'wpEditToken' ) )
3278 ) {
3279 return false;
3280 }
3281 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3282 return false;
3283 }
3284 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3285 // Don't execute another user's CSS or JS on preview (T85855)
3286 return false;
3287 }
3288
3289 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3290 }
3291
3292 /**
3293 * @return array Array in format "link name or number => 'link html'".
3294 */
3295 public function getHeadLinksArray() {
3296 global $wgVersion;
3297
3298 $tags = array();
3299 $config = $this->getConfig();
3300
3301 $canonicalUrl = $this->mCanonicalUrl;
3302
3303 $tags['meta-generator'] = Html::element( 'meta', array(
3304 'name' => 'generator',
3305 'content' => "MediaWiki $wgVersion",
3306 ) );
3307
3308 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3309 $tags['meta-referrer'] = Html::element( 'meta', array(
3310 'name' => 'referrer',
3311 'content' => $config->get( 'ReferrerPolicy' )
3312 ) );
3313 }
3314
3315 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3316 if ( $p !== 'index,follow' ) {
3317 // http://www.robotstxt.org/wc/meta-user.html
3318 // Only show if it's different from the default robots policy
3319 $tags['meta-robots'] = Html::element( 'meta', array(
3320 'name' => 'robots',
3321 'content' => $p,
3322 ) );
3323 }
3324
3325 foreach ( $this->mMetatags as $tag ) {
3326 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3327 $a = 'http-equiv';
3328 $tag[0] = substr( $tag[0], 5 );
3329 } else {
3330 $a = 'name';
3331 }
3332 $tagName = "meta-{$tag[0]}";
3333 if ( isset( $tags[$tagName] ) ) {
3334 $tagName .= $tag[1];
3335 }
3336 $tags[$tagName] = Html::element( 'meta',
3337 array(
3338 $a => $tag[0],
3339 'content' => $tag[1]
3340 )
3341 );
3342 }
3343
3344 foreach ( $this->mLinktags as $tag ) {
3345 $tags[] = Html::element( 'link', $tag );
3346 }
3347
3348 # Universal edit button
3349 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3350 $user = $this->getUser();
3351 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3352 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3353 // Original UniversalEditButton
3354 $msg = $this->msg( 'edit' )->text();
3355 $tags['universal-edit-button'] = Html::element( 'link', array(
3356 'rel' => 'alternate',
3357 'type' => 'application/x-wiki',
3358 'title' => $msg,
3359 'href' => $this->getTitle()->getEditURL(),
3360 ) );
3361 // Alternate edit link
3362 $tags['alternative-edit'] = Html::element( 'link', array(
3363 'rel' => 'edit',
3364 'title' => $msg,
3365 'href' => $this->getTitle()->getEditURL(),
3366 ) );
3367 }
3368 }
3369
3370 # Generally the order of the favicon and apple-touch-icon links
3371 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3372 # uses whichever one appears later in the HTML source. Make sure
3373 # apple-touch-icon is specified first to avoid this.
3374 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3375 $tags['apple-touch-icon'] = Html::element( 'link', array(
3376 'rel' => 'apple-touch-icon',
3377 'href' => $config->get( 'AppleTouchIcon' )
3378 ) );
3379 }
3380
3381 if ( $config->get( 'Favicon' ) !== false ) {
3382 $tags['favicon'] = Html::element( 'link', array(
3383 'rel' => 'shortcut icon',
3384 'href' => $config->get( 'Favicon' )
3385 ) );
3386 }
3387
3388 # OpenSearch description link
3389 $tags['opensearch'] = Html::element( 'link', array(
3390 'rel' => 'search',
3391 'type' => 'application/opensearchdescription+xml',
3392 'href' => wfScript( 'opensearch_desc' ),
3393 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3394 ) );
3395
3396 if ( $config->get( 'EnableAPI' ) ) {
3397 # Real Simple Discovery link, provides auto-discovery information
3398 # for the MediaWiki API (and potentially additional custom API
3399 # support such as WordPress or Twitter-compatible APIs for a
3400 # blogging extension, etc)
3401 $tags['rsd'] = Html::element( 'link', array(
3402 'rel' => 'EditURI',
3403 'type' => 'application/rsd+xml',
3404 // Output a protocol-relative URL here if $wgServer is protocol-relative
3405 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3406 'href' => wfExpandUrl( wfAppendQuery(
3407 wfScript( 'api' ),
3408 array( 'action' => 'rsd' ) ),
3409 PROTO_RELATIVE
3410 ),
3411 ) );
3412 }
3413
3414 # Language variants
3415 if ( !$config->get( 'DisableLangConversion' ) ) {
3416 $lang = $this->getTitle()->getPageLanguage();
3417 if ( $lang->hasVariants() ) {
3418 $variants = $lang->getVariants();
3419 foreach ( $variants as $_v ) {
3420 $tags["variant-$_v"] = Html::element( 'link', array(
3421 'rel' => 'alternate',
3422 'hreflang' => wfBCP47( $_v ),
3423 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3424 );
3425 }
3426 }
3427 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3428 $tags["variant-x-default"] = Html::element( 'link', array(
3429 'rel' => 'alternate',
3430 'hreflang' => 'x-default',
3431 'href' => $this->getTitle()->getLocalURL() ) );
3432 }
3433
3434 # Copyright
3435 $copyright = '';
3436 if ( $config->get( 'RightsPage' ) ) {
3437 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3438
3439 if ( $copy ) {
3440 $copyright = $copy->getLocalURL();
3441 }
3442 }
3443
3444 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3445 $copyright = $config->get( 'RightsUrl' );
3446 }
3447
3448 if ( $copyright ) {
3449 $tags['copyright'] = Html::element( 'link', array(
3450 'rel' => 'copyright',
3451 'href' => $copyright )
3452 );
3453 }
3454
3455 # Feeds
3456 if ( $config->get( 'Feed' ) ) {
3457 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3458 # Use the page name for the title. In principle, this could
3459 # lead to issues with having the same name for different feeds
3460 # corresponding to the same page, but we can't avoid that at
3461 # this low a level.
3462
3463 $tags[] = $this->feedLink(
3464 $format,
3465 $link,
3466 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3467 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3468 );
3469 }
3470
3471 # Recent changes feed should appear on every page (except recentchanges,
3472 # that would be redundant). Put it after the per-page feed to avoid
3473 # changing existing behavior. It's still available, probably via a
3474 # menu in your browser. Some sites might have a different feed they'd
3475 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3476 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3477 # If so, use it instead.
3478 $sitename = $config->get( 'Sitename' );
3479 if ( $config->get( 'OverrideSiteFeed' ) ) {
3480 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3481 // Note, this->feedLink escapes the url.
3482 $tags[] = $this->feedLink(
3483 $type,
3484 $feedUrl,
3485 $this->msg( "site-{$type}-feed", $sitename )->text()
3486 );
3487 }
3488 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3489 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3490 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3491 $tags[] = $this->feedLink(
3492 $format,
3493 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3494 # For grep: 'site-rss-feed', 'site-atom-feed'
3495 $this->msg( "site-{$format}-feed", $sitename )->text()
3496 );
3497 }
3498 }
3499 }
3500
3501 # Canonical URL
3502 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3503 if ( $canonicalUrl !== false ) {
3504 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3505 } else {
3506 $reqUrl = $this->getRequest()->getRequestURL();
3507 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3508 }
3509 }
3510 if ( $canonicalUrl !== false ) {
3511 $tags[] = Html::element( 'link', array(
3512 'rel' => 'canonical',
3513 'href' => $canonicalUrl
3514 ) );
3515 }
3516
3517 return $tags;
3518 }
3519
3520 /**
3521 * @return string HTML tag links to be put in the header.
3522 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3523 * OutputPage::getHeadLinksArray directly.
3524 */
3525 public function getHeadLinks() {
3526 wfDeprecated( __METHOD__, '1.24' );
3527 return implode( "\n", $this->getHeadLinksArray() );
3528 }
3529
3530 /**
3531 * Generate a "<link rel/>" for a feed.
3532 *
3533 * @param string $type Feed type
3534 * @param string $url URL to the feed
3535 * @param string $text Value of the "title" attribute
3536 * @return string HTML fragment
3537 */
3538 private function feedLink( $type, $url, $text ) {
3539 return Html::element( 'link', array(
3540 'rel' => 'alternate',
3541 'type' => "application/$type+xml",
3542 'title' => $text,
3543 'href' => $url )
3544 );
3545 }
3546
3547 /**
3548 * Add a local or specified stylesheet, with the given media options.
3549 * Meant primarily for internal use...
3550 *
3551 * @param string $style URL to the file
3552 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3553 * @param string $condition For IE conditional comments, specifying an IE version
3554 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3555 */
3556 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3557 $options = array();
3558 // Even though we expect the media type to be lowercase, but here we
3559 // force it to lowercase to be safe.
3560 if ( $media ) {
3561 $options['media'] = $media;
3562 }
3563 if ( $condition ) {
3564 $options['condition'] = $condition;
3565 }
3566 if ( $dir ) {
3567 $options['dir'] = $dir;
3568 }
3569 $this->styles[$style] = $options;
3570 }
3571
3572 /**
3573 * Adds inline CSS styles
3574 * @param mixed $style_css Inline CSS
3575 * @param string $flip Set to 'flip' to flip the CSS if needed
3576 */
3577 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3578 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3579 # If wanted, and the interface is right-to-left, flip the CSS
3580 $style_css = CSSJanus::transform( $style_css, true, false );
3581 }
3582 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3583 }
3584
3585 /**
3586 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3587 * These will be applied to various media & IE conditionals.
3588 *
3589 * @return string
3590 */
3591 public function buildCssLinks() {
3592 global $wgContLang;
3593
3594 $this->getSkin()->setupSkinUserCss( $this );
3595
3596 // Add ResourceLoader styles
3597 // Split the styles into these groups
3598 $styles = array(
3599 'other' => array(),
3600 'user' => array(),
3601 'site' => array(),
3602 'private' => array(),
3603 'noscript' => array()
3604 );
3605 $links = array();
3606 $otherTags = ''; // Tags to append after the normal <link> tags
3607 $resourceLoader = $this->getResourceLoader();
3608
3609 $moduleStyles = $this->getModuleStyles( true, 'top' );
3610
3611 // Per-site custom styles
3612 $moduleStyles[] = 'site';
3613 $moduleStyles[] = 'noscript';
3614 $moduleStyles[] = 'user.groups';
3615
3616 // Per-user custom styles
3617 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3618 && $this->userCanPreview()
3619 ) {
3620 // We're on a preview of a CSS subpage
3621 // Exclude this page from the user module in case it's in there (bug 26283)
3622 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3623 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3624 );
3625 $otherTags .= $link['html'];
3626
3627 // Load the previewed CSS
3628 // If needed, Janus it first. This is user-supplied CSS, so it's
3629 // assumed to be right for the content language directionality.
3630 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3631 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3632 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3633 }
3634 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3635 } else {
3636 // Load the user styles normally
3637 $moduleStyles[] = 'user';
3638 }
3639
3640 // Per-user preference styles
3641 $moduleStyles[] = 'user.cssprefs';
3642
3643 foreach ( $moduleStyles as $name ) {
3644 $module = $resourceLoader->getModule( $name );
3645 if ( !$module ) {
3646 continue;
3647 }
3648 $group = $module->getGroup();
3649 // Modules in groups different than the ones listed on top (see $styles assignment)
3650 // will be placed in the "other" group
3651 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3652 }
3653
3654 // We want site, private and user styles to override dynamically added
3655 // styles from modules, but we want dynamically added styles to override
3656 // statically added styles from other modules. So the order has to be
3657 // other, dynamic, site, private, user. Add statically added styles for
3658 // other modules
3659 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3660 // Add normal styles added through addStyle()/addInlineStyle() here
3661 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3662 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3663 // We use a <meta> tag with a made-up name for this because that's valid HTML
3664 $links[] = Html::element(
3665 'meta',
3666 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3667 ) . "\n";
3668
3669 // Add site, private and user styles
3670 // 'private' at present only contains user.options, so put that before 'user'
3671 // Any future private modules will likely have a similar user-specific character
3672 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3673 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3674 ResourceLoaderModule::TYPE_STYLES
3675 );
3676 }
3677
3678 // Add stuff in $otherTags (previewed user CSS if applicable)
3679 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3680 }
3681
3682 /**
3683 * @return array
3684 */
3685 public function buildCssLinksArray() {
3686 $links = array();
3687
3688 // Add any extension CSS
3689 foreach ( $this->mExtStyles as $url ) {
3690 $this->addStyle( $url );
3691 }
3692 $this->mExtStyles = array();
3693
3694 foreach ( $this->styles as $file => $options ) {
3695 $link = $this->styleLink( $file, $options );
3696 if ( $link ) {
3697 $links[$file] = $link;
3698 }
3699 }
3700 return $links;
3701 }
3702
3703 /**
3704 * Generate \<link\> tags for stylesheets
3705 *
3706 * @param string $style URL to the file
3707 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3708 * @return string HTML fragment
3709 */
3710 protected function styleLink( $style, array $options ) {
3711 if ( isset( $options['dir'] ) ) {
3712 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3713 return '';
3714 }
3715 }
3716
3717 if ( isset( $options['media'] ) ) {
3718 $media = self::transformCssMedia( $options['media'] );
3719 if ( is_null( $media ) ) {
3720 return '';
3721 }
3722 } else {
3723 $media = 'all';
3724 }
3725
3726 if ( substr( $style, 0, 1 ) == '/' ||
3727 substr( $style, 0, 5 ) == 'http:' ||
3728 substr( $style, 0, 6 ) == 'https:' ) {
3729 $url = $style;
3730 } else {
3731 $config = $this->getConfig();
3732 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3733 }
3734
3735 $link = Html::linkedStyle( $url, $media );
3736
3737 if ( isset( $options['condition'] ) ) {
3738 $condition = htmlspecialchars( $options['condition'] );
3739 $link = "<!--[if $condition]>$link<![endif]-->";
3740 }
3741 return $link;
3742 }
3743
3744 /**
3745 * Transform "media" attribute based on request parameters
3746 *
3747 * @param string $media Current value of the "media" attribute
3748 * @return string Modified value of the "media" attribute, or null to skip
3749 * this stylesheet
3750 */
3751 public static function transformCssMedia( $media ) {
3752 global $wgRequest;
3753
3754 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3755 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3756
3757 // Switch in on-screen display for media testing
3758 $switches = array(
3759 'printable' => 'print',
3760 'handheld' => 'handheld',
3761 );
3762 foreach ( $switches as $switch => $targetMedia ) {
3763 if ( $wgRequest->getBool( $switch ) ) {
3764 if ( $media == $targetMedia ) {
3765 $media = '';
3766 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3767 // This regex will not attempt to understand a comma-separated media_query_list
3768 //
3769 // Example supported values for $media:
3770 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3771 // Example NOT supported value for $media:
3772 // '3d-glasses, screen, print and resolution > 90dpi'
3773 //
3774 // If it's a print request, we never want any kind of screen stylesheets
3775 // If it's a handheld request (currently the only other choice with a switch),
3776 // we don't want simple 'screen' but we might want screen queries that
3777 // have a max-width or something, so we'll pass all others on and let the
3778 // client do the query.
3779 if ( $targetMedia == 'print' || $media == 'screen' ) {
3780 return null;
3781 }
3782 }
3783 }
3784 }
3785
3786 return $media;
3787 }
3788
3789 /**
3790 * Add a wikitext-formatted message to the output.
3791 * This is equivalent to:
3792 *
3793 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3794 */
3795 public function addWikiMsg( /*...*/ ) {
3796 $args = func_get_args();
3797 $name = array_shift( $args );
3798 $this->addWikiMsgArray( $name, $args );
3799 }
3800
3801 /**
3802 * Add a wikitext-formatted message to the output.
3803 * Like addWikiMsg() except the parameters are taken as an array
3804 * instead of a variable argument list.
3805 *
3806 * @param string $name
3807 * @param array $args
3808 */
3809 public function addWikiMsgArray( $name, $args ) {
3810 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3811 }
3812
3813 /**
3814 * This function takes a number of message/argument specifications, wraps them in
3815 * some overall structure, and then parses the result and adds it to the output.
3816 *
3817 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3818 * and so on. The subsequent arguments may be either
3819 * 1) strings, in which case they are message names, or
3820 * 2) arrays, in which case, within each array, the first element is the message
3821 * name, and subsequent elements are the parameters to that message.
3822 *
3823 * Don't use this for messages that are not in the user's interface language.
3824 *
3825 * For example:
3826 *
3827 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3828 *
3829 * Is equivalent to:
3830 *
3831 * $wgOut->addWikiText( "<div class='error'>\n"
3832 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3833 *
3834 * The newline after the opening div is needed in some wikitext. See bug 19226.
3835 *
3836 * @param string $wrap
3837 */
3838 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3839 $msgSpecs = func_get_args();
3840 array_shift( $msgSpecs );
3841 $msgSpecs = array_values( $msgSpecs );
3842 $s = $wrap;
3843 foreach ( $msgSpecs as $n => $spec ) {
3844 if ( is_array( $spec ) ) {
3845 $args = $spec;
3846 $name = array_shift( $args );
3847 if ( isset( $args['options'] ) ) {
3848 unset( $args['options'] );
3849 wfDeprecated(
3850 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3851 '1.20'
3852 );
3853 }
3854 } else {
3855 $args = array();
3856 $name = $spec;
3857 }
3858 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3859 }
3860 $this->addWikiText( $s );
3861 }
3862
3863 /**
3864 * Include jQuery core. Use this to avoid loading it multiple times
3865 * before we get a usable script loader.
3866 *
3867 * @param array $modules List of jQuery modules which should be loaded
3868 * @return array The list of modules which were not loaded.
3869 * @since 1.16
3870 * @deprecated since 1.17
3871 */
3872 public function includeJQuery( array $modules = array() ) {
3873 return array();
3874 }
3875
3876 /**
3877 * Enables/disables TOC, doesn't override __NOTOC__
3878 * @param bool $flag
3879 * @since 1.22
3880 */
3881 public function enableTOC( $flag = true ) {
3882 $this->mEnableTOC = $flag;
3883 }
3884
3885 /**
3886 * @return bool
3887 * @since 1.22
3888 */
3889 public function isTOCEnabled() {
3890 return $this->mEnableTOC;
3891 }
3892
3893 /**
3894 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3895 * @param bool $flag
3896 * @since 1.23
3897 */
3898 public function enableSectionEditLinks( $flag = true ) {
3899 $this->mEnableSectionEditLinks = $flag;
3900 }
3901
3902 /**
3903 * @return bool
3904 * @since 1.23
3905 */
3906 public function sectionEditLinksEnabled() {
3907 return $this->mEnableSectionEditLinks;
3908 }
3909
3910 /**
3911 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3912 * MediaWiki and this OutputPage instance.
3913 *
3914 * @since 1.25
3915 */
3916 public function enableOOUI() {
3917 OOUI\Theme::setSingleton( new OOUI\MediaWikiTheme() );
3918 OOUI\Element::setDefaultDir( $this->getLanguage()->getDir() );
3919 $this->addModuleStyles( array(
3920 'oojs-ui.styles',
3921 'oojs-ui.styles.icons',
3922 'oojs-ui.styles.indicators',
3923 'oojs-ui.styles.textures',
3924 ) );
3925 }
3926 }