Merge "Don't localize parentheses in version number in parserTests.php"
[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 * Link target can be overridden by a local message containing a wikilink:
1402 * the message key is: lowercase action or special page name + '-helppage'.
1403 * @param string $to Target MediaWiki.org page title or encoded URL.
1404 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1405 * @since 1.25
1406 */
1407 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1408 $this->addModuleStyles( 'mediawiki.helplink' );
1409 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1410
1411 if ( $overrideBaseUrl ) {
1412 $helpUrl = $to;
1413 } else {
1414 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1415 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1416 }
1417
1418 $link = Html::rawElement(
1419 'a',
1420 array(
1421 'href' => $helpUrl,
1422 'target' => '_blank',
1423 'class' => 'mw-helplink',
1424 ),
1425 $text
1426 );
1427
1428 $this->setIndicators( array( 'mw-helplink' => $link ) );
1429 }
1430
1431 /**
1432 * Do not allow scripts which can be modified by wiki users to load on this page;
1433 * only allow scripts bundled with, or generated by, the software.
1434 * Site-wide styles are controlled by a config setting, since they can be
1435 * used to create a custom skin/theme, but not user-specific ones.
1436 *
1437 * @todo this should be given a more accurate name
1438 */
1439 public function disallowUserJs() {
1440 $this->reduceAllowedModules(
1441 ResourceLoaderModule::TYPE_SCRIPTS,
1442 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1443 );
1444
1445 // Site-wide styles are controlled by a config setting, see bug 71621
1446 // for background on why. User styles are never allowed.
1447 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1448 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1449 } else {
1450 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1451 }
1452 $this->reduceAllowedModules(
1453 ResourceLoaderModule::TYPE_STYLES,
1454 $styleOrigin
1455 );
1456 }
1457
1458 /**
1459 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1460 * @see ResourceLoaderModule::$origin
1461 * @param string $type ResourceLoaderModule TYPE_ constant
1462 * @return int ResourceLoaderModule ORIGIN_ class constant
1463 */
1464 public function getAllowedModules( $type ) {
1465 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1466 return min( array_values( $this->mAllowedModules ) );
1467 } else {
1468 return isset( $this->mAllowedModules[$type] )
1469 ? $this->mAllowedModules[$type]
1470 : ResourceLoaderModule::ORIGIN_ALL;
1471 }
1472 }
1473
1474 /**
1475 * Set the highest level of CSS/JS untrustworthiness allowed
1476 *
1477 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1478 * Use reduceAllowedModules() instead
1479 * @param string $type ResourceLoaderModule TYPE_ constant
1480 * @param int $level ResourceLoaderModule class constant
1481 */
1482 public function setAllowedModules( $type, $level ) {
1483 wfDeprecated( __METHOD__, '1.24' );
1484 $this->reduceAllowedModules( $type, $level );
1485 }
1486
1487 /**
1488 * Limit the highest level of CSS/JS untrustworthiness allowed.
1489 *
1490 * If passed the same or a higher level than the current level of untrustworthiness set, the
1491 * level will remain unchanged.
1492 *
1493 * @param string $type
1494 * @param int $level ResourceLoaderModule class constant
1495 */
1496 public function reduceAllowedModules( $type, $level ) {
1497 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1498 }
1499
1500 /**
1501 * Prepend $text to the body HTML
1502 *
1503 * @param string $text HTML
1504 */
1505 public function prependHTML( $text ) {
1506 $this->mBodytext = $text . $this->mBodytext;
1507 }
1508
1509 /**
1510 * Append $text to the body HTML
1511 *
1512 * @param string $text HTML
1513 */
1514 public function addHTML( $text ) {
1515 $this->mBodytext .= $text;
1516 }
1517
1518 /**
1519 * Shortcut for adding an Html::element via addHTML.
1520 *
1521 * @since 1.19
1522 *
1523 * @param string $element
1524 * @param array $attribs
1525 * @param string $contents
1526 */
1527 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1528 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1529 }
1530
1531 /**
1532 * Clear the body HTML
1533 */
1534 public function clearHTML() {
1535 $this->mBodytext = '';
1536 }
1537
1538 /**
1539 * Get the body HTML
1540 *
1541 * @return string HTML
1542 */
1543 public function getHTML() {
1544 return $this->mBodytext;
1545 }
1546
1547 /**
1548 * Get/set the ParserOptions object to use for wikitext parsing
1549 *
1550 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1551 * current ParserOption object
1552 * @return ParserOptions
1553 */
1554 public function parserOptions( $options = null ) {
1555 if ( !$this->mParserOptions ) {
1556 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1557 $this->mParserOptions->setEditSection( false );
1558 }
1559 return wfSetVar( $this->mParserOptions, $options );
1560 }
1561
1562 /**
1563 * Set the revision ID which will be seen by the wiki text parser
1564 * for things such as embedded {{REVISIONID}} variable use.
1565 *
1566 * @param int|null $revid An positive integer, or null
1567 * @return mixed Previous value
1568 */
1569 public function setRevisionId( $revid ) {
1570 $val = is_null( $revid ) ? null : intval( $revid );
1571 return wfSetVar( $this->mRevisionId, $val );
1572 }
1573
1574 /**
1575 * Get the displayed revision ID
1576 *
1577 * @return int
1578 */
1579 public function getRevisionId() {
1580 return $this->mRevisionId;
1581 }
1582
1583 /**
1584 * Set the timestamp of the revision which will be displayed. This is used
1585 * to avoid a extra DB call in Skin::lastModified().
1586 *
1587 * @param string|null $timestamp
1588 * @return mixed Previous value
1589 */
1590 public function setRevisionTimestamp( $timestamp ) {
1591 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1592 }
1593
1594 /**
1595 * Get the timestamp of displayed revision.
1596 * This will be null if not filled by setRevisionTimestamp().
1597 *
1598 * @return string|null
1599 */
1600 public function getRevisionTimestamp() {
1601 return $this->mRevisionTimestamp;
1602 }
1603
1604 /**
1605 * Set the displayed file version
1606 *
1607 * @param File|bool $file
1608 * @return mixed Previous value
1609 */
1610 public function setFileVersion( $file ) {
1611 $val = null;
1612 if ( $file instanceof File && $file->exists() ) {
1613 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1614 }
1615 return wfSetVar( $this->mFileVersion, $val, true );
1616 }
1617
1618 /**
1619 * Get the displayed file version
1620 *
1621 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1622 */
1623 public function getFileVersion() {
1624 return $this->mFileVersion;
1625 }
1626
1627 /**
1628 * Get the templates used on this page
1629 *
1630 * @return array (namespace => dbKey => revId)
1631 * @since 1.18
1632 */
1633 public function getTemplateIds() {
1634 return $this->mTemplateIds;
1635 }
1636
1637 /**
1638 * Get the files used on this page
1639 *
1640 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1641 * @since 1.18
1642 */
1643 public function getFileSearchOptions() {
1644 return $this->mImageTimeKeys;
1645 }
1646
1647 /**
1648 * Convert wikitext to HTML and add it to the buffer
1649 * Default assumes that the current page title will be used.
1650 *
1651 * @param string $text
1652 * @param bool $linestart Is this the start of a line?
1653 * @param bool $interface Is this text in the user interface language?
1654 * @throws MWException
1655 */
1656 public function addWikiText( $text, $linestart = true, $interface = true ) {
1657 $title = $this->getTitle(); // Work around E_STRICT
1658 if ( !$title ) {
1659 throw new MWException( 'Title is null' );
1660 }
1661 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1662 }
1663
1664 /**
1665 * Add wikitext with a custom Title object
1666 *
1667 * @param string $text Wikitext
1668 * @param Title $title
1669 * @param bool $linestart Is this the start of a line?
1670 */
1671 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1672 $this->addWikiTextTitle( $text, $title, $linestart );
1673 }
1674
1675 /**
1676 * Add wikitext with a custom Title object and tidy enabled.
1677 *
1678 * @param string $text Wikitext
1679 * @param Title $title
1680 * @param bool $linestart Is this the start of a line?
1681 */
1682 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1683 $this->addWikiTextTitle( $text, $title, $linestart, true );
1684 }
1685
1686 /**
1687 * Add wikitext with tidy enabled
1688 *
1689 * @param string $text Wikitext
1690 * @param bool $linestart Is this the start of a line?
1691 */
1692 public function addWikiTextTidy( $text, $linestart = true ) {
1693 $title = $this->getTitle();
1694 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1695 }
1696
1697 /**
1698 * Add wikitext with a custom Title object
1699 *
1700 * @param string $text Wikitext
1701 * @param Title $title
1702 * @param bool $linestart Is this the start of a line?
1703 * @param bool $tidy Whether to use tidy
1704 * @param bool $interface Whether it is an interface message
1705 * (for example disables conversion)
1706 */
1707 public function addWikiTextTitle( $text, Title $title, $linestart,
1708 $tidy = false, $interface = false
1709 ) {
1710 global $wgParser;
1711
1712 $popts = $this->parserOptions();
1713 $oldTidy = $popts->setTidy( $tidy );
1714 $popts->setInterfaceMessage( (bool)$interface );
1715
1716 $parserOutput = $wgParser->getFreshParser()->parse(
1717 $text, $title, $popts,
1718 $linestart, true, $this->mRevisionId
1719 );
1720
1721 $popts->setTidy( $oldTidy );
1722
1723 $this->addParserOutput( $parserOutput );
1724
1725 }
1726
1727 /**
1728 * Add a ParserOutput object, but without Html.
1729 *
1730 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1731 * @param ParserOutput $parserOutput
1732 */
1733 public function addParserOutputNoText( $parserOutput ) {
1734 $this->addParserOutputMetadata( $parserOutput );
1735 }
1736
1737 /**
1738 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1739 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1740 * and so on.
1741 *
1742 * @since 1.24
1743 * @param ParserOutput $parserOutput
1744 */
1745 public function addParserOutputMetadata( $parserOutput ) {
1746 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1747 $this->addCategoryLinks( $parserOutput->getCategories() );
1748 $this->setIndicators( $parserOutput->getIndicators() );
1749 $this->mNewSectionLink = $parserOutput->getNewSection();
1750 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1751
1752 $this->mParseWarnings = $parserOutput->getWarnings();
1753 if ( !$parserOutput->isCacheable() ) {
1754 $this->enableClientCache( false );
1755 }
1756 $this->mNoGallery = $parserOutput->getNoGallery();
1757 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1758 $this->addModules( $parserOutput->getModules() );
1759 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1760 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1761 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1762 $this->mPreventClickjacking = $this->mPreventClickjacking
1763 || $parserOutput->preventClickjacking();
1764
1765 // Template versioning...
1766 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1767 if ( isset( $this->mTemplateIds[$ns] ) ) {
1768 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1769 } else {
1770 $this->mTemplateIds[$ns] = $dbks;
1771 }
1772 }
1773 // File versioning...
1774 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1775 $this->mImageTimeKeys[$dbk] = $data;
1776 }
1777
1778 // Hooks registered in the object
1779 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1780 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1781 list( $hookName, $data ) = $hookInfo;
1782 if ( isset( $parserOutputHooks[$hookName] ) ) {
1783 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1784 }
1785 }
1786
1787 // Link flags are ignored for now, but may in the future be
1788 // used to mark individual language links.
1789 $linkFlags = array();
1790 Hooks::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1791 Hooks::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1792 }
1793
1794 /**
1795 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1796 * ParserOutput object, without any other metadata.
1797 *
1798 * @since 1.24
1799 * @param ParserOutput $parserOutput
1800 */
1801 public function addParserOutputContent( $parserOutput ) {
1802 $this->addParserOutputText( $parserOutput );
1803
1804 $this->addModules( $parserOutput->getModules() );
1805 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1806 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1807
1808 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1809 }
1810
1811 /**
1812 * Add the HTML associated with a ParserOutput object, without any metadata.
1813 *
1814 * @since 1.24
1815 * @param ParserOutput $parserOutput
1816 */
1817 public function addParserOutputText( $parserOutput ) {
1818 $text = $parserOutput->getText();
1819 Hooks::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1820 $this->addHTML( $text );
1821 }
1822
1823 /**
1824 * Add everything from a ParserOutput object.
1825 *
1826 * @param ParserOutput $parserOutput
1827 */
1828 function addParserOutput( $parserOutput ) {
1829 $this->addParserOutputMetadata( $parserOutput );
1830 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1831
1832 // Touch section edit links only if not previously disabled
1833 if ( $parserOutput->getEditSectionTokens() ) {
1834 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1835 }
1836
1837 $this->addParserOutputText( $parserOutput );
1838 }
1839
1840 /**
1841 * Add the output of a QuickTemplate to the output buffer
1842 *
1843 * @param QuickTemplate $template
1844 */
1845 public function addTemplate( &$template ) {
1846 $this->addHTML( $template->getHTML() );
1847 }
1848
1849 /**
1850 * Parse wikitext and return the HTML.
1851 *
1852 * @param string $text
1853 * @param bool $linestart Is this the start of a line?
1854 * @param bool $interface Use interface language ($wgLang instead of
1855 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1856 * This also disables LanguageConverter.
1857 * @param Language $language Target language object, will override $interface
1858 * @throws MWException
1859 * @return string HTML
1860 */
1861 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1862 global $wgParser;
1863
1864 if ( is_null( $this->getTitle() ) ) {
1865 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1866 }
1867
1868 $popts = $this->parserOptions();
1869 if ( $interface ) {
1870 $popts->setInterfaceMessage( true );
1871 }
1872 if ( $language !== null ) {
1873 $oldLang = $popts->setTargetLanguage( $language );
1874 }
1875
1876 $parserOutput = $wgParser->getFreshParser()->parse(
1877 $text, $this->getTitle(), $popts,
1878 $linestart, true, $this->mRevisionId
1879 );
1880
1881 if ( $interface ) {
1882 $popts->setInterfaceMessage( false );
1883 }
1884 if ( $language !== null ) {
1885 $popts->setTargetLanguage( $oldLang );
1886 }
1887
1888 return $parserOutput->getText();
1889 }
1890
1891 /**
1892 * Parse wikitext, strip paragraphs, and return the HTML.
1893 *
1894 * @param string $text
1895 * @param bool $linestart Is this the start of a line?
1896 * @param bool $interface Use interface language ($wgLang instead of
1897 * $wgContLang) while parsing language sensitive magic
1898 * words like GRAMMAR and PLURAL
1899 * @return string HTML
1900 */
1901 public function parseInline( $text, $linestart = true, $interface = false ) {
1902 $parsed = $this->parse( $text, $linestart, $interface );
1903 return Parser::stripOuterParagraph( $parsed );
1904 }
1905
1906 /**
1907 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1908 *
1909 * @param int $maxage Maximum cache time on the Squid, in seconds.
1910 */
1911 public function setSquidMaxage( $maxage ) {
1912 $this->mSquidMaxage = $maxage;
1913 }
1914
1915 /**
1916 * Use enableClientCache(false) to force it to send nocache headers
1917 *
1918 * @param bool $state
1919 *
1920 * @return bool
1921 */
1922 public function enableClientCache( $state ) {
1923 return wfSetVar( $this->mEnableClientCache, $state );
1924 }
1925
1926 /**
1927 * Get the list of cookies that will influence on the cache
1928 *
1929 * @return array
1930 */
1931 function getCacheVaryCookies() {
1932 static $cookies;
1933 if ( $cookies === null ) {
1934 $config = $this->getConfig();
1935 $cookies = array_merge(
1936 array(
1937 $config->get( 'CookiePrefix' ) . 'Token',
1938 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1939 "forceHTTPS",
1940 session_name()
1941 ),
1942 $config->get( 'CacheVaryCookies' )
1943 );
1944 Hooks::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1945 }
1946 return $cookies;
1947 }
1948
1949 /**
1950 * Check if the request has a cache-varying cookie header
1951 * If it does, it's very important that we don't allow public caching
1952 *
1953 * @return bool
1954 */
1955 function haveCacheVaryCookies() {
1956 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1957 if ( $cookieHeader === false ) {
1958 return false;
1959 }
1960 $cvCookies = $this->getCacheVaryCookies();
1961 foreach ( $cvCookies as $cookieName ) {
1962 # Check for a simple string match, like the way squid does it
1963 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1964 wfDebug( __METHOD__ . ": found $cookieName\n" );
1965 return true;
1966 }
1967 }
1968 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
1969 return false;
1970 }
1971
1972 /**
1973 * Add an HTTP header that will influence on the cache
1974 *
1975 * @param string $header Header name
1976 * @param array|null $option
1977 * @todo FIXME: Document the $option parameter; it appears to be for
1978 * X-Vary-Options but what format is acceptable?
1979 */
1980 public function addVaryHeader( $header, $option = null ) {
1981 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
1982 $this->mVaryHeader[$header] = (array)$option;
1983 } elseif ( is_array( $option ) ) {
1984 if ( is_array( $this->mVaryHeader[$header] ) ) {
1985 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
1986 } else {
1987 $this->mVaryHeader[$header] = $option;
1988 }
1989 }
1990 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
1991 }
1992
1993 /**
1994 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1995 * such as Accept-Encoding or Cookie
1996 *
1997 * @return string
1998 */
1999 public function getVaryHeader() {
2000 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2001 }
2002
2003 /**
2004 * Get a complete X-Vary-Options header
2005 *
2006 * @return string
2007 */
2008 public function getXVO() {
2009 $cvCookies = $this->getCacheVaryCookies();
2010
2011 $cookiesOption = array();
2012 foreach ( $cvCookies as $cookieName ) {
2013 $cookiesOption[] = 'string-contains=' . $cookieName;
2014 }
2015 $this->addVaryHeader( 'Cookie', $cookiesOption );
2016
2017 $headers = array();
2018 foreach ( $this->mVaryHeader as $header => $option ) {
2019 $newheader = $header;
2020 if ( is_array( $option ) && count( $option ) > 0 ) {
2021 $newheader .= ';' . implode( ';', $option );
2022 }
2023 $headers[] = $newheader;
2024 }
2025 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2026
2027 return $xvo;
2028 }
2029
2030 /**
2031 * bug 21672: Add Accept-Language to Vary and XVO headers
2032 * if there's no 'variant' parameter existed in GET.
2033 *
2034 * For example:
2035 * /w/index.php?title=Main_page should always be served; but
2036 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2037 */
2038 function addAcceptLanguage() {
2039 $title = $this->getTitle();
2040 if ( !$title instanceof Title ) {
2041 return;
2042 }
2043
2044 $lang = $title->getPageLanguage();
2045 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2046 $variants = $lang->getVariants();
2047 $aloption = array();
2048 foreach ( $variants as $variant ) {
2049 if ( $variant === $lang->getCode() ) {
2050 continue;
2051 } else {
2052 $aloption[] = 'string-contains=' . $variant;
2053
2054 // IE and some other browsers use BCP 47 standards in
2055 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2056 // We should handle these too.
2057 $variantBCP47 = wfBCP47( $variant );
2058 if ( $variantBCP47 !== $variant ) {
2059 $aloption[] = 'string-contains=' . $variantBCP47;
2060 }
2061 }
2062 }
2063 $this->addVaryHeader( 'Accept-Language', $aloption );
2064 }
2065 }
2066
2067 /**
2068 * Set a flag which will cause an X-Frame-Options header appropriate for
2069 * edit pages to be sent. The header value is controlled by
2070 * $wgEditPageFrameOptions.
2071 *
2072 * This is the default for special pages. If you display a CSRF-protected
2073 * form on an ordinary view page, then you need to call this function.
2074 *
2075 * @param bool $enable
2076 */
2077 public function preventClickjacking( $enable = true ) {
2078 $this->mPreventClickjacking = $enable;
2079 }
2080
2081 /**
2082 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2083 * This can be called from pages which do not contain any CSRF-protected
2084 * HTML form.
2085 */
2086 public function allowClickjacking() {
2087 $this->mPreventClickjacking = false;
2088 }
2089
2090 /**
2091 * Get the prevent-clickjacking flag
2092 *
2093 * @since 1.24
2094 * @return bool
2095 */
2096 public function getPreventClickjacking() {
2097 return $this->mPreventClickjacking;
2098 }
2099
2100 /**
2101 * Get the X-Frame-Options header value (without the name part), or false
2102 * if there isn't one. This is used by Skin to determine whether to enable
2103 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2104 *
2105 * @return string
2106 */
2107 public function getFrameOptions() {
2108 $config = $this->getConfig();
2109 if ( $config->get( 'BreakFrames' ) ) {
2110 return 'DENY';
2111 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2112 return $config->get( 'EditPageFrameOptions' );
2113 }
2114 return false;
2115 }
2116
2117 /**
2118 * Send cache control HTTP headers
2119 */
2120 public function sendCacheControl() {
2121 $response = $this->getRequest()->response();
2122 $config = $this->getConfig();
2123 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2124 $response->header( "ETag: $this->mETag" );
2125 }
2126
2127 $this->addVaryHeader( 'Cookie' );
2128 $this->addAcceptLanguage();
2129
2130 # don't serve compressed data to clients who can't handle it
2131 # maintain different caches for logged-in users and non-logged in ones
2132 $response->header( $this->getVaryHeader() );
2133
2134 if ( $config->get( 'UseXVO' ) ) {
2135 # Add an X-Vary-Options header for Squid with Wikimedia patches
2136 $response->header( $this->getXVO() );
2137 }
2138
2139 if ( $this->mEnableClientCache ) {
2140 if (
2141 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2142 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2143 ) {
2144 if ( $config->get( 'UseESI' ) ) {
2145 # We'll purge the proxy cache explicitly, but require end user agents
2146 # to revalidate against the proxy on each visit.
2147 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2148 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2149 # start with a shorter timeout for initial testing
2150 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2151 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2152 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2153 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2154 } else {
2155 # We'll purge the proxy cache for anons explicitly, but require end user agents
2156 # to revalidate against the proxy on each visit.
2157 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2158 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2159 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2160 # start with a shorter timeout for initial testing
2161 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2162 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2163 . ', must-revalidate, max-age=0' );
2164 }
2165 } else {
2166 # We do want clients to cache if they can, but they *must* check for updates
2167 # on revisiting the page.
2168 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2169 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2170 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2171 }
2172 if ( $this->mLastModified ) {
2173 $response->header( "Last-Modified: {$this->mLastModified}" );
2174 }
2175 } else {
2176 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2177
2178 # In general, the absence of a last modified header should be enough to prevent
2179 # the client from using its cache. We send a few other things just to make sure.
2180 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2181 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2182 $response->header( 'Pragma: no-cache' );
2183 }
2184 }
2185
2186 /**
2187 * Finally, all the text has been munged and accumulated into
2188 * the object, let's actually output it:
2189 */
2190 public function output() {
2191 if ( $this->mDoNothing ) {
2192 return;
2193 }
2194
2195 $response = $this->getRequest()->response();
2196 $config = $this->getConfig();
2197
2198 if ( $this->mRedirect != '' ) {
2199 # Standards require redirect URLs to be absolute
2200 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2201
2202 $redirect = $this->mRedirect;
2203 $code = $this->mRedirectCode;
2204
2205 if ( Hooks::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2206 if ( $code == '301' || $code == '303' ) {
2207 if ( !$config->get( 'DebugRedirects' ) ) {
2208 $message = HttpStatus::getMessage( $code );
2209 $response->header( "HTTP/1.1 $code $message" );
2210 }
2211 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2212 }
2213 if ( $config->get( 'VaryOnXFP' ) ) {
2214 $this->addVaryHeader( 'X-Forwarded-Proto' );
2215 }
2216 $this->sendCacheControl();
2217
2218 $response->header( "Content-Type: text/html; charset=utf-8" );
2219 if ( $config->get( 'DebugRedirects' ) ) {
2220 $url = htmlspecialchars( $redirect );
2221 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2222 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2223 print "</body>\n</html>\n";
2224 } else {
2225 $response->header( 'Location: ' . $redirect );
2226 }
2227 }
2228
2229 return;
2230 } elseif ( $this->mStatusCode ) {
2231 $message = HttpStatus::getMessage( $this->mStatusCode );
2232 if ( $message ) {
2233 $response->header( 'HTTP/1.1 ' . $this->mStatusCode . ' ' . $message );
2234 }
2235 }
2236
2237 # Buffer output; final headers may depend on later processing
2238 ob_start();
2239
2240 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2241 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2242
2243 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2244 // jQuery etc. can work correctly.
2245 $response->header( 'X-UA-Compatible: IE=Edge' );
2246
2247 // Prevent framing, if requested
2248 $frameOptions = $this->getFrameOptions();
2249 if ( $frameOptions ) {
2250 $response->header( "X-Frame-Options: $frameOptions" );
2251 }
2252
2253 if ( $this->mArticleBodyOnly ) {
2254 echo $this->mBodytext;
2255 } else {
2256
2257 $sk = $this->getSkin();
2258 // add skin specific modules
2259 $modules = $sk->getDefaultModules();
2260
2261 // enforce various default modules for all skins
2262 $coreModules = array(
2263 // keep this list as small as possible
2264 'mediawiki.page.startup',
2265 'mediawiki.user',
2266 );
2267
2268 // Support for high-density display images if enabled
2269 if ( $config->get( 'ResponsiveImages' ) ) {
2270 $coreModules[] = 'mediawiki.hidpi';
2271 }
2272
2273 $this->addModules( $coreModules );
2274 foreach ( $modules as $group ) {
2275 $this->addModules( $group );
2276 }
2277 MWDebug::addModules( $this );
2278
2279 // Hook that allows last minute changes to the output page, e.g.
2280 // adding of CSS or Javascript by extensions.
2281 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2282
2283 $sk->outputPage();
2284 }
2285
2286 // This hook allows last minute changes to final overall output by modifying output buffer
2287 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2288
2289 $this->sendCacheControl();
2290
2291 ob_end_flush();
2292
2293 }
2294
2295 /**
2296 * Actually output something with print.
2297 *
2298 * @param string $ins The string to output
2299 * @deprecated since 1.22 Use echo yourself.
2300 */
2301 public function out( $ins ) {
2302 wfDeprecated( __METHOD__, '1.22' );
2303 print $ins;
2304 }
2305
2306 /**
2307 * Produce a "user is blocked" page.
2308 * @deprecated since 1.18
2309 */
2310 function blockedPage() {
2311 throw new UserBlockedError( $this->getUser()->mBlock );
2312 }
2313
2314 /**
2315 * Prepare this object to display an error page; disable caching and
2316 * indexing, clear the current text and redirect, set the page's title
2317 * and optionally an custom HTML title (content of the "<title>" tag).
2318 *
2319 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2320 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2321 * optional, if not passed the "<title>" attribute will be
2322 * based on $pageTitle
2323 */
2324 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2325 $this->setPageTitle( $pageTitle );
2326 if ( $htmlTitle !== false ) {
2327 $this->setHTMLTitle( $htmlTitle );
2328 }
2329 $this->setRobotPolicy( 'noindex,nofollow' );
2330 $this->setArticleRelated( false );
2331 $this->enableClientCache( false );
2332 $this->mRedirect = '';
2333 $this->clearSubtitle();
2334 $this->clearHTML();
2335 }
2336
2337 /**
2338 * Output a standard error page
2339 *
2340 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2341 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2342 * showErrorPage( 'titlemsg', $messageObject );
2343 * showErrorPage( $titleMessageObject, $messageObject );
2344 *
2345 * @param string|Message $title Message key (string) for page title, or a Message object
2346 * @param string|Message $msg Message key (string) for page text, or a Message object
2347 * @param array $params Message parameters; ignored if $msg is a Message object
2348 */
2349 public function showErrorPage( $title, $msg, $params = array() ) {
2350 if ( !$title instanceof Message ) {
2351 $title = $this->msg( $title );
2352 }
2353
2354 $this->prepareErrorPage( $title );
2355
2356 if ( $msg instanceof Message ) {
2357 if ( $params !== array() ) {
2358 trigger_error( 'Argument ignored: $params. The message parameters argument '
2359 . 'is discarded when the $msg argument is a Message object instead of '
2360 . 'a string.', E_USER_NOTICE );
2361 }
2362 $this->addHTML( $msg->parseAsBlock() );
2363 } else {
2364 $this->addWikiMsgArray( $msg, $params );
2365 }
2366
2367 $this->returnToMain();
2368 }
2369
2370 /**
2371 * Output a standard permission error page
2372 *
2373 * @param array $errors Error message keys
2374 * @param string $action Action that was denied or null if unknown
2375 */
2376 public function showPermissionsErrorPage( array $errors, $action = null ) {
2377 // For some action (read, edit, create and upload), display a "login to do this action"
2378 // error if all of the following conditions are met:
2379 // 1. the user is not logged in
2380 // 2. the only error is insufficient permissions (i.e. no block or something else)
2381 // 3. the error can be avoided simply by logging in
2382 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2383 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2384 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2385 && ( User::groupHasPermission( 'user', $action )
2386 || User::groupHasPermission( 'autoconfirmed', $action ) )
2387 ) {
2388 $displayReturnto = null;
2389
2390 # Due to bug 32276, if a user does not have read permissions,
2391 # $this->getTitle() will just give Special:Badtitle, which is
2392 # not especially useful as a returnto parameter. Use the title
2393 # from the request instead, if there was one.
2394 $request = $this->getRequest();
2395 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2396 if ( $action == 'edit' ) {
2397 $msg = 'whitelistedittext';
2398 $displayReturnto = $returnto;
2399 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2400 $msg = 'nocreatetext';
2401 } elseif ( $action == 'upload' ) {
2402 $msg = 'uploadnologintext';
2403 } else { # Read
2404 $msg = 'loginreqpagetext';
2405 $displayReturnto = Title::newMainPage();
2406 }
2407
2408 $query = array();
2409
2410 if ( $returnto ) {
2411 $query['returnto'] = $returnto->getPrefixedText();
2412
2413 if ( !$request->wasPosted() ) {
2414 $returntoquery = $request->getValues();
2415 unset( $returntoquery['title'] );
2416 unset( $returntoquery['returnto'] );
2417 unset( $returntoquery['returntoquery'] );
2418 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2419 }
2420 }
2421 $loginLink = Linker::linkKnown(
2422 SpecialPage::getTitleFor( 'Userlogin' ),
2423 $this->msg( 'loginreqlink' )->escaped(),
2424 array(),
2425 $query
2426 );
2427
2428 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2429 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2430
2431 # Don't return to a page the user can't read otherwise
2432 # we'll end up in a pointless loop
2433 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2434 $this->returnToMain( null, $displayReturnto );
2435 }
2436 } else {
2437 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2438 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2439 }
2440 }
2441
2442 /**
2443 * Display an error page indicating that a given version of MediaWiki is
2444 * required to use it
2445 *
2446 * @param mixed $version The version of MediaWiki needed to use the page
2447 */
2448 public function versionRequired( $version ) {
2449 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2450
2451 $this->addWikiMsg( 'versionrequiredtext', $version );
2452 $this->returnToMain();
2453 }
2454
2455 /**
2456 * Display an error page noting that a given permission bit is required.
2457 * @deprecated since 1.18, just throw the exception directly
2458 * @param string $permission Key required
2459 * @throws PermissionsError
2460 */
2461 public function permissionRequired( $permission ) {
2462 throw new PermissionsError( $permission );
2463 }
2464
2465 /**
2466 * Produce the stock "please login to use the wiki" page
2467 *
2468 * @deprecated since 1.19; throw the exception directly
2469 */
2470 public function loginToUse() {
2471 throw new PermissionsError( 'read' );
2472 }
2473
2474 /**
2475 * Format a list of error messages
2476 *
2477 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2478 * @param string $action Action that was denied or null if unknown
2479 * @return string The wikitext error-messages, formatted into a list.
2480 */
2481 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2482 if ( $action == null ) {
2483 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2484 } else {
2485 $action_desc = $this->msg( "action-$action" )->plain();
2486 $text = $this->msg(
2487 'permissionserrorstext-withaction',
2488 count( $errors ),
2489 $action_desc
2490 )->plain() . "\n\n";
2491 }
2492
2493 if ( count( $errors ) > 1 ) {
2494 $text .= '<ul class="permissions-errors">' . "\n";
2495
2496 foreach ( $errors as $error ) {
2497 $text .= '<li>';
2498 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2499 $text .= "</li>\n";
2500 }
2501 $text .= '</ul>';
2502 } else {
2503 $text .= "<div class=\"permissions-errors\">\n" .
2504 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2505 "\n</div>";
2506 }
2507
2508 return $text;
2509 }
2510
2511 /**
2512 * Display a page stating that the Wiki is in read-only mode.
2513 * Should only be called after wfReadOnly() has returned true.
2514 *
2515 * Historically, this function was used to show the source of the page that the user
2516 * was trying to edit and _also_ permissions error messages. The relevant code was
2517 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2518 *
2519 * @deprecated since 1.25; throw the exception directly
2520 * @throws ReadOnlyError
2521 */
2522 public function readOnlyPage() {
2523 if ( func_num_args() > 0 ) {
2524 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2525 }
2526
2527 throw new ReadOnlyError;
2528 }
2529
2530 /**
2531 * Turn off regular page output and return an error response
2532 * for when rate limiting has triggered.
2533 *
2534 * @deprecated since 1.25; throw the exception directly
2535 */
2536 public function rateLimited() {
2537 wfDeprecated( __METHOD__, '1.25' );
2538 throw new ThrottledError;
2539 }
2540
2541 /**
2542 * Show a warning about slave lag
2543 *
2544 * If the lag is higher than $wgSlaveLagCritical seconds,
2545 * then the warning is a bit more obvious. If the lag is
2546 * lower than $wgSlaveLagWarning, then no warning is shown.
2547 *
2548 * @param int $lag Slave lag
2549 */
2550 public function showLagWarning( $lag ) {
2551 $config = $this->getConfig();
2552 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2553 $message = $lag < $config->get( 'SlaveLagCritical' )
2554 ? 'lag-warn-normal'
2555 : 'lag-warn-high';
2556 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2557 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2558 }
2559 }
2560
2561 public function showFatalError( $message ) {
2562 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2563
2564 $this->addHTML( $message );
2565 }
2566
2567 public function showUnexpectedValueError( $name, $val ) {
2568 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2569 }
2570
2571 public function showFileCopyError( $old, $new ) {
2572 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2573 }
2574
2575 public function showFileRenameError( $old, $new ) {
2576 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2577 }
2578
2579 public function showFileDeleteError( $name ) {
2580 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2581 }
2582
2583 public function showFileNotFoundError( $name ) {
2584 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2585 }
2586
2587 /**
2588 * Add a "return to" link pointing to a specified title
2589 *
2590 * @param Title $title Title to link
2591 * @param array $query Query string parameters
2592 * @param string $text Text of the link (input is not escaped)
2593 * @param array $options Options array to pass to Linker
2594 */
2595 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2596 $link = $this->msg( 'returnto' )->rawParams(
2597 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2598 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2599 }
2600
2601 /**
2602 * Add a "return to" link pointing to a specified title,
2603 * or the title indicated in the request, or else the main page
2604 *
2605 * @param mixed $unused
2606 * @param Title|string $returnto Title or String to return to
2607 * @param string $returntoquery Query string for the return to link
2608 */
2609 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2610 if ( $returnto == null ) {
2611 $returnto = $this->getRequest()->getText( 'returnto' );
2612 }
2613
2614 if ( $returntoquery == null ) {
2615 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2616 }
2617
2618 if ( $returnto === '' ) {
2619 $returnto = Title::newMainPage();
2620 }
2621
2622 if ( is_object( $returnto ) ) {
2623 $titleObj = $returnto;
2624 } else {
2625 $titleObj = Title::newFromText( $returnto );
2626 }
2627 if ( !is_object( $titleObj ) ) {
2628 $titleObj = Title::newMainPage();
2629 }
2630
2631 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2632 }
2633
2634 /**
2635 * @param Skin $sk The given Skin
2636 * @param bool $includeStyle Unused
2637 * @return string The doctype, opening "<html>", and head element.
2638 */
2639 public function headElement( Skin $sk, $includeStyle = true ) {
2640 global $wgContLang;
2641
2642 $userdir = $this->getLanguage()->getDir();
2643 $sitedir = $wgContLang->getDir();
2644
2645 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2646
2647 if ( $this->getHTMLTitle() == '' ) {
2648 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2649 }
2650
2651 $openHead = Html::openElement( 'head' );
2652 if ( $openHead ) {
2653 # Don't bother with the newline if $head == ''
2654 $ret .= "$openHead\n";
2655 }
2656
2657 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2658 // Add <meta charset="UTF-8">
2659 // This should be before <title> since it defines the charset used by
2660 // text including the text inside <title>.
2661 // The spec recommends defining XHTML5's charset using the XML declaration
2662 // instead of meta.
2663 // Our XML declaration is output by Html::htmlHeader.
2664 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2665 // http://www.whatwg.org/html/semantics.html#charset
2666 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2667 }
2668
2669 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2670
2671 foreach ( $this->getHeadLinksArray() as $item ) {
2672 $ret .= $item . "\n";
2673 }
2674
2675 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2676 $ret .= $this->buildCssLinks();
2677
2678 $ret .= $this->getHeadScripts() . "\n";
2679
2680 foreach ( $this->mHeadItems as $item ) {
2681 $ret .= $item . "\n";
2682 }
2683
2684 $closeHead = Html::closeElement( 'head' );
2685 if ( $closeHead ) {
2686 $ret .= "$closeHead\n";
2687 }
2688
2689 $bodyClasses = array();
2690 $bodyClasses[] = 'mediawiki';
2691
2692 # Classes for LTR/RTL directionality support
2693 $bodyClasses[] = $userdir;
2694 $bodyClasses[] = "sitedir-$sitedir";
2695
2696 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2697 # A <body> class is probably not the best way to do this . . .
2698 $bodyClasses[] = 'capitalize-all-nouns';
2699 }
2700
2701 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2702 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2703 $bodyClasses[] =
2704 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2705
2706 $bodyAttrs = array();
2707 // While the implode() is not strictly needed, it's used for backwards compatibility
2708 // (this used to be built as a string and hooks likely still expect that).
2709 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2710
2711 // Allow skins and extensions to add body attributes they need
2712 $sk->addToBodyAttributes( $this, $bodyAttrs );
2713 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2714
2715 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2716
2717 return $ret;
2718 }
2719
2720 /**
2721 * Get a ResourceLoader object associated with this OutputPage
2722 *
2723 * @return ResourceLoader
2724 */
2725 public function getResourceLoader() {
2726 if ( is_null( $this->mResourceLoader ) ) {
2727 $this->mResourceLoader = new ResourceLoader( $this->getConfig() );
2728 }
2729 return $this->mResourceLoader;
2730 }
2731
2732 /**
2733 * @todo Document
2734 * @param array|string $modules One or more module names
2735 * @param string $only ResourceLoaderModule TYPE_ class constant
2736 * @param bool $useESI
2737 * @param array $extraQuery Array with extra query parameters to add to each
2738 * request. array( param => value ).
2739 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2740 * call rather than a "<script src='...'>" tag.
2741 * @return string The html "<script>", "<link>" and "<style>" tags
2742 */
2743 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2744 array $extraQuery = array(), $loadCall = false
2745 ) {
2746 $modules = (array)$modules;
2747
2748 $links = array(
2749 'html' => '',
2750 'states' => array(),
2751 );
2752
2753 if ( !count( $modules ) ) {
2754 return $links;
2755 }
2756
2757 if ( count( $modules ) > 1 ) {
2758 // Remove duplicate module requests
2759 $modules = array_unique( $modules );
2760 // Sort module names so requests are more uniform
2761 sort( $modules );
2762
2763 if ( ResourceLoader::inDebugMode() ) {
2764 // Recursively call us for every item
2765 foreach ( $modules as $name ) {
2766 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2767 $links['html'] .= $link['html'];
2768 $links['states'] += $link['states'];
2769 }
2770 return $links;
2771 }
2772 }
2773
2774 if ( !is_null( $this->mTarget ) ) {
2775 $extraQuery['target'] = $this->mTarget;
2776 }
2777
2778 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2779 $sortedModules = array();
2780 $resourceLoader = $this->getResourceLoader();
2781 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2782 foreach ( $modules as $name ) {
2783 $module = $resourceLoader->getModule( $name );
2784 # Check that we're allowed to include this module on this page
2785 if ( !$module
2786 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2787 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2788 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2789 && $only == ResourceLoaderModule::TYPE_STYLES )
2790 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2791 && $only == ResourceLoaderModule::TYPE_COMBINED )
2792 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2793 ) {
2794 continue;
2795 }
2796
2797 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2798 }
2799
2800 foreach ( $sortedModules as $source => $groups ) {
2801 foreach ( $groups as $group => $grpModules ) {
2802 // Special handling for user-specific groups
2803 $user = null;
2804 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2805 $user = $this->getUser()->getName();
2806 }
2807
2808 // Create a fake request based on the one we are about to make so modules return
2809 // correct timestamp and emptiness data
2810 $query = ResourceLoader::makeLoaderQuery(
2811 array(), // modules; not determined yet
2812 $this->getLanguage()->getCode(),
2813 $this->getSkin()->getSkinName(),
2814 $user,
2815 null, // version; not determined yet
2816 ResourceLoader::inDebugMode(),
2817 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2818 $this->isPrintable(),
2819 $this->getRequest()->getBool( 'handheld' ),
2820 $extraQuery
2821 );
2822 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2823
2824 // Extract modules that know they're empty and see if we have one or more
2825 // raw modules
2826 $isRaw = false;
2827 foreach ( $grpModules as $key => $module ) {
2828 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2829 // If we're only getting the styles, we don't need to do anything for empty modules.
2830 if ( $module->isKnownEmpty( $context ) ) {
2831 unset( $grpModules[$key] );
2832 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2833 $links['states'][$key] = 'ready';
2834 }
2835 }
2836
2837 $isRaw |= $module->isRaw();
2838 }
2839
2840 // If there are no non-empty modules, skip this group
2841 if ( count( $grpModules ) === 0 ) {
2842 continue;
2843 }
2844
2845 // Inline private modules. These can't be loaded through load.php for security
2846 // reasons, see bug 34907. Note that these modules should be loaded from
2847 // getHeadScripts() before the first loader call. Otherwise other modules can't
2848 // properly use them as dependencies (bug 30914)
2849 if ( $group === 'private' ) {
2850 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2851 $links['html'] .= Html::inlineStyle(
2852 $resourceLoader->makeModuleResponse( $context, $grpModules )
2853 );
2854 } else {
2855 $links['html'] .= ResourceLoader::makeInlineScript(
2856 $resourceLoader->makeModuleResponse( $context, $grpModules )
2857 );
2858 }
2859 $links['html'] .= "\n";
2860 continue;
2861 }
2862
2863 // Special handling for the user group; because users might change their stuff
2864 // on-wiki like user pages, or user preferences; we need to find the highest
2865 // timestamp of these user-changeable modules so we can ensure cache misses on change
2866 // This should NOT be done for the site group (bug 27564) because anons get that too
2867 // and we shouldn't be putting timestamps in Squid-cached HTML
2868 $version = null;
2869 if ( $group === 'user' ) {
2870 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2871 }
2872
2873 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2874 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2875 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2876
2877 if ( $useESI && $resourceLoaderUseESI ) {
2878 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2879 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2880 $link = Html::inlineStyle( $esi );
2881 } else {
2882 $link = Html::inlineScript( $esi );
2883 }
2884 } else {
2885 // Automatically select style/script elements
2886 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2887 $link = Html::linkedStyle( $url );
2888 } elseif ( $loadCall ) {
2889 $link = ResourceLoader::makeInlineScript(
2890 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2891 );
2892 } else {
2893 $link = Html::linkedScript( $url );
2894 if ( !$context->getRaw() && !$isRaw ) {
2895 // Wrap only=script / only=combined requests in a conditional as
2896 // browsers not supported by the startup module would unconditionally
2897 // execute this module. Otherwise users will get "ReferenceError: mw is
2898 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2899 $link = ResourceLoader::makeInlineScript(
2900 Xml::encodeJsCall( 'document.write', array( $link ) )
2901 );
2902 }
2903
2904 // For modules requested directly in the html via <link> or <script>,
2905 // tell mw.loader they are being loading to prevent duplicate requests.
2906 foreach ( $grpModules as $key => $module ) {
2907 // Don't output state=loading for the startup module..
2908 if ( $key !== 'startup' ) {
2909 $links['states'][$key] = 'loading';
2910 }
2911 }
2912 }
2913 }
2914
2915 if ( $group == 'noscript' ) {
2916 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2917 } else {
2918 $links['html'] .= $link . "\n";
2919 }
2920 }
2921 }
2922
2923 return $links;
2924 }
2925
2926 /**
2927 * Build html output from an array of links from makeResourceLoaderLink.
2928 * @param array $links
2929 * @return string HTML
2930 */
2931 protected static function getHtmlFromLoaderLinks( array $links ) {
2932 $html = '';
2933 $states = array();
2934 foreach ( $links as $link ) {
2935 if ( !is_array( $link ) ) {
2936 $html .= $link;
2937 } else {
2938 $html .= $link['html'];
2939 $states += $link['states'];
2940 }
2941 }
2942
2943 if ( count( $states ) ) {
2944 $html = ResourceLoader::makeInlineScript(
2945 ResourceLoader::makeLoaderStateScript( $states )
2946 ) . "\n" . $html;
2947 }
2948
2949 return $html;
2950 }
2951
2952 /**
2953 * JS stuff to put in the "<head>". This is the startup module, config
2954 * vars and modules marked with position 'top'
2955 *
2956 * @return string HTML fragment
2957 */
2958 function getHeadScripts() {
2959 // Startup - this will immediately load jquery and mediawiki modules
2960 $links = array();
2961 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2962
2963 // Load config before anything else
2964 $links[] = ResourceLoader::makeInlineScript(
2965 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2966 );
2967
2968 // Load embeddable private modules before any loader links
2969 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2970 // in mw.loader.implement() calls and deferred until mw.user is available
2971 $embedScripts = array( 'user.options', 'user.tokens' );
2972 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2973
2974 // Scripts and messages "only" requests marked for top inclusion
2975 $links[] = $this->makeResourceLoaderLink(
2976 $this->getModuleScripts( true, 'top' ),
2977 ResourceLoaderModule::TYPE_SCRIPTS
2978 );
2979
2980 // Modules requests - let the client calculate dependencies and batch requests as it likes
2981 // Only load modules that have marked themselves for loading at the top
2982 $modules = $this->getModules( true, 'top' );
2983 if ( $modules ) {
2984 $links[] = ResourceLoader::makeInlineScript(
2985 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
2986 );
2987 }
2988
2989 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2990 $links[] = $this->getScriptsForBottomQueue( true );
2991 }
2992
2993 return self::getHtmlFromLoaderLinks( $links );
2994 }
2995
2996 /**
2997 * JS stuff to put at the 'bottom', which can either be the bottom of the
2998 * "<body>" or the bottom of the "<head>" depending on
2999 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3000 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3001 * and user JS.
3002 *
3003 * @param bool $inHead If true, this HTML goes into the "<head>",
3004 * if false it goes into the "<body>".
3005 * @return string
3006 */
3007 function getScriptsForBottomQueue( $inHead ) {
3008 // Scripts "only" requests marked for bottom inclusion
3009 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3010 $links = array();
3011 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3012 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
3013 /* $loadCall = */ $inHead
3014 );
3015
3016 // Modules requests - let the client calculate dependencies and batch requests as it likes
3017 // Only load modules that have marked themselves for loading at the bottom
3018 $modules = $this->getModules( true, 'bottom' );
3019 if ( $modules ) {
3020 $links[] = ResourceLoader::makeInlineScript(
3021 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3022 );
3023 }
3024
3025 // Legacy Scripts
3026 $links[] = "\n" . $this->mScripts;
3027
3028 // Add site JS if enabled
3029 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
3030 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3031 );
3032
3033 // Add user JS if enabled
3034 if ( $this->getConfig()->get( 'AllowUserJs' )
3035 && $this->getUser()->isLoggedIn()
3036 && $this->getTitle()
3037 && $this->getTitle()->isJsSubpage()
3038 && $this->userCanPreview()
3039 ) {
3040 # XXX: additional security check/prompt?
3041 // We're on a preview of a JS subpage
3042 // Exclude this page from the user module in case it's in there (bug 26283)
3043 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3044 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3045 );
3046 // Load the previewed JS
3047 $links[] = Html::inlineScript( "\n"
3048 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3049
3050 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3051 // asynchronously and may arrive *after* the inline script here. So the previewed code
3052 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3053 } else {
3054 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3055 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3056 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3057 );
3058 }
3059
3060 // Group JS is only enabled if site JS is enabled.
3061 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3062 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3063 );
3064
3065 return self::getHtmlFromLoaderLinks( $links );
3066 }
3067
3068 /**
3069 * JS stuff to put at the bottom of the "<body>"
3070 * @return string
3071 */
3072 function getBottomScripts() {
3073 // Optimise jQuery ready event cross-browser.
3074 // This also enforces $.isReady to be true at </body> which fixes the
3075 // mw.loader bug in Firefox with using document.write between </body>
3076 // and the DOMContentReady event (bug 47457).
3077 $html = Html::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3078
3079 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3080 $html .= $this->getScriptsForBottomQueue( false );
3081 }
3082
3083 return $html;
3084 }
3085
3086 /**
3087 * Get the javascript config vars to include on this page
3088 *
3089 * @return array Array of javascript config vars
3090 * @since 1.23
3091 */
3092 public function getJsConfigVars() {
3093 return $this->mJsConfigVars;
3094 }
3095
3096 /**
3097 * Add one or more variables to be set in mw.config in JavaScript
3098 *
3099 * @param string|array $keys Key or array of key/value pairs
3100 * @param mixed $value [optional] Value of the configuration variable
3101 */
3102 public function addJsConfigVars( $keys, $value = null ) {
3103 if ( is_array( $keys ) ) {
3104 foreach ( $keys as $key => $value ) {
3105 $this->mJsConfigVars[$key] = $value;
3106 }
3107 return;
3108 }
3109
3110 $this->mJsConfigVars[$keys] = $value;
3111 }
3112
3113 /**
3114 * Get an array containing the variables to be set in mw.config in JavaScript.
3115 *
3116 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3117 * - in other words, page-independent/site-wide variables (without state).
3118 * You will only be adding bloat to the html page and causing page caches to
3119 * have to be purged on configuration changes.
3120 * @return array
3121 */
3122 public function getJSVars() {
3123 global $wgContLang;
3124
3125 $curRevisionId = 0;
3126 $articleId = 0;
3127 $canonicalSpecialPageName = false; # bug 21115
3128
3129 $title = $this->getTitle();
3130 $ns = $title->getNamespace();
3131 $canonicalNamespace = MWNamespace::exists( $ns )
3132 ? MWNamespace::getCanonicalName( $ns )
3133 : $title->getNsText();
3134
3135 $sk = $this->getSkin();
3136 // Get the relevant title so that AJAX features can use the correct page name
3137 // when making API requests from certain special pages (bug 34972).
3138 $relevantTitle = $sk->getRelevantTitle();
3139 $relevantUser = $sk->getRelevantUser();
3140
3141 if ( $ns == NS_SPECIAL ) {
3142 list( $canonicalSpecialPageName, /*...*/ ) =
3143 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3144 } elseif ( $this->canUseWikiPage() ) {
3145 $wikiPage = $this->getWikiPage();
3146 $curRevisionId = $wikiPage->getLatest();
3147 $articleId = $wikiPage->getId();
3148 }
3149
3150 $lang = $title->getPageLanguage();
3151
3152 // Pre-process information
3153 $separatorTransTable = $lang->separatorTransformTable();
3154 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3155 $compactSeparatorTransTable = array(
3156 implode( "\t", array_keys( $separatorTransTable ) ),
3157 implode( "\t", $separatorTransTable ),
3158 );
3159 $digitTransTable = $lang->digitTransformTable();
3160 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3161 $compactDigitTransTable = array(
3162 implode( "\t", array_keys( $digitTransTable ) ),
3163 implode( "\t", $digitTransTable ),
3164 );
3165
3166 $user = $this->getUser();
3167
3168 $vars = array(
3169 'wgCanonicalNamespace' => $canonicalNamespace,
3170 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3171 'wgNamespaceNumber' => $title->getNamespace(),
3172 'wgPageName' => $title->getPrefixedDBkey(),
3173 'wgTitle' => $title->getText(),
3174 'wgCurRevisionId' => $curRevisionId,
3175 'wgRevisionId' => (int)$this->getRevisionId(),
3176 'wgArticleId' => $articleId,
3177 'wgIsArticle' => $this->isArticle(),
3178 'wgIsRedirect' => $title->isRedirect(),
3179 'wgAction' => Action::getActionName( $this->getContext() ),
3180 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3181 'wgUserGroups' => $user->getEffectiveGroups(),
3182 'wgCategories' => $this->getCategories(),
3183 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3184 'wgPageContentLanguage' => $lang->getCode(),
3185 'wgPageContentModel' => $title->getContentModel(),
3186 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3187 'wgDigitTransformTable' => $compactDigitTransTable,
3188 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3189 'wgMonthNames' => $lang->getMonthNamesArray(),
3190 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3191 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3192 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3193 );
3194
3195 if ( $user->isLoggedIn() ) {
3196 $vars['wgUserId'] = $user->getId();
3197 $vars['wgUserEditCount'] = $user->getEditCount();
3198 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3199 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3200 // Get the revision ID of the oldest new message on the user's talk
3201 // page. This can be used for constructing new message alerts on
3202 // the client side.
3203 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3204 }
3205
3206 if ( $wgContLang->hasVariants() ) {
3207 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3208 }
3209 // Same test as SkinTemplate
3210 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3211 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3212
3213 foreach ( $title->getRestrictionTypes() as $type ) {
3214 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3215 }
3216
3217 if ( $title->isMainPage() ) {
3218 $vars['wgIsMainPage'] = true;
3219 }
3220
3221 if ( $this->mRedirectedFrom ) {
3222 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3223 }
3224
3225 if ( $relevantUser ) {
3226 $vars['wgRelevantUserName'] = $relevantUser->getName();
3227 }
3228
3229 // Allow extensions to add their custom variables to the mw.config map.
3230 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3231 // page-dependant but site-wide (without state).
3232 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3233 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3234
3235 // Merge in variables from addJsConfigVars last
3236 return array_merge( $vars, $this->getJsConfigVars() );
3237 }
3238
3239 /**
3240 * To make it harder for someone to slip a user a fake
3241 * user-JavaScript or user-CSS preview, a random token
3242 * is associated with the login session. If it's not
3243 * passed back with the preview request, we won't render
3244 * the code.
3245 *
3246 * @return bool
3247 */
3248 public function userCanPreview() {
3249 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3250 || !$this->getRequest()->wasPosted()
3251 || !$this->getUser()->matchEditToken(
3252 $this->getRequest()->getVal( 'wpEditToken' ) )
3253 ) {
3254 return false;
3255 }
3256 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3257 return false;
3258 }
3259 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3260 // Don't execute another user's CSS or JS on preview (T85855)
3261 return false;
3262 }
3263
3264 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3265 }
3266
3267 /**
3268 * @return array Array in format "link name or number => 'link html'".
3269 */
3270 public function getHeadLinksArray() {
3271 global $wgVersion;
3272
3273 $tags = array();
3274 $config = $this->getConfig();
3275
3276 $canonicalUrl = $this->mCanonicalUrl;
3277
3278 $tags['meta-generator'] = Html::element( 'meta', array(
3279 'name' => 'generator',
3280 'content' => "MediaWiki $wgVersion",
3281 ) );
3282
3283 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3284 $tags['meta-referrer'] = Html::element( 'meta', array(
3285 'name' => 'referrer',
3286 'content' => $config->get( 'ReferrerPolicy' )
3287 ) );
3288 }
3289
3290 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3291 if ( $p !== 'index,follow' ) {
3292 // http://www.robotstxt.org/wc/meta-user.html
3293 // Only show if it's different from the default robots policy
3294 $tags['meta-robots'] = Html::element( 'meta', array(
3295 'name' => 'robots',
3296 'content' => $p,
3297 ) );
3298 }
3299
3300 foreach ( $this->mMetatags as $tag ) {
3301 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3302 $a = 'http-equiv';
3303 $tag[0] = substr( $tag[0], 5 );
3304 } else {
3305 $a = 'name';
3306 }
3307 $tagName = "meta-{$tag[0]}";
3308 if ( isset( $tags[$tagName] ) ) {
3309 $tagName .= $tag[1];
3310 }
3311 $tags[$tagName] = Html::element( 'meta',
3312 array(
3313 $a => $tag[0],
3314 'content' => $tag[1]
3315 )
3316 );
3317 }
3318
3319 foreach ( $this->mLinktags as $tag ) {
3320 $tags[] = Html::element( 'link', $tag );
3321 }
3322
3323 # Universal edit button
3324 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3325 $user = $this->getUser();
3326 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3327 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3328 // Original UniversalEditButton
3329 $msg = $this->msg( 'edit' )->text();
3330 $tags['universal-edit-button'] = Html::element( 'link', array(
3331 'rel' => 'alternate',
3332 'type' => 'application/x-wiki',
3333 'title' => $msg,
3334 'href' => $this->getTitle()->getEditURL(),
3335 ) );
3336 // Alternate edit link
3337 $tags['alternative-edit'] = Html::element( 'link', array(
3338 'rel' => 'edit',
3339 'title' => $msg,
3340 'href' => $this->getTitle()->getEditURL(),
3341 ) );
3342 }
3343 }
3344
3345 # Generally the order of the favicon and apple-touch-icon links
3346 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3347 # uses whichever one appears later in the HTML source. Make sure
3348 # apple-touch-icon is specified first to avoid this.
3349 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3350 $tags['apple-touch-icon'] = Html::element( 'link', array(
3351 'rel' => 'apple-touch-icon',
3352 'href' => $config->get( 'AppleTouchIcon' )
3353 ) );
3354 }
3355
3356 if ( $config->get( 'Favicon' ) !== false ) {
3357 $tags['favicon'] = Html::element( 'link', array(
3358 'rel' => 'shortcut icon',
3359 'href' => $config->get( 'Favicon' )
3360 ) );
3361 }
3362
3363 # OpenSearch description link
3364 $tags['opensearch'] = Html::element( 'link', array(
3365 'rel' => 'search',
3366 'type' => 'application/opensearchdescription+xml',
3367 'href' => wfScript( 'opensearch_desc' ),
3368 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3369 ) );
3370
3371 if ( $config->get( 'EnableAPI' ) ) {
3372 # Real Simple Discovery link, provides auto-discovery information
3373 # for the MediaWiki API (and potentially additional custom API
3374 # support such as WordPress or Twitter-compatible APIs for a
3375 # blogging extension, etc)
3376 $tags['rsd'] = Html::element( 'link', array(
3377 'rel' => 'EditURI',
3378 'type' => 'application/rsd+xml',
3379 // Output a protocol-relative URL here if $wgServer is protocol-relative
3380 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3381 'href' => wfExpandUrl( wfAppendQuery(
3382 wfScript( 'api' ),
3383 array( 'action' => 'rsd' ) ),
3384 PROTO_RELATIVE
3385 ),
3386 ) );
3387 }
3388
3389 # Language variants
3390 if ( !$config->get( 'DisableLangConversion' ) ) {
3391 $lang = $this->getTitle()->getPageLanguage();
3392 if ( $lang->hasVariants() ) {
3393 $variants = $lang->getVariants();
3394 foreach ( $variants as $_v ) {
3395 $tags["variant-$_v"] = Html::element( 'link', array(
3396 'rel' => 'alternate',
3397 'hreflang' => wfBCP47( $_v ),
3398 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3399 );
3400 }
3401 }
3402 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3403 $tags["variant-x-default"] = Html::element( 'link', array(
3404 'rel' => 'alternate',
3405 'hreflang' => 'x-default',
3406 'href' => $this->getTitle()->getLocalURL() ) );
3407 }
3408
3409 # Copyright
3410 $copyright = '';
3411 if ( $config->get( 'RightsPage' ) ) {
3412 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3413
3414 if ( $copy ) {
3415 $copyright = $copy->getLocalURL();
3416 }
3417 }
3418
3419 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3420 $copyright = $config->get( 'RightsUrl' );
3421 }
3422
3423 if ( $copyright ) {
3424 $tags['copyright'] = Html::element( 'link', array(
3425 'rel' => 'copyright',
3426 'href' => $copyright )
3427 );
3428 }
3429
3430 # Feeds
3431 if ( $config->get( 'Feed' ) ) {
3432 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3433 # Use the page name for the title. In principle, this could
3434 # lead to issues with having the same name for different feeds
3435 # corresponding to the same page, but we can't avoid that at
3436 # this low a level.
3437
3438 $tags[] = $this->feedLink(
3439 $format,
3440 $link,
3441 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3442 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3443 );
3444 }
3445
3446 # Recent changes feed should appear on every page (except recentchanges,
3447 # that would be redundant). Put it after the per-page feed to avoid
3448 # changing existing behavior. It's still available, probably via a
3449 # menu in your browser. Some sites might have a different feed they'd
3450 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3451 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3452 # If so, use it instead.
3453 $sitename = $config->get( 'Sitename' );
3454 if ( $config->get( 'OverrideSiteFeed' ) ) {
3455 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3456 // Note, this->feedLink escapes the url.
3457 $tags[] = $this->feedLink(
3458 $type,
3459 $feedUrl,
3460 $this->msg( "site-{$type}-feed", $sitename )->text()
3461 );
3462 }
3463 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3464 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3465 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3466 $tags[] = $this->feedLink(
3467 $format,
3468 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3469 # For grep: 'site-rss-feed', 'site-atom-feed'
3470 $this->msg( "site-{$format}-feed", $sitename )->text()
3471 );
3472 }
3473 }
3474 }
3475
3476 # Canonical URL
3477 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3478 if ( $canonicalUrl !== false ) {
3479 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3480 } else {
3481 $reqUrl = $this->getRequest()->getRequestURL();
3482 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3483 }
3484 }
3485 if ( $canonicalUrl !== false ) {
3486 $tags[] = Html::element( 'link', array(
3487 'rel' => 'canonical',
3488 'href' => $canonicalUrl
3489 ) );
3490 }
3491
3492 return $tags;
3493 }
3494
3495 /**
3496 * @return string HTML tag links to be put in the header.
3497 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3498 * OutputPage::getHeadLinksArray directly.
3499 */
3500 public function getHeadLinks() {
3501 wfDeprecated( __METHOD__, '1.24' );
3502 return implode( "\n", $this->getHeadLinksArray() );
3503 }
3504
3505 /**
3506 * Generate a "<link rel/>" for a feed.
3507 *
3508 * @param string $type Feed type
3509 * @param string $url URL to the feed
3510 * @param string $text Value of the "title" attribute
3511 * @return string HTML fragment
3512 */
3513 private function feedLink( $type, $url, $text ) {
3514 return Html::element( 'link', array(
3515 'rel' => 'alternate',
3516 'type' => "application/$type+xml",
3517 'title' => $text,
3518 'href' => $url )
3519 );
3520 }
3521
3522 /**
3523 * Add a local or specified stylesheet, with the given media options.
3524 * Meant primarily for internal use...
3525 *
3526 * @param string $style URL to the file
3527 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3528 * @param string $condition For IE conditional comments, specifying an IE version
3529 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3530 */
3531 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3532 $options = array();
3533 // Even though we expect the media type to be lowercase, but here we
3534 // force it to lowercase to be safe.
3535 if ( $media ) {
3536 $options['media'] = $media;
3537 }
3538 if ( $condition ) {
3539 $options['condition'] = $condition;
3540 }
3541 if ( $dir ) {
3542 $options['dir'] = $dir;
3543 }
3544 $this->styles[$style] = $options;
3545 }
3546
3547 /**
3548 * Adds inline CSS styles
3549 * @param mixed $style_css Inline CSS
3550 * @param string $flip Set to 'flip' to flip the CSS if needed
3551 */
3552 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3553 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3554 # If wanted, and the interface is right-to-left, flip the CSS
3555 $style_css = CSSJanus::transform( $style_css, true, false );
3556 }
3557 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3558 }
3559
3560 /**
3561 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3562 * These will be applied to various media & IE conditionals.
3563 *
3564 * @return string
3565 */
3566 public function buildCssLinks() {
3567 global $wgContLang;
3568
3569 $this->getSkin()->setupSkinUserCss( $this );
3570
3571 // Add ResourceLoader styles
3572 // Split the styles into these groups
3573 $styles = array(
3574 'other' => array(),
3575 'user' => array(),
3576 'site' => array(),
3577 'private' => array(),
3578 'noscript' => array()
3579 );
3580 $links = array();
3581 $otherTags = ''; // Tags to append after the normal <link> tags
3582 $resourceLoader = $this->getResourceLoader();
3583
3584 $moduleStyles = $this->getModuleStyles();
3585
3586 // Per-site custom styles
3587 $moduleStyles[] = 'site';
3588 $moduleStyles[] = 'noscript';
3589 $moduleStyles[] = 'user.groups';
3590
3591 // Per-user custom styles
3592 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3593 && $this->userCanPreview()
3594 ) {
3595 // We're on a preview of a CSS subpage
3596 // Exclude this page from the user module in case it's in there (bug 26283)
3597 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3598 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3599 );
3600 $otherTags .= $link['html'];
3601
3602 // Load the previewed CSS
3603 // If needed, Janus it first. This is user-supplied CSS, so it's
3604 // assumed to be right for the content language directionality.
3605 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3606 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3607 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3608 }
3609 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3610 } else {
3611 // Load the user styles normally
3612 $moduleStyles[] = 'user';
3613 }
3614
3615 // Per-user preference styles
3616 $moduleStyles[] = 'user.cssprefs';
3617
3618 foreach ( $moduleStyles as $name ) {
3619 $module = $resourceLoader->getModule( $name );
3620 if ( !$module ) {
3621 continue;
3622 }
3623 $group = $module->getGroup();
3624 // Modules in groups different than the ones listed on top (see $styles assignment)
3625 // will be placed in the "other" group
3626 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3627 }
3628
3629 // We want site, private and user styles to override dynamically added
3630 // styles from modules, but we want dynamically added styles to override
3631 // statically added styles from other modules. So the order has to be
3632 // other, dynamic, site, private, user. Add statically added styles for
3633 // other modules
3634 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3635 // Add normal styles added through addStyle()/addInlineStyle() here
3636 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3637 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3638 // We use a <meta> tag with a made-up name for this because that's valid HTML
3639 $links[] = Html::element(
3640 'meta',
3641 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3642 ) . "\n";
3643
3644 // Add site, private and user styles
3645 // 'private' at present only contains user.options, so put that before 'user'
3646 // Any future private modules will likely have a similar user-specific character
3647 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3648 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3649 ResourceLoaderModule::TYPE_STYLES
3650 );
3651 }
3652
3653 // Add stuff in $otherTags (previewed user CSS if applicable)
3654 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3655 }
3656
3657 /**
3658 * @return array
3659 */
3660 public function buildCssLinksArray() {
3661 $links = array();
3662
3663 // Add any extension CSS
3664 foreach ( $this->mExtStyles as $url ) {
3665 $this->addStyle( $url );
3666 }
3667 $this->mExtStyles = array();
3668
3669 foreach ( $this->styles as $file => $options ) {
3670 $link = $this->styleLink( $file, $options );
3671 if ( $link ) {
3672 $links[$file] = $link;
3673 }
3674 }
3675 return $links;
3676 }
3677
3678 /**
3679 * Generate \<link\> tags for stylesheets
3680 *
3681 * @param string $style URL to the file
3682 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3683 * @return string HTML fragment
3684 */
3685 protected function styleLink( $style, array $options ) {
3686 if ( isset( $options['dir'] ) ) {
3687 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3688 return '';
3689 }
3690 }
3691
3692 if ( isset( $options['media'] ) ) {
3693 $media = self::transformCssMedia( $options['media'] );
3694 if ( is_null( $media ) ) {
3695 return '';
3696 }
3697 } else {
3698 $media = 'all';
3699 }
3700
3701 if ( substr( $style, 0, 1 ) == '/' ||
3702 substr( $style, 0, 5 ) == 'http:' ||
3703 substr( $style, 0, 6 ) == 'https:' ) {
3704 $url = $style;
3705 } else {
3706 $config = $this->getConfig();
3707 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3708 }
3709
3710 $link = Html::linkedStyle( $url, $media );
3711
3712 if ( isset( $options['condition'] ) ) {
3713 $condition = htmlspecialchars( $options['condition'] );
3714 $link = "<!--[if $condition]>$link<![endif]-->";
3715 }
3716 return $link;
3717 }
3718
3719 /**
3720 * Transform "media" attribute based on request parameters
3721 *
3722 * @param string $media Current value of the "media" attribute
3723 * @return string Modified value of the "media" attribute, or null to skip
3724 * this stylesheet
3725 */
3726 public static function transformCssMedia( $media ) {
3727 global $wgRequest;
3728
3729 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3730 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3731
3732 // Switch in on-screen display for media testing
3733 $switches = array(
3734 'printable' => 'print',
3735 'handheld' => 'handheld',
3736 );
3737 foreach ( $switches as $switch => $targetMedia ) {
3738 if ( $wgRequest->getBool( $switch ) ) {
3739 if ( $media == $targetMedia ) {
3740 $media = '';
3741 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3742 // This regex will not attempt to understand a comma-separated media_query_list
3743 //
3744 // Example supported values for $media:
3745 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3746 // Example NOT supported value for $media:
3747 // '3d-glasses, screen, print and resolution > 90dpi'
3748 //
3749 // If it's a print request, we never want any kind of screen stylesheets
3750 // If it's a handheld request (currently the only other choice with a switch),
3751 // we don't want simple 'screen' but we might want screen queries that
3752 // have a max-width or something, so we'll pass all others on and let the
3753 // client do the query.
3754 if ( $targetMedia == 'print' || $media == 'screen' ) {
3755 return null;
3756 }
3757 }
3758 }
3759 }
3760
3761 return $media;
3762 }
3763
3764 /**
3765 * Add a wikitext-formatted message to the output.
3766 * This is equivalent to:
3767 *
3768 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3769 */
3770 public function addWikiMsg( /*...*/ ) {
3771 $args = func_get_args();
3772 $name = array_shift( $args );
3773 $this->addWikiMsgArray( $name, $args );
3774 }
3775
3776 /**
3777 * Add a wikitext-formatted message to the output.
3778 * Like addWikiMsg() except the parameters are taken as an array
3779 * instead of a variable argument list.
3780 *
3781 * @param string $name
3782 * @param array $args
3783 */
3784 public function addWikiMsgArray( $name, $args ) {
3785 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3786 }
3787
3788 /**
3789 * This function takes a number of message/argument specifications, wraps them in
3790 * some overall structure, and then parses the result and adds it to the output.
3791 *
3792 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3793 * and so on. The subsequent arguments may be either
3794 * 1) strings, in which case they are message names, or
3795 * 2) arrays, in which case, within each array, the first element is the message
3796 * name, and subsequent elements are the parameters to that message.
3797 *
3798 * Don't use this for messages that are not in the user's interface language.
3799 *
3800 * For example:
3801 *
3802 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3803 *
3804 * Is equivalent to:
3805 *
3806 * $wgOut->addWikiText( "<div class='error'>\n"
3807 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3808 *
3809 * The newline after the opening div is needed in some wikitext. See bug 19226.
3810 *
3811 * @param string $wrap
3812 */
3813 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3814 $msgSpecs = func_get_args();
3815 array_shift( $msgSpecs );
3816 $msgSpecs = array_values( $msgSpecs );
3817 $s = $wrap;
3818 foreach ( $msgSpecs as $n => $spec ) {
3819 if ( is_array( $spec ) ) {
3820 $args = $spec;
3821 $name = array_shift( $args );
3822 if ( isset( $args['options'] ) ) {
3823 unset( $args['options'] );
3824 wfDeprecated(
3825 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3826 '1.20'
3827 );
3828 }
3829 } else {
3830 $args = array();
3831 $name = $spec;
3832 }
3833 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3834 }
3835 $this->addWikiText( $s );
3836 }
3837
3838 /**
3839 * Include jQuery core. Use this to avoid loading it multiple times
3840 * before we get a usable script loader.
3841 *
3842 * @param array $modules List of jQuery modules which should be loaded
3843 * @return array The list of modules which were not loaded.
3844 * @since 1.16
3845 * @deprecated since 1.17
3846 */
3847 public function includeJQuery( array $modules = array() ) {
3848 return array();
3849 }
3850
3851 /**
3852 * Enables/disables TOC, doesn't override __NOTOC__
3853 * @param bool $flag
3854 * @since 1.22
3855 */
3856 public function enableTOC( $flag = true ) {
3857 $this->mEnableTOC = $flag;
3858 }
3859
3860 /**
3861 * @return bool
3862 * @since 1.22
3863 */
3864 public function isTOCEnabled() {
3865 return $this->mEnableTOC;
3866 }
3867
3868 /**
3869 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3870 * @param bool $flag
3871 * @since 1.23
3872 */
3873 public function enableSectionEditLinks( $flag = true ) {
3874 $this->mEnableSectionEditLinks = $flag;
3875 }
3876
3877 /**
3878 * @return bool
3879 * @since 1.23
3880 */
3881 public function sectionEditLinksEnabled() {
3882 return $this->mEnableSectionEditLinks;
3883 }
3884
3885 /**
3886 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3887 * MediaWiki and this OutputPage instance.
3888 *
3889 * @since 1.25
3890 */
3891 public function enableOOUI() {
3892 OOUI\Theme::setSingleton( new OOUI\MediaWikiTheme() );
3893 OOUI\Element::setDefaultDir( $this->getLanguage()->getDir() );
3894 $this->addModuleStyles( array(
3895 'oojs-ui.styles',
3896 'oojs-ui.styles.icons',
3897 'oojs-ui.styles.indicators',
3898 'oojs-ui.styles.textures',
3899 ) );
3900 }
3901 }