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