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