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