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