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