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