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