Switch some HTMLForms in special pages to OOUI
[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 'mediawiki.page.startup',
2293 'mediawiki.user',
2294 );
2295
2296 // Support for high-density display images if enabled
2297 if ( $config->get( 'ResponsiveImages' ) ) {
2298 $coreModules[] = 'mediawiki.hidpi';
2299 }
2300
2301 $this->addModules( $coreModules );
2302 foreach ( $modules as $group ) {
2303 $this->addModules( $group );
2304 }
2305 MWDebug::addModules( $this );
2306
2307 // Hook that allows last minute changes to the output page, e.g.
2308 // adding of CSS or Javascript by extensions.
2309 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2310
2311 $sk->outputPage();
2312 }
2313
2314 // This hook allows last minute changes to final overall output by modifying output buffer
2315 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2316
2317 $this->sendCacheControl();
2318
2319 ob_end_flush();
2320
2321 }
2322
2323 /**
2324 * Actually output something with print.
2325 *
2326 * @param string $ins The string to output
2327 * @deprecated since 1.22 Use echo yourself.
2328 */
2329 public function out( $ins ) {
2330 wfDeprecated( __METHOD__, '1.22' );
2331 print $ins;
2332 }
2333
2334 /**
2335 * Produce a "user is blocked" page.
2336 * @deprecated since 1.18
2337 */
2338 function blockedPage() {
2339 throw new UserBlockedError( $this->getUser()->mBlock );
2340 }
2341
2342 /**
2343 * Prepare this object to display an error page; disable caching and
2344 * indexing, clear the current text and redirect, set the page's title
2345 * and optionally an custom HTML title (content of the "<title>" tag).
2346 *
2347 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2348 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2349 * optional, if not passed the "<title>" attribute will be
2350 * based on $pageTitle
2351 */
2352 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2353 $this->setPageTitle( $pageTitle );
2354 if ( $htmlTitle !== false ) {
2355 $this->setHTMLTitle( $htmlTitle );
2356 }
2357 $this->setRobotPolicy( 'noindex,nofollow' );
2358 $this->setArticleRelated( false );
2359 $this->enableClientCache( false );
2360 $this->mRedirect = '';
2361 $this->clearSubtitle();
2362 $this->clearHTML();
2363 }
2364
2365 /**
2366 * Output a standard error page
2367 *
2368 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2369 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2370 * showErrorPage( 'titlemsg', $messageObject );
2371 * showErrorPage( $titleMessageObject, $messageObject );
2372 *
2373 * @param string|Message $title Message key (string) for page title, or a Message object
2374 * @param string|Message $msg Message key (string) for page text, or a Message object
2375 * @param array $params Message parameters; ignored if $msg is a Message object
2376 */
2377 public function showErrorPage( $title, $msg, $params = array() ) {
2378 if ( !$title instanceof Message ) {
2379 $title = $this->msg( $title );
2380 }
2381
2382 $this->prepareErrorPage( $title );
2383
2384 if ( $msg instanceof Message ) {
2385 if ( $params !== array() ) {
2386 trigger_error( 'Argument ignored: $params. The message parameters argument '
2387 . 'is discarded when the $msg argument is a Message object instead of '
2388 . 'a string.', E_USER_NOTICE );
2389 }
2390 $this->addHTML( $msg->parseAsBlock() );
2391 } else {
2392 $this->addWikiMsgArray( $msg, $params );
2393 }
2394
2395 $this->returnToMain();
2396 }
2397
2398 /**
2399 * Output a standard permission error page
2400 *
2401 * @param array $errors Error message keys
2402 * @param string $action Action that was denied or null if unknown
2403 */
2404 public function showPermissionsErrorPage( array $errors, $action = null ) {
2405 // For some action (read, edit, create and upload), display a "login to do this action"
2406 // error if all of the following conditions are met:
2407 // 1. the user is not logged in
2408 // 2. the only error is insufficient permissions (i.e. no block or something else)
2409 // 3. the error can be avoided simply by logging in
2410 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2411 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2412 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2413 && ( User::groupHasPermission( 'user', $action )
2414 || User::groupHasPermission( 'autoconfirmed', $action ) )
2415 ) {
2416 $displayReturnto = null;
2417
2418 # Due to bug 32276, if a user does not have read permissions,
2419 # $this->getTitle() will just give Special:Badtitle, which is
2420 # not especially useful as a returnto parameter. Use the title
2421 # from the request instead, if there was one.
2422 $request = $this->getRequest();
2423 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2424 if ( $action == 'edit' ) {
2425 $msg = 'whitelistedittext';
2426 $displayReturnto = $returnto;
2427 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2428 $msg = 'nocreatetext';
2429 } elseif ( $action == 'upload' ) {
2430 $msg = 'uploadnologintext';
2431 } else { # Read
2432 $msg = 'loginreqpagetext';
2433 $displayReturnto = Title::newMainPage();
2434 }
2435
2436 $query = array();
2437
2438 if ( $returnto ) {
2439 $query['returnto'] = $returnto->getPrefixedText();
2440
2441 if ( !$request->wasPosted() ) {
2442 $returntoquery = $request->getValues();
2443 unset( $returntoquery['title'] );
2444 unset( $returntoquery['returnto'] );
2445 unset( $returntoquery['returntoquery'] );
2446 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2447 }
2448 }
2449 $loginLink = Linker::linkKnown(
2450 SpecialPage::getTitleFor( 'Userlogin' ),
2451 $this->msg( 'loginreqlink' )->escaped(),
2452 array(),
2453 $query
2454 );
2455
2456 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2457 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2458
2459 # Don't return to a page the user can't read otherwise
2460 # we'll end up in a pointless loop
2461 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2462 $this->returnToMain( null, $displayReturnto );
2463 }
2464 } else {
2465 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2466 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2467 }
2468 }
2469
2470 /**
2471 * Display an error page indicating that a given version of MediaWiki is
2472 * required to use it
2473 *
2474 * @param mixed $version The version of MediaWiki needed to use the page
2475 */
2476 public function versionRequired( $version ) {
2477 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2478
2479 $this->addWikiMsg( 'versionrequiredtext', $version );
2480 $this->returnToMain();
2481 }
2482
2483 /**
2484 * Display an error page noting that a given permission bit is required.
2485 * @deprecated since 1.18, just throw the exception directly
2486 * @param string $permission Key required
2487 * @throws PermissionsError
2488 */
2489 public function permissionRequired( $permission ) {
2490 throw new PermissionsError( $permission );
2491 }
2492
2493 /**
2494 * Produce the stock "please login to use the wiki" page
2495 *
2496 * @deprecated since 1.19; throw the exception directly
2497 */
2498 public function loginToUse() {
2499 throw new PermissionsError( 'read' );
2500 }
2501
2502 /**
2503 * Format a list of error messages
2504 *
2505 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2506 * @param string $action Action that was denied or null if unknown
2507 * @return string The wikitext error-messages, formatted into a list.
2508 */
2509 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2510 if ( $action == null ) {
2511 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2512 } else {
2513 $action_desc = $this->msg( "action-$action" )->plain();
2514 $text = $this->msg(
2515 'permissionserrorstext-withaction',
2516 count( $errors ),
2517 $action_desc
2518 )->plain() . "\n\n";
2519 }
2520
2521 if ( count( $errors ) > 1 ) {
2522 $text .= '<ul class="permissions-errors">' . "\n";
2523
2524 foreach ( $errors as $error ) {
2525 $text .= '<li>';
2526 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2527 $text .= "</li>\n";
2528 }
2529 $text .= '</ul>';
2530 } else {
2531 $text .= "<div class=\"permissions-errors\">\n" .
2532 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2533 "\n</div>";
2534 }
2535
2536 return $text;
2537 }
2538
2539 /**
2540 * Display a page stating that the Wiki is in read-only mode.
2541 * Should only be called after wfReadOnly() has returned true.
2542 *
2543 * Historically, this function was used to show the source of the page that the user
2544 * was trying to edit and _also_ permissions error messages. The relevant code was
2545 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2546 *
2547 * @deprecated since 1.25; throw the exception directly
2548 * @throws ReadOnlyError
2549 */
2550 public function readOnlyPage() {
2551 if ( func_num_args() > 0 ) {
2552 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2553 }
2554
2555 throw new ReadOnlyError;
2556 }
2557
2558 /**
2559 * Turn off regular page output and return an error response
2560 * for when rate limiting has triggered.
2561 *
2562 * @deprecated since 1.25; throw the exception directly
2563 */
2564 public function rateLimited() {
2565 wfDeprecated( __METHOD__, '1.25' );
2566 throw new ThrottledError;
2567 }
2568
2569 /**
2570 * Show a warning about slave lag
2571 *
2572 * If the lag is higher than $wgSlaveLagCritical seconds,
2573 * then the warning is a bit more obvious. If the lag is
2574 * lower than $wgSlaveLagWarning, then no warning is shown.
2575 *
2576 * @param int $lag Slave lag
2577 */
2578 public function showLagWarning( $lag ) {
2579 $config = $this->getConfig();
2580 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2581 $message = $lag < $config->get( 'SlaveLagCritical' )
2582 ? 'lag-warn-normal'
2583 : 'lag-warn-high';
2584 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2585 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2586 }
2587 }
2588
2589 public function showFatalError( $message ) {
2590 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2591
2592 $this->addHTML( $message );
2593 }
2594
2595 public function showUnexpectedValueError( $name, $val ) {
2596 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2597 }
2598
2599 public function showFileCopyError( $old, $new ) {
2600 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2601 }
2602
2603 public function showFileRenameError( $old, $new ) {
2604 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2605 }
2606
2607 public function showFileDeleteError( $name ) {
2608 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2609 }
2610
2611 public function showFileNotFoundError( $name ) {
2612 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2613 }
2614
2615 /**
2616 * Add a "return to" link pointing to a specified title
2617 *
2618 * @param Title $title Title to link
2619 * @param array $query Query string parameters
2620 * @param string $text Text of the link (input is not escaped)
2621 * @param array $options Options array to pass to Linker
2622 */
2623 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2624 $link = $this->msg( 'returnto' )->rawParams(
2625 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2626 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2627 }
2628
2629 /**
2630 * Add a "return to" link pointing to a specified title,
2631 * or the title indicated in the request, or else the main page
2632 *
2633 * @param mixed $unused
2634 * @param Title|string $returnto Title or String to return to
2635 * @param string $returntoquery Query string for the return to link
2636 */
2637 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2638 if ( $returnto == null ) {
2639 $returnto = $this->getRequest()->getText( 'returnto' );
2640 }
2641
2642 if ( $returntoquery == null ) {
2643 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2644 }
2645
2646 if ( $returnto === '' ) {
2647 $returnto = Title::newMainPage();
2648 }
2649
2650 if ( is_object( $returnto ) ) {
2651 $titleObj = $returnto;
2652 } else {
2653 $titleObj = Title::newFromText( $returnto );
2654 }
2655 if ( !is_object( $titleObj ) ) {
2656 $titleObj = Title::newMainPage();
2657 }
2658
2659 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2660 }
2661
2662 /**
2663 * @param Skin $sk The given Skin
2664 * @param bool $includeStyle Unused
2665 * @return string The doctype, opening "<html>", and head element.
2666 */
2667 public function headElement( Skin $sk, $includeStyle = true ) {
2668 global $wgContLang;
2669
2670 $userdir = $this->getLanguage()->getDir();
2671 $sitedir = $wgContLang->getDir();
2672
2673 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2674
2675 if ( $this->getHTMLTitle() == '' ) {
2676 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2677 }
2678
2679 $openHead = Html::openElement( 'head' );
2680 if ( $openHead ) {
2681 # Don't bother with the newline if $head == ''
2682 $ret .= "$openHead\n";
2683 }
2684
2685 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2686 // Add <meta charset="UTF-8">
2687 // This should be before <title> since it defines the charset used by
2688 // text including the text inside <title>.
2689 // The spec recommends defining XHTML5's charset using the XML declaration
2690 // instead of meta.
2691 // Our XML declaration is output by Html::htmlHeader.
2692 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2693 // http://www.whatwg.org/html/semantics.html#charset
2694 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2695 }
2696
2697 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2698
2699 foreach ( $this->getHeadLinksArray() as $item ) {
2700 $ret .= $item . "\n";
2701 }
2702
2703 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2704 $ret .= $this->buildCssLinks();
2705
2706 $ret .= $this->getHeadScripts() . "\n";
2707
2708 foreach ( $this->mHeadItems as $item ) {
2709 $ret .= $item . "\n";
2710 }
2711
2712 $closeHead = Html::closeElement( 'head' );
2713 if ( $closeHead ) {
2714 $ret .= "$closeHead\n";
2715 }
2716
2717 $bodyClasses = array();
2718 $bodyClasses[] = 'mediawiki';
2719
2720 # Classes for LTR/RTL directionality support
2721 $bodyClasses[] = $userdir;
2722 $bodyClasses[] = "sitedir-$sitedir";
2723
2724 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2725 # A <body> class is probably not the best way to do this . . .
2726 $bodyClasses[] = 'capitalize-all-nouns';
2727 }
2728
2729 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2730 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2731 $bodyClasses[] =
2732 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2733
2734 $bodyAttrs = array();
2735 // While the implode() is not strictly needed, it's used for backwards compatibility
2736 // (this used to be built as a string and hooks likely still expect that).
2737 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2738
2739 // Allow skins and extensions to add body attributes they need
2740 $sk->addToBodyAttributes( $this, $bodyAttrs );
2741 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2742
2743 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2744
2745 return $ret;
2746 }
2747
2748 /**
2749 * Get a ResourceLoader object associated with this OutputPage
2750 *
2751 * @return ResourceLoader
2752 */
2753 public function getResourceLoader() {
2754 if ( is_null( $this->mResourceLoader ) ) {
2755 $this->mResourceLoader = new ResourceLoader(
2756 $this->getConfig(),
2757 LoggerFactory::getInstance( 'resourceloader' )
2758 );
2759 }
2760 return $this->mResourceLoader;
2761 }
2762
2763 /**
2764 * @todo Document
2765 * @param array|string $modules One or more module names
2766 * @param string $only ResourceLoaderModule TYPE_ class constant
2767 * @param bool $useESI
2768 * @param array $extraQuery Array with extra query parameters to add to each
2769 * request. array( param => value ).
2770 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2771 * call rather than a "<script src='...'>" tag.
2772 * @return string The html "<script>", "<link>" and "<style>" tags
2773 */
2774 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2775 array $extraQuery = array(), $loadCall = false
2776 ) {
2777 $modules = (array)$modules;
2778
2779 $links = array(
2780 'html' => '',
2781 'states' => array(),
2782 );
2783
2784 if ( !count( $modules ) ) {
2785 return $links;
2786 }
2787
2788 if ( count( $modules ) > 1 ) {
2789 // Remove duplicate module requests
2790 $modules = array_unique( $modules );
2791 // Sort module names so requests are more uniform
2792 sort( $modules );
2793
2794 if ( ResourceLoader::inDebugMode() ) {
2795 // Recursively call us for every item
2796 foreach ( $modules as $name ) {
2797 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2798 $links['html'] .= $link['html'];
2799 $links['states'] += $link['states'];
2800 }
2801 return $links;
2802 }
2803 }
2804
2805 if ( !is_null( $this->mTarget ) ) {
2806 $extraQuery['target'] = $this->mTarget;
2807 }
2808
2809 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2810 $sortedModules = array();
2811 $resourceLoader = $this->getResourceLoader();
2812 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2813 foreach ( $modules as $name ) {
2814 $module = $resourceLoader->getModule( $name );
2815 # Check that we're allowed to include this module on this page
2816 if ( !$module
2817 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2818 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2819 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2820 && $only == ResourceLoaderModule::TYPE_STYLES )
2821 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2822 && $only == ResourceLoaderModule::TYPE_COMBINED )
2823 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2824 ) {
2825 continue;
2826 }
2827
2828 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2829 }
2830
2831 foreach ( $sortedModules as $source => $groups ) {
2832 foreach ( $groups as $group => $grpModules ) {
2833 // Special handling for user-specific groups
2834 $user = null;
2835 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2836 $user = $this->getUser()->getName();
2837 }
2838
2839 // Create a fake request based on the one we are about to make so modules return
2840 // correct timestamp and emptiness data
2841 $query = ResourceLoader::makeLoaderQuery(
2842 array(), // modules; not determined yet
2843 $this->getLanguage()->getCode(),
2844 $this->getSkin()->getSkinName(),
2845 $user,
2846 null, // version; not determined yet
2847 ResourceLoader::inDebugMode(),
2848 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2849 $this->isPrintable(),
2850 $this->getRequest()->getBool( 'handheld' ),
2851 $extraQuery
2852 );
2853 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2854
2855 // Extract modules that know they're empty and see if we have one or more
2856 // raw modules
2857 $isRaw = false;
2858 foreach ( $grpModules as $key => $module ) {
2859 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2860 // If we're only getting the styles, we don't need to do anything for empty modules.
2861 if ( $module->isKnownEmpty( $context ) ) {
2862 unset( $grpModules[$key] );
2863 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2864 $links['states'][$key] = 'ready';
2865 }
2866 }
2867
2868 $isRaw |= $module->isRaw();
2869 }
2870
2871 // If there are no non-empty modules, skip this group
2872 if ( count( $grpModules ) === 0 ) {
2873 continue;
2874 }
2875
2876 // Inline private modules. These can't be loaded through load.php for security
2877 // reasons, see bug 34907. Note that these modules should be loaded from
2878 // getHeadScripts() before the first loader call. Otherwise other modules can't
2879 // properly use them as dependencies (bug 30914)
2880 if ( $group === 'private' ) {
2881 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2882 $links['html'] .= Html::inlineStyle(
2883 $resourceLoader->makeModuleResponse( $context, $grpModules )
2884 );
2885 } else {
2886 $links['html'] .= ResourceLoader::makeInlineScript(
2887 $resourceLoader->makeModuleResponse( $context, $grpModules )
2888 );
2889 }
2890 $links['html'] .= "\n";
2891 continue;
2892 }
2893
2894 // Special handling for the user group; because users might change their stuff
2895 // on-wiki like user pages, or user preferences; we need to find the highest
2896 // timestamp of these user-changeable modules so we can ensure cache misses on change
2897 // This should NOT be done for the site group (bug 27564) because anons get that too
2898 // and we shouldn't be putting timestamps in Squid-cached HTML
2899 $version = null;
2900 if ( $group === 'user' ) {
2901 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2902 }
2903
2904 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2905 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2906 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2907
2908 if ( $useESI && $resourceLoaderUseESI ) {
2909 $esi = Xml::element( 'esi:include', array( 'src' => $url ) );
2910 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2911 $link = Html::inlineStyle( $esi );
2912 } else {
2913 $link = Html::inlineScript( $esi );
2914 }
2915 } else {
2916 // Automatically select style/script elements
2917 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2918 $link = Html::linkedStyle( $url );
2919 } elseif ( $loadCall ) {
2920 $link = ResourceLoader::makeInlineScript(
2921 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2922 );
2923 } else {
2924 $link = Html::linkedScript( $url );
2925 if ( !$context->getRaw() && !$isRaw ) {
2926 // Wrap only=script / only=combined requests in a conditional as
2927 // browsers not supported by the startup module would unconditionally
2928 // execute this module. Otherwise users will get "ReferenceError: mw is
2929 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2930 $link = ResourceLoader::makeInlineScript(
2931 Xml::encodeJsCall( 'document.write', array( $link ) )
2932 );
2933 }
2934
2935 // For modules requested directly in the html via <link> or <script>,
2936 // tell mw.loader they are being loading to prevent duplicate requests.
2937 foreach ( $grpModules as $key => $module ) {
2938 // Don't output state=loading for the startup module..
2939 if ( $key !== 'startup' ) {
2940 $links['states'][$key] = 'loading';
2941 }
2942 }
2943 }
2944 }
2945
2946 if ( $group == 'noscript' ) {
2947 $links['html'] .= Html::rawElement( 'noscript', array(), $link ) . "\n";
2948 } else {
2949 $links['html'] .= $link . "\n";
2950 }
2951 }
2952 }
2953
2954 return $links;
2955 }
2956
2957 /**
2958 * Build html output from an array of links from makeResourceLoaderLink.
2959 * @param array $links
2960 * @return string HTML
2961 */
2962 protected static function getHtmlFromLoaderLinks( array $links ) {
2963 $html = '';
2964 $states = array();
2965 foreach ( $links as $link ) {
2966 if ( !is_array( $link ) ) {
2967 $html .= $link;
2968 } else {
2969 $html .= $link['html'];
2970 $states += $link['states'];
2971 }
2972 }
2973
2974 if ( count( $states ) ) {
2975 $html = ResourceLoader::makeInlineScript(
2976 ResourceLoader::makeLoaderStateScript( $states )
2977 ) . "\n" . $html;
2978 }
2979
2980 return $html;
2981 }
2982
2983 /**
2984 * JS stuff to put in the "<head>". This is the startup module, config
2985 * vars and modules marked with position 'top'
2986 *
2987 * @return string HTML fragment
2988 */
2989 function getHeadScripts() {
2990 // Startup - this will immediately load jquery and mediawiki modules
2991 $links = array();
2992 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS, true );
2993
2994 // Load config before anything else
2995 $links[] = ResourceLoader::makeInlineScript(
2996 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2997 );
2998
2999 // Load embeddable private modules before any loader links
3000 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3001 // in mw.loader.implement() calls and deferred until mw.user is available
3002 $embedScripts = array( 'user.options' );
3003 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
3004 // Separate user.tokens as otherwise caching will be allowed (T84960)
3005 $links[] = $this->makeResourceLoaderLink( 'user.tokens', ResourceLoaderModule::TYPE_COMBINED );
3006
3007 // Scripts and messages "only" requests marked for top inclusion
3008 $links[] = $this->makeResourceLoaderLink(
3009 $this->getModuleScripts( true, 'top' ),
3010 ResourceLoaderModule::TYPE_SCRIPTS
3011 );
3012
3013 // Modules requests - let the client calculate dependencies and batch requests as it likes
3014 // Only load modules that have marked themselves for loading at the top
3015 $modules = $this->getModules( true, 'top' );
3016 if ( $modules ) {
3017 $links[] = ResourceLoader::makeInlineScript(
3018 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3019 );
3020 }
3021
3022 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3023 $links[] = $this->getScriptsForBottomQueue( true );
3024 }
3025
3026 return self::getHtmlFromLoaderLinks( $links );
3027 }
3028
3029 /**
3030 * JS stuff to put at the 'bottom', which can either be the bottom of the
3031 * "<body>" or the bottom of the "<head>" depending on
3032 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3033 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3034 * and user JS.
3035 *
3036 * @param bool $inHead If true, this HTML goes into the "<head>",
3037 * if false it goes into the "<body>".
3038 * @return string
3039 */
3040 function getScriptsForBottomQueue( $inHead ) {
3041 // Scripts "only" requests marked for bottom inclusion
3042 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3043 $links = array();
3044
3045 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3046 ResourceLoaderModule::TYPE_SCRIPTS, /* $useESI = */ false, /* $extraQuery = */ array(),
3047 /* $loadCall = */ $inHead
3048 );
3049
3050 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3051 ResourceLoaderModule::TYPE_STYLES, /* $useESI = */ false, /* $extraQuery = */ array(),
3052 /* $loadCall = */ $inHead
3053 );
3054
3055 // Modules requests - let the client calculate dependencies and batch requests as it likes
3056 // Only load modules that have marked themselves for loading at the bottom
3057 $modules = $this->getModules( true, 'bottom' );
3058 if ( $modules ) {
3059 $links[] = ResourceLoader::makeInlineScript(
3060 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3061 );
3062 }
3063
3064 // Legacy Scripts
3065 $links[] = "\n" . $this->mScripts;
3066
3067 // Add site JS if enabled
3068 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule::TYPE_SCRIPTS,
3069 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3070 );
3071
3072 // Add user JS if enabled
3073 if ( $this->getConfig()->get( 'AllowUserJs' )
3074 && $this->getUser()->isLoggedIn()
3075 && $this->getTitle()
3076 && $this->getTitle()->isJsSubpage()
3077 && $this->userCanPreview()
3078 ) {
3079 # XXX: additional security check/prompt?
3080 // We're on a preview of a JS subpage
3081 // Exclude this page from the user module in case it's in there (bug 26283)
3082 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS, false,
3083 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3084 );
3085 // Load the previewed JS
3086 $links[] = Html::inlineScript( "\n"
3087 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3088
3089 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3090 // asynchronously and may arrive *after* the inline script here. So the previewed code
3091 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3092 } else {
3093 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3094 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_SCRIPTS,
3095 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3096 );
3097 }
3098
3099 // Group JS is only enabled if site JS is enabled.
3100 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3101 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3102 );
3103
3104 return self::getHtmlFromLoaderLinks( $links );
3105 }
3106
3107 /**
3108 * JS stuff to put at the bottom of the "<body>"
3109 * @return string
3110 */
3111 function getBottomScripts() {
3112 // In case the skin wants to add bottom CSS
3113 $this->getSkin()->setupSkinUserCss( $this );
3114
3115 // Optimise jQuery ready event cross-browser.
3116 // This also enforces $.isReady to be true at </body> which fixes the
3117 // mw.loader bug in Firefox with using document.write between </body>
3118 // and the DOMContentReady event (bug 47457).
3119 $html = Html::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3120
3121 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3122 $html .= $this->getScriptsForBottomQueue( false );
3123 }
3124
3125 return $html;
3126 }
3127
3128 /**
3129 * Get the javascript config vars to include on this page
3130 *
3131 * @return array Array of javascript config vars
3132 * @since 1.23
3133 */
3134 public function getJsConfigVars() {
3135 return $this->mJsConfigVars;
3136 }
3137
3138 /**
3139 * Add one or more variables to be set in mw.config in JavaScript
3140 *
3141 * @param string|array $keys Key or array of key/value pairs
3142 * @param mixed $value [optional] Value of the configuration variable
3143 */
3144 public function addJsConfigVars( $keys, $value = null ) {
3145 if ( is_array( $keys ) ) {
3146 foreach ( $keys as $key => $value ) {
3147 $this->mJsConfigVars[$key] = $value;
3148 }
3149 return;
3150 }
3151
3152 $this->mJsConfigVars[$keys] = $value;
3153 }
3154
3155 /**
3156 * Get an array containing the variables to be set in mw.config in JavaScript.
3157 *
3158 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3159 * - in other words, page-independent/site-wide variables (without state).
3160 * You will only be adding bloat to the html page and causing page caches to
3161 * have to be purged on configuration changes.
3162 * @return array
3163 */
3164 public function getJSVars() {
3165 global $wgContLang;
3166
3167 $curRevisionId = 0;
3168 $articleId = 0;
3169 $canonicalSpecialPageName = false; # bug 21115
3170
3171 $title = $this->getTitle();
3172 $ns = $title->getNamespace();
3173 $canonicalNamespace = MWNamespace::exists( $ns )
3174 ? MWNamespace::getCanonicalName( $ns )
3175 : $title->getNsText();
3176
3177 $sk = $this->getSkin();
3178 // Get the relevant title so that AJAX features can use the correct page name
3179 // when making API requests from certain special pages (bug 34972).
3180 $relevantTitle = $sk->getRelevantTitle();
3181 $relevantUser = $sk->getRelevantUser();
3182
3183 if ( $ns == NS_SPECIAL ) {
3184 list( $canonicalSpecialPageName, /*...*/ ) =
3185 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3186 } elseif ( $this->canUseWikiPage() ) {
3187 $wikiPage = $this->getWikiPage();
3188 $curRevisionId = $wikiPage->getLatest();
3189 $articleId = $wikiPage->getId();
3190 }
3191
3192 $lang = $title->getPageLanguage();
3193
3194 // Pre-process information
3195 $separatorTransTable = $lang->separatorTransformTable();
3196 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3197 $compactSeparatorTransTable = array(
3198 implode( "\t", array_keys( $separatorTransTable ) ),
3199 implode( "\t", $separatorTransTable ),
3200 );
3201 $digitTransTable = $lang->digitTransformTable();
3202 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3203 $compactDigitTransTable = array(
3204 implode( "\t", array_keys( $digitTransTable ) ),
3205 implode( "\t", $digitTransTable ),
3206 );
3207
3208 $user = $this->getUser();
3209
3210 $vars = array(
3211 'wgCanonicalNamespace' => $canonicalNamespace,
3212 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3213 'wgNamespaceNumber' => $title->getNamespace(),
3214 'wgPageName' => $title->getPrefixedDBkey(),
3215 'wgTitle' => $title->getText(),
3216 'wgCurRevisionId' => $curRevisionId,
3217 'wgRevisionId' => (int)$this->getRevisionId(),
3218 'wgArticleId' => $articleId,
3219 'wgIsArticle' => $this->isArticle(),
3220 'wgIsRedirect' => $title->isRedirect(),
3221 'wgAction' => Action::getActionName( $this->getContext() ),
3222 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3223 'wgUserGroups' => $user->getEffectiveGroups(),
3224 'wgCategories' => $this->getCategories(),
3225 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3226 'wgPageContentLanguage' => $lang->getCode(),
3227 'wgPageContentModel' => $title->getContentModel(),
3228 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3229 'wgDigitTransformTable' => $compactDigitTransTable,
3230 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3231 'wgMonthNames' => $lang->getMonthNamesArray(),
3232 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3233 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3234 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3235 );
3236
3237 if ( $user->isLoggedIn() ) {
3238 $vars['wgUserId'] = $user->getId();
3239 $vars['wgUserEditCount'] = $user->getEditCount();
3240 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3241 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3242 // Get the revision ID of the oldest new message on the user's talk
3243 // page. This can be used for constructing new message alerts on
3244 // the client side.
3245 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3246 }
3247
3248 if ( $wgContLang->hasVariants() ) {
3249 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3250 }
3251 // Same test as SkinTemplate
3252 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3253 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3254
3255 foreach ( $title->getRestrictionTypes() as $type ) {
3256 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3257 }
3258
3259 if ( $title->isMainPage() ) {
3260 $vars['wgIsMainPage'] = true;
3261 }
3262
3263 if ( $this->mRedirectedFrom ) {
3264 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3265 }
3266
3267 if ( $relevantUser ) {
3268 $vars['wgRelevantUserName'] = $relevantUser->getName();
3269 }
3270
3271 // Allow extensions to add their custom variables to the mw.config map.
3272 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3273 // page-dependant but site-wide (without state).
3274 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3275 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3276
3277 // Merge in variables from addJsConfigVars last
3278 return array_merge( $vars, $this->getJsConfigVars() );
3279 }
3280
3281 /**
3282 * To make it harder for someone to slip a user a fake
3283 * user-JavaScript or user-CSS preview, a random token
3284 * is associated with the login session. If it's not
3285 * passed back with the preview request, we won't render
3286 * the code.
3287 *
3288 * @return bool
3289 */
3290 public function userCanPreview() {
3291 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3292 || !$this->getRequest()->wasPosted()
3293 || !$this->getUser()->matchEditToken(
3294 $this->getRequest()->getVal( 'wpEditToken' ) )
3295 ) {
3296 return false;
3297 }
3298 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3299 return false;
3300 }
3301 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3302 // Don't execute another user's CSS or JS on preview (T85855)
3303 return false;
3304 }
3305
3306 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3307 }
3308
3309 /**
3310 * @return array Array in format "link name or number => 'link html'".
3311 */
3312 public function getHeadLinksArray() {
3313 global $wgVersion;
3314
3315 $tags = array();
3316 $config = $this->getConfig();
3317
3318 $canonicalUrl = $this->mCanonicalUrl;
3319
3320 $tags['meta-generator'] = Html::element( 'meta', array(
3321 'name' => 'generator',
3322 'content' => "MediaWiki $wgVersion",
3323 ) );
3324
3325 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3326 $tags['meta-referrer'] = Html::element( 'meta', array(
3327 'name' => 'referrer',
3328 'content' => $config->get( 'ReferrerPolicy' )
3329 ) );
3330 }
3331
3332 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3333 if ( $p !== 'index,follow' ) {
3334 // http://www.robotstxt.org/wc/meta-user.html
3335 // Only show if it's different from the default robots policy
3336 $tags['meta-robots'] = Html::element( 'meta', array(
3337 'name' => 'robots',
3338 'content' => $p,
3339 ) );
3340 }
3341
3342 foreach ( $this->mMetatags as $tag ) {
3343 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3344 $a = 'http-equiv';
3345 $tag[0] = substr( $tag[0], 5 );
3346 } else {
3347 $a = 'name';
3348 }
3349 $tagName = "meta-{$tag[0]}";
3350 if ( isset( $tags[$tagName] ) ) {
3351 $tagName .= $tag[1];
3352 }
3353 $tags[$tagName] = Html::element( 'meta',
3354 array(
3355 $a => $tag[0],
3356 'content' => $tag[1]
3357 )
3358 );
3359 }
3360
3361 foreach ( $this->mLinktags as $tag ) {
3362 $tags[] = Html::element( 'link', $tag );
3363 }
3364
3365 # Universal edit button
3366 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3367 $user = $this->getUser();
3368 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3369 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3370 // Original UniversalEditButton
3371 $msg = $this->msg( 'edit' )->text();
3372 $tags['universal-edit-button'] = Html::element( 'link', array(
3373 'rel' => 'alternate',
3374 'type' => 'application/x-wiki',
3375 'title' => $msg,
3376 'href' => $this->getTitle()->getEditURL(),
3377 ) );
3378 // Alternate edit link
3379 $tags['alternative-edit'] = Html::element( 'link', array(
3380 'rel' => 'edit',
3381 'title' => $msg,
3382 'href' => $this->getTitle()->getEditURL(),
3383 ) );
3384 }
3385 }
3386
3387 # Generally the order of the favicon and apple-touch-icon links
3388 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3389 # uses whichever one appears later in the HTML source. Make sure
3390 # apple-touch-icon is specified first to avoid this.
3391 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3392 $tags['apple-touch-icon'] = Html::element( 'link', array(
3393 'rel' => 'apple-touch-icon',
3394 'href' => $config->get( 'AppleTouchIcon' )
3395 ) );
3396 }
3397
3398 if ( $config->get( 'Favicon' ) !== false ) {
3399 $tags['favicon'] = Html::element( 'link', array(
3400 'rel' => 'shortcut icon',
3401 'href' => $config->get( 'Favicon' )
3402 ) );
3403 }
3404
3405 # OpenSearch description link
3406 $tags['opensearch'] = Html::element( 'link', array(
3407 'rel' => 'search',
3408 'type' => 'application/opensearchdescription+xml',
3409 'href' => wfScript( 'opensearch_desc' ),
3410 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3411 ) );
3412
3413 if ( $config->get( 'EnableAPI' ) ) {
3414 # Real Simple Discovery link, provides auto-discovery information
3415 # for the MediaWiki API (and potentially additional custom API
3416 # support such as WordPress or Twitter-compatible APIs for a
3417 # blogging extension, etc)
3418 $tags['rsd'] = Html::element( 'link', array(
3419 'rel' => 'EditURI',
3420 'type' => 'application/rsd+xml',
3421 // Output a protocol-relative URL here if $wgServer is protocol-relative
3422 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3423 'href' => wfExpandUrl( wfAppendQuery(
3424 wfScript( 'api' ),
3425 array( 'action' => 'rsd' ) ),
3426 PROTO_RELATIVE
3427 ),
3428 ) );
3429 }
3430
3431 # Language variants
3432 if ( !$config->get( 'DisableLangConversion' ) ) {
3433 $lang = $this->getTitle()->getPageLanguage();
3434 if ( $lang->hasVariants() ) {
3435 $variants = $lang->getVariants();
3436 foreach ( $variants as $_v ) {
3437 $tags["variant-$_v"] = Html::element( 'link', array(
3438 'rel' => 'alternate',
3439 'hreflang' => wfBCP47( $_v ),
3440 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3441 );
3442 }
3443 }
3444 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3445 $tags["variant-x-default"] = Html::element( 'link', array(
3446 'rel' => 'alternate',
3447 'hreflang' => 'x-default',
3448 'href' => $this->getTitle()->getLocalURL() ) );
3449 }
3450
3451 # Copyright
3452 if ( $this->copyrightUrl !== null ) {
3453 $copyright = $this->copyrightUrl;
3454 } else {
3455 $copyright = '';
3456 if ( $config->get( 'RightsPage' ) ) {
3457 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3458
3459 if ( $copy ) {
3460 $copyright = $copy->getLocalURL();
3461 }
3462 }
3463
3464 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3465 $copyright = $config->get( 'RightsUrl' );
3466 }
3467 }
3468
3469 if ( $copyright ) {
3470 $tags['copyright'] = Html::element( 'link', array(
3471 'rel' => 'copyright',
3472 'href' => $copyright )
3473 );
3474 }
3475
3476 # Feeds
3477 if ( $config->get( 'Feed' ) ) {
3478 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3479 # Use the page name for the title. In principle, this could
3480 # lead to issues with having the same name for different feeds
3481 # corresponding to the same page, but we can't avoid that at
3482 # this low a level.
3483
3484 $tags[] = $this->feedLink(
3485 $format,
3486 $link,
3487 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3488 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3489 );
3490 }
3491
3492 # Recent changes feed should appear on every page (except recentchanges,
3493 # that would be redundant). Put it after the per-page feed to avoid
3494 # changing existing behavior. It's still available, probably via a
3495 # menu in your browser. Some sites might have a different feed they'd
3496 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3497 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3498 # If so, use it instead.
3499 $sitename = $config->get( 'Sitename' );
3500 if ( $config->get( 'OverrideSiteFeed' ) ) {
3501 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3502 // Note, this->feedLink escapes the url.
3503 $tags[] = $this->feedLink(
3504 $type,
3505 $feedUrl,
3506 $this->msg( "site-{$type}-feed", $sitename )->text()
3507 );
3508 }
3509 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3510 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3511 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3512 $tags[] = $this->feedLink(
3513 $format,
3514 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3515 # For grep: 'site-rss-feed', 'site-atom-feed'
3516 $this->msg( "site-{$format}-feed", $sitename )->text()
3517 );
3518 }
3519 }
3520 }
3521
3522 # Canonical URL
3523 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3524 if ( $canonicalUrl !== false ) {
3525 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3526 } else {
3527 if ( $this->isArticleRelated() ) {
3528 // This affects all requests where "setArticleRelated" is true. This is
3529 // typically all requests that show content (query title, curid, oldid, diff),
3530 // and all wikipage actions (edit, delete, purge, info, history etc.).
3531 // It does not apply to File pages and Special pages.
3532 // 'history' and 'info' actions address page metadata rather than the page
3533 // content itself, so they may not be canonicalized to the view page url.
3534 // TODO: this ought to be better encapsulated in the Action class.
3535 $action = Action::getActionName( $this->getContext() );
3536 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3537 $query = "action={$action}";
3538 } else {
3539 $query = '';
3540 }
3541 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3542 } else {
3543 $reqUrl = $this->getRequest()->getRequestURL();
3544 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3545 }
3546 }
3547 }
3548 if ( $canonicalUrl !== false ) {
3549 $tags[] = Html::element( 'link', array(
3550 'rel' => 'canonical',
3551 'href' => $canonicalUrl
3552 ) );
3553 }
3554
3555 return $tags;
3556 }
3557
3558 /**
3559 * @return string HTML tag links to be put in the header.
3560 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3561 * OutputPage::getHeadLinksArray directly.
3562 */
3563 public function getHeadLinks() {
3564 wfDeprecated( __METHOD__, '1.24' );
3565 return implode( "\n", $this->getHeadLinksArray() );
3566 }
3567
3568 /**
3569 * Generate a "<link rel/>" for a feed.
3570 *
3571 * @param string $type Feed type
3572 * @param string $url URL to the feed
3573 * @param string $text Value of the "title" attribute
3574 * @return string HTML fragment
3575 */
3576 private function feedLink( $type, $url, $text ) {
3577 return Html::element( 'link', array(
3578 'rel' => 'alternate',
3579 'type' => "application/$type+xml",
3580 'title' => $text,
3581 'href' => $url )
3582 );
3583 }
3584
3585 /**
3586 * Add a local or specified stylesheet, with the given media options.
3587 * Meant primarily for internal use...
3588 *
3589 * @param string $style URL to the file
3590 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3591 * @param string $condition For IE conditional comments, specifying an IE version
3592 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3593 */
3594 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3595 $options = array();
3596 // Even though we expect the media type to be lowercase, but here we
3597 // force it to lowercase to be safe.
3598 if ( $media ) {
3599 $options['media'] = $media;
3600 }
3601 if ( $condition ) {
3602 $options['condition'] = $condition;
3603 }
3604 if ( $dir ) {
3605 $options['dir'] = $dir;
3606 }
3607 $this->styles[$style] = $options;
3608 }
3609
3610 /**
3611 * Adds inline CSS styles
3612 * @param mixed $style_css Inline CSS
3613 * @param string $flip Set to 'flip' to flip the CSS if needed
3614 */
3615 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3616 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3617 # If wanted, and the interface is right-to-left, flip the CSS
3618 $style_css = CSSJanus::transform( $style_css, true, false );
3619 }
3620 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3621 }
3622
3623 /**
3624 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3625 * These will be applied to various media & IE conditionals.
3626 *
3627 * @return string
3628 */
3629 public function buildCssLinks() {
3630 global $wgContLang;
3631
3632 $this->getSkin()->setupSkinUserCss( $this );
3633
3634 // Add ResourceLoader styles
3635 // Split the styles into these groups
3636 $styles = array(
3637 'other' => array(),
3638 'user' => array(),
3639 'site' => array(),
3640 'private' => array(),
3641 'noscript' => array()
3642 );
3643 $links = array();
3644 $otherTags = ''; // Tags to append after the normal <link> tags
3645 $resourceLoader = $this->getResourceLoader();
3646
3647 $moduleStyles = $this->getModuleStyles( true, 'top' );
3648
3649 // Per-site custom styles
3650 $moduleStyles[] = 'site';
3651 $moduleStyles[] = 'noscript';
3652 $moduleStyles[] = 'user.groups';
3653
3654 // Per-user custom styles
3655 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3656 && $this->userCanPreview()
3657 ) {
3658 // We're on a preview of a CSS subpage
3659 // Exclude this page from the user module in case it's in there (bug 26283)
3660 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES, false,
3661 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3662 );
3663 $otherTags .= $link['html'];
3664
3665 // Load the previewed CSS
3666 // If needed, Janus it first. This is user-supplied CSS, so it's
3667 // assumed to be right for the content language directionality.
3668 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3669 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3670 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3671 }
3672 $otherTags .= Html::inlineStyle( $previewedCSS ) . "\n";
3673 } else {
3674 // Load the user styles normally
3675 $moduleStyles[] = 'user';
3676 }
3677
3678 // Per-user preference styles
3679 $moduleStyles[] = 'user.cssprefs';
3680
3681 foreach ( $moduleStyles as $name ) {
3682 $module = $resourceLoader->getModule( $name );
3683 if ( !$module ) {
3684 continue;
3685 }
3686 $group = $module->getGroup();
3687 // Modules in groups different than the ones listed on top (see $styles assignment)
3688 // will be placed in the "other" group
3689 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3690 }
3691
3692 // We want site, private and user styles to override dynamically added
3693 // styles from modules, but we want dynamically added styles to override
3694 // statically added styles from other modules. So the order has to be
3695 // other, dynamic, site, private, user. Add statically added styles for
3696 // other modules
3697 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3698 // Add normal styles added through addStyle()/addInlineStyle() here
3699 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3700 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3701 // We use a <meta> tag with a made-up name for this because that's valid HTML
3702 $links[] = Html::element(
3703 'meta',
3704 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3705 ) . "\n";
3706
3707 // Add site, private and user styles
3708 // 'private' at present only contains user.options, so put that before 'user'
3709 // Any future private modules will likely have a similar user-specific character
3710 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3711 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3712 ResourceLoaderModule::TYPE_STYLES
3713 );
3714 }
3715
3716 // Add stuff in $otherTags (previewed user CSS if applicable)
3717 return self::getHtmlFromLoaderLinks( $links ) . $otherTags;
3718 }
3719
3720 /**
3721 * @return array
3722 */
3723 public function buildCssLinksArray() {
3724 $links = array();
3725
3726 // Add any extension CSS
3727 foreach ( $this->mExtStyles as $url ) {
3728 $this->addStyle( $url );
3729 }
3730 $this->mExtStyles = array();
3731
3732 foreach ( $this->styles as $file => $options ) {
3733 $link = $this->styleLink( $file, $options );
3734 if ( $link ) {
3735 $links[$file] = $link;
3736 }
3737 }
3738 return $links;
3739 }
3740
3741 /**
3742 * Generate \<link\> tags for stylesheets
3743 *
3744 * @param string $style URL to the file
3745 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3746 * @return string HTML fragment
3747 */
3748 protected function styleLink( $style, array $options ) {
3749 if ( isset( $options['dir'] ) ) {
3750 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3751 return '';
3752 }
3753 }
3754
3755 if ( isset( $options['media'] ) ) {
3756 $media = self::transformCssMedia( $options['media'] );
3757 if ( is_null( $media ) ) {
3758 return '';
3759 }
3760 } else {
3761 $media = 'all';
3762 }
3763
3764 if ( substr( $style, 0, 1 ) == '/' ||
3765 substr( $style, 0, 5 ) == 'http:' ||
3766 substr( $style, 0, 6 ) == 'https:' ) {
3767 $url = $style;
3768 } else {
3769 $config = $this->getConfig();
3770 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3771 }
3772
3773 $link = Html::linkedStyle( $url, $media );
3774
3775 if ( isset( $options['condition'] ) ) {
3776 $condition = htmlspecialchars( $options['condition'] );
3777 $link = "<!--[if $condition]>$link<![endif]-->";
3778 }
3779 return $link;
3780 }
3781
3782 /**
3783 * Transform "media" attribute based on request parameters
3784 *
3785 * @param string $media Current value of the "media" attribute
3786 * @return string Modified value of the "media" attribute, or null to skip
3787 * this stylesheet
3788 */
3789 public static function transformCssMedia( $media ) {
3790 global $wgRequest;
3791
3792 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3793 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3794
3795 // Switch in on-screen display for media testing
3796 $switches = array(
3797 'printable' => 'print',
3798 'handheld' => 'handheld',
3799 );
3800 foreach ( $switches as $switch => $targetMedia ) {
3801 if ( $wgRequest->getBool( $switch ) ) {
3802 if ( $media == $targetMedia ) {
3803 $media = '';
3804 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3805 // This regex will not attempt to understand a comma-separated media_query_list
3806 //
3807 // Example supported values for $media:
3808 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3809 // Example NOT supported value for $media:
3810 // '3d-glasses, screen, print and resolution > 90dpi'
3811 //
3812 // If it's a print request, we never want any kind of screen stylesheets
3813 // If it's a handheld request (currently the only other choice with a switch),
3814 // we don't want simple 'screen' but we might want screen queries that
3815 // have a max-width or something, so we'll pass all others on and let the
3816 // client do the query.
3817 if ( $targetMedia == 'print' || $media == 'screen' ) {
3818 return null;
3819 }
3820 }
3821 }
3822 }
3823
3824 return $media;
3825 }
3826
3827 /**
3828 * Add a wikitext-formatted message to the output.
3829 * This is equivalent to:
3830 *
3831 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3832 */
3833 public function addWikiMsg( /*...*/ ) {
3834 $args = func_get_args();
3835 $name = array_shift( $args );
3836 $this->addWikiMsgArray( $name, $args );
3837 }
3838
3839 /**
3840 * Add a wikitext-formatted message to the output.
3841 * Like addWikiMsg() except the parameters are taken as an array
3842 * instead of a variable argument list.
3843 *
3844 * @param string $name
3845 * @param array $args
3846 */
3847 public function addWikiMsgArray( $name, $args ) {
3848 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3849 }
3850
3851 /**
3852 * This function takes a number of message/argument specifications, wraps them in
3853 * some overall structure, and then parses the result and adds it to the output.
3854 *
3855 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3856 * and so on. The subsequent arguments may be either
3857 * 1) strings, in which case they are message names, or
3858 * 2) arrays, in which case, within each array, the first element is the message
3859 * name, and subsequent elements are the parameters to that message.
3860 *
3861 * Don't use this for messages that are not in the user's interface language.
3862 *
3863 * For example:
3864 *
3865 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3866 *
3867 * Is equivalent to:
3868 *
3869 * $wgOut->addWikiText( "<div class='error'>\n"
3870 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3871 *
3872 * The newline after the opening div is needed in some wikitext. See bug 19226.
3873 *
3874 * @param string $wrap
3875 */
3876 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3877 $msgSpecs = func_get_args();
3878 array_shift( $msgSpecs );
3879 $msgSpecs = array_values( $msgSpecs );
3880 $s = $wrap;
3881 foreach ( $msgSpecs as $n => $spec ) {
3882 if ( is_array( $spec ) ) {
3883 $args = $spec;
3884 $name = array_shift( $args );
3885 if ( isset( $args['options'] ) ) {
3886 unset( $args['options'] );
3887 wfDeprecated(
3888 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3889 '1.20'
3890 );
3891 }
3892 } else {
3893 $args = array();
3894 $name = $spec;
3895 }
3896 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3897 }
3898 $this->addWikiText( $s );
3899 }
3900
3901 /**
3902 * Include jQuery core. Use this to avoid loading it multiple times
3903 * before we get a usable script loader.
3904 *
3905 * @param array $modules List of jQuery modules which should be loaded
3906 * @return array The list of modules which were not loaded.
3907 * @since 1.16
3908 * @deprecated since 1.17
3909 */
3910 public function includeJQuery( array $modules = array() ) {
3911 return array();
3912 }
3913
3914 /**
3915 * Enables/disables TOC, doesn't override __NOTOC__
3916 * @param bool $flag
3917 * @since 1.22
3918 */
3919 public function enableTOC( $flag = true ) {
3920 $this->mEnableTOC = $flag;
3921 }
3922
3923 /**
3924 * @return bool
3925 * @since 1.22
3926 */
3927 public function isTOCEnabled() {
3928 return $this->mEnableTOC;
3929 }
3930
3931 /**
3932 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3933 * @param bool $flag
3934 * @since 1.23
3935 */
3936 public function enableSectionEditLinks( $flag = true ) {
3937 $this->mEnableSectionEditLinks = $flag;
3938 }
3939
3940 /**
3941 * @return bool
3942 * @since 1.23
3943 */
3944 public function sectionEditLinksEnabled() {
3945 return $this->mEnableSectionEditLinks;
3946 }
3947
3948 /**
3949 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3950 * MediaWiki and this OutputPage instance.
3951 *
3952 * @since 1.25
3953 */
3954 public function enableOOUI() {
3955 OOUI\Theme::setSingleton( new OOUI\MediaWikiTheme() );
3956 OOUI\Element::setDefaultDir( $this->getLanguage()->getDir() );
3957 $this->addModuleStyles( array(
3958 'oojs-ui.styles',
3959 'oojs-ui.styles.icons',
3960 'oojs-ui.styles.indicators',
3961 'oojs-ui.styles.textures',
3962 ) );
3963 }
3964 }