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