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