Merge "OutputPage: Add \n between </style> and <script>"
[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 // Link flags are ignored for now, but may in the future be
1822 // used to mark individual language links.
1823 $linkFlags = array();
1824 Hooks::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ) );
1825 Hooks::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1826 }
1827
1828 /**
1829 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1830 * ParserOutput object, without any other metadata.
1831 *
1832 * @since 1.24
1833 * @param ParserOutput $parserOutput
1834 */
1835 public function addParserOutputContent( $parserOutput ) {
1836 $this->addParserOutputText( $parserOutput );
1837
1838 $this->addModules( $parserOutput->getModules() );
1839 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1840 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1841
1842 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1843 }
1844
1845 /**
1846 * Add the HTML associated with a ParserOutput object, without any metadata.
1847 *
1848 * @since 1.24
1849 * @param ParserOutput $parserOutput
1850 */
1851 public function addParserOutputText( $parserOutput ) {
1852 $text = $parserOutput->getText();
1853 Hooks::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1854 $this->addHTML( $text );
1855 }
1856
1857 /**
1858 * Add everything from a ParserOutput object.
1859 *
1860 * @param ParserOutput $parserOutput
1861 */
1862 function addParserOutput( $parserOutput ) {
1863 $this->addParserOutputMetadata( $parserOutput );
1864 $parserOutput->setTOCEnabled( $this->mEnableTOC );
1865
1866 // Touch section edit links only if not previously disabled
1867 if ( $parserOutput->getEditSectionTokens() ) {
1868 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1869 }
1870
1871 $this->addParserOutputText( $parserOutput );
1872 }
1873
1874 /**
1875 * Add the output of a QuickTemplate to the output buffer
1876 *
1877 * @param QuickTemplate $template
1878 */
1879 public function addTemplate( &$template ) {
1880 $this->addHTML( $template->getHTML() );
1881 }
1882
1883 /**
1884 * Parse wikitext and return the HTML.
1885 *
1886 * @param string $text
1887 * @param bool $linestart Is this the start of a line?
1888 * @param bool $interface Use interface language ($wgLang instead of
1889 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1890 * This also disables LanguageConverter.
1891 * @param Language $language Target language object, will override $interface
1892 * @throws MWException
1893 * @return string HTML
1894 */
1895 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1896 global $wgParser;
1897
1898 if ( is_null( $this->getTitle() ) ) {
1899 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1900 }
1901
1902 $popts = $this->parserOptions();
1903 if ( $interface ) {
1904 $popts->setInterfaceMessage( true );
1905 }
1906 if ( $language !== null ) {
1907 $oldLang = $popts->setTargetLanguage( $language );
1908 }
1909
1910 $parserOutput = $wgParser->getFreshParser()->parse(
1911 $text, $this->getTitle(), $popts,
1912 $linestart, true, $this->mRevisionId
1913 );
1914
1915 if ( $interface ) {
1916 $popts->setInterfaceMessage( false );
1917 }
1918 if ( $language !== null ) {
1919 $popts->setTargetLanguage( $oldLang );
1920 }
1921
1922 return $parserOutput->getText();
1923 }
1924
1925 /**
1926 * Parse wikitext, strip paragraphs, and return the HTML.
1927 *
1928 * @param string $text
1929 * @param bool $linestart Is this the start of a line?
1930 * @param bool $interface Use interface language ($wgLang instead of
1931 * $wgContLang) while parsing language sensitive magic
1932 * words like GRAMMAR and PLURAL
1933 * @return string HTML
1934 */
1935 public function parseInline( $text, $linestart = true, $interface = false ) {
1936 $parsed = $this->parse( $text, $linestart, $interface );
1937 return Parser::stripOuterParagraph( $parsed );
1938 }
1939
1940 /**
1941 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1942 *
1943 * @param int $maxage Maximum cache time on the Squid, in seconds.
1944 */
1945 public function setSquidMaxage( $maxage ) {
1946 $this->mSquidMaxage = $maxage;
1947 }
1948
1949 /**
1950 * Use enableClientCache(false) to force it to send nocache headers
1951 *
1952 * @param bool $state
1953 *
1954 * @return bool
1955 */
1956 public function enableClientCache( $state ) {
1957 return wfSetVar( $this->mEnableClientCache, $state );
1958 }
1959
1960 /**
1961 * Get the list of cookies that will influence on the cache
1962 *
1963 * @return array
1964 */
1965 function getCacheVaryCookies() {
1966 static $cookies;
1967 if ( $cookies === null ) {
1968 $config = $this->getConfig();
1969 $cookies = array_merge(
1970 array(
1971 $config->get( 'CookiePrefix' ) . 'Token',
1972 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1973 "forceHTTPS",
1974 session_name()
1975 ),
1976 $config->get( 'CacheVaryCookies' )
1977 );
1978 Hooks::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1979 }
1980 return $cookies;
1981 }
1982
1983 /**
1984 * Check if the request has a cache-varying cookie header
1985 * If it does, it's very important that we don't allow public caching
1986 *
1987 * @return bool
1988 */
1989 function haveCacheVaryCookies() {
1990 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1991 if ( $cookieHeader === false ) {
1992 return false;
1993 }
1994 $cvCookies = $this->getCacheVaryCookies();
1995 foreach ( $cvCookies as $cookieName ) {
1996 # Check for a simple string match, like the way squid does it
1997 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1998 wfDebug( __METHOD__ . ": found $cookieName\n" );
1999 return true;
2000 }
2001 }
2002 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2003 return false;
2004 }
2005
2006 /**
2007 * Add an HTTP header that will influence on the cache
2008 *
2009 * @param string $header Header name
2010 * @param array|null $option
2011 * @todo FIXME: Document the $option parameter; it appears to be for
2012 * X-Vary-Options but what format is acceptable?
2013 */
2014 public function addVaryHeader( $header, $option = null ) {
2015 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2016 $this->mVaryHeader[$header] = (array)$option;
2017 } elseif ( is_array( $option ) ) {
2018 if ( is_array( $this->mVaryHeader[$header] ) ) {
2019 $this->mVaryHeader[$header] = array_merge( $this->mVaryHeader[$header], $option );
2020 } else {
2021 $this->mVaryHeader[$header] = $option;
2022 }
2023 }
2024 $this->mVaryHeader[$header] = array_unique( (array)$this->mVaryHeader[$header] );
2025 }
2026
2027 /**
2028 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2029 * such as Accept-Encoding or Cookie
2030 *
2031 * @return string
2032 */
2033 public function getVaryHeader() {
2034 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader ) );
2035 }
2036
2037 /**
2038 * Get a complete X-Vary-Options header
2039 *
2040 * @return string
2041 */
2042 public function getXVO() {
2043 $cvCookies = $this->getCacheVaryCookies();
2044
2045 $cookiesOption = array();
2046 foreach ( $cvCookies as $cookieName ) {
2047 $cookiesOption[] = 'string-contains=' . $cookieName;
2048 }
2049 $this->addVaryHeader( 'Cookie', $cookiesOption );
2050
2051 $headers = array();
2052 foreach ( $this->mVaryHeader as $header => $option ) {
2053 $newheader = $header;
2054 if ( is_array( $option ) && count( $option ) > 0 ) {
2055 $newheader .= ';' . implode( ';', $option );
2056 }
2057 $headers[] = $newheader;
2058 }
2059 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2060
2061 return $xvo;
2062 }
2063
2064 /**
2065 * bug 21672: Add Accept-Language to Vary and XVO headers
2066 * if there's no 'variant' parameter existed in GET.
2067 *
2068 * For example:
2069 * /w/index.php?title=Main_page should always be served; but
2070 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2071 */
2072 function addAcceptLanguage() {
2073 $title = $this->getTitle();
2074 if ( !$title instanceof Title ) {
2075 return;
2076 }
2077
2078 $lang = $title->getPageLanguage();
2079 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2080 $variants = $lang->getVariants();
2081 $aloption = array();
2082 foreach ( $variants as $variant ) {
2083 if ( $variant === $lang->getCode() ) {
2084 continue;
2085 } else {
2086 $aloption[] = 'string-contains=' . $variant;
2087
2088 // IE and some other browsers use BCP 47 standards in
2089 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2090 // We should handle these too.
2091 $variantBCP47 = wfBCP47( $variant );
2092 if ( $variantBCP47 !== $variant ) {
2093 $aloption[] = 'string-contains=' . $variantBCP47;
2094 }
2095 }
2096 }
2097 $this->addVaryHeader( 'Accept-Language', $aloption );
2098 }
2099 }
2100
2101 /**
2102 * Set a flag which will cause an X-Frame-Options header appropriate for
2103 * edit pages to be sent. The header value is controlled by
2104 * $wgEditPageFrameOptions.
2105 *
2106 * This is the default for special pages. If you display a CSRF-protected
2107 * form on an ordinary view page, then you need to call this function.
2108 *
2109 * @param bool $enable
2110 */
2111 public function preventClickjacking( $enable = true ) {
2112 $this->mPreventClickjacking = $enable;
2113 }
2114
2115 /**
2116 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2117 * This can be called from pages which do not contain any CSRF-protected
2118 * HTML form.
2119 */
2120 public function allowClickjacking() {
2121 $this->mPreventClickjacking = false;
2122 }
2123
2124 /**
2125 * Get the prevent-clickjacking flag
2126 *
2127 * @since 1.24
2128 * @return bool
2129 */
2130 public function getPreventClickjacking() {
2131 return $this->mPreventClickjacking;
2132 }
2133
2134 /**
2135 * Get the X-Frame-Options header value (without the name part), or false
2136 * if there isn't one. This is used by Skin to determine whether to enable
2137 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2138 *
2139 * @return string
2140 */
2141 public function getFrameOptions() {
2142 $config = $this->getConfig();
2143 if ( $config->get( 'BreakFrames' ) ) {
2144 return 'DENY';
2145 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2146 return $config->get( 'EditPageFrameOptions' );
2147 }
2148 return false;
2149 }
2150
2151 /**
2152 * Send cache control HTTP headers
2153 */
2154 public function sendCacheControl() {
2155 $response = $this->getRequest()->response();
2156 $config = $this->getConfig();
2157 if ( $config->get( 'UseETag' ) && $this->mETag ) {
2158 $response->header( "ETag: $this->mETag" );
2159 }
2160
2161 $this->addVaryHeader( 'Cookie' );
2162 $this->addAcceptLanguage();
2163
2164 # don't serve compressed data to clients who can't handle it
2165 # maintain different caches for logged-in users and non-logged in ones
2166 $response->header( $this->getVaryHeader() );
2167
2168 if ( $config->get( 'UseXVO' ) ) {
2169 # Add an X-Vary-Options header for Squid with Wikimedia patches
2170 $response->header( $this->getXVO() );
2171 }
2172
2173 if ( $this->mEnableClientCache ) {
2174 if (
2175 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2176 $this->mSquidMaxage != 0 && !$this->haveCacheVaryCookies()
2177 ) {
2178 if ( $config->get( 'UseESI' ) ) {
2179 # We'll purge the proxy cache explicitly, but require end user agents
2180 # to revalidate against the proxy on each visit.
2181 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2182 wfDebug( __METHOD__ . ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2183 # start with a shorter timeout for initial testing
2184 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2185 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2186 . '+' . $this->mSquidMaxage . ', content="ESI/1.0"' );
2187 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2188 } else {
2189 # We'll purge the proxy cache for anons explicitly, but require end user agents
2190 # to revalidate against the proxy on each visit.
2191 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2192 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2193 wfDebug( __METHOD__ . ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2194 # start with a shorter timeout for initial testing
2195 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2196 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2197 . ', must-revalidate, max-age=0' );
2198 }
2199 } else {
2200 # We do want clients to cache if they can, but they *must* check for updates
2201 # on revisiting the page.
2202 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **\n", 'log' );
2203 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2204 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2205 }
2206 if ( $this->mLastModified ) {
2207 $response->header( "Last-Modified: {$this->mLastModified}" );
2208 }
2209 } else {
2210 wfDebug( __METHOD__ . ": no caching **\n", 'log' );
2211
2212 # In general, the absence of a last modified header should be enough to prevent
2213 # the client from using its cache. We send a few other things just to make sure.
2214 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2215 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2216 $response->header( 'Pragma: no-cache' );
2217 }
2218 }
2219
2220 /**
2221 * Finally, all the text has been munged and accumulated into
2222 * the object, let's actually output it:
2223 */
2224 public function output() {
2225 if ( $this->mDoNothing ) {
2226 return;
2227 }
2228
2229 $response = $this->getRequest()->response();
2230 $config = $this->getConfig();
2231
2232 if ( $this->mRedirect != '' ) {
2233 # Standards require redirect URLs to be absolute
2234 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2235
2236 $redirect = $this->mRedirect;
2237 $code = $this->mRedirectCode;
2238
2239 if ( Hooks::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2240 if ( $code == '301' || $code == '303' ) {
2241 if ( !$config->get( 'DebugRedirects' ) ) {
2242 $response->statusHeader( $code );
2243 }
2244 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2245 }
2246 if ( $config->get( 'VaryOnXFP' ) ) {
2247 $this->addVaryHeader( 'X-Forwarded-Proto' );
2248 }
2249 $this->sendCacheControl();
2250
2251 $response->header( "Content-Type: text/html; charset=utf-8" );
2252 if ( $config->get( 'DebugRedirects' ) ) {
2253 $url = htmlspecialchars( $redirect );
2254 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2255 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2256 print "</body>\n</html>\n";
2257 } else {
2258 $response->header( 'Location: ' . $redirect );
2259 }
2260 }
2261
2262 return;
2263 } elseif ( $this->mStatusCode ) {
2264 $response->statusHeader( $this->mStatusCode );
2265 }
2266
2267 # Buffer output; final headers may depend on later processing
2268 ob_start();
2269
2270 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2271 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2272
2273 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2274 // jQuery etc. can work correctly.
2275 $response->header( 'X-UA-Compatible: IE=Edge' );
2276
2277 // Prevent framing, if requested
2278 $frameOptions = $this->getFrameOptions();
2279 if ( $frameOptions ) {
2280 $response->header( "X-Frame-Options: $frameOptions" );
2281 }
2282
2283 if ( $this->mArticleBodyOnly ) {
2284 echo $this->mBodytext;
2285 } else {
2286 $sk = $this->getSkin();
2287 // add skin specific modules
2288 $modules = $sk->getDefaultModules();
2289
2290 // Enforce various default modules for all skins
2291 $coreModules = array(
2292 // Keep this list as small as possible
2293 'site',
2294 'mediawiki.page.startup',
2295 'mediawiki.user',
2296 );
2297
2298 // Support for high-density display images if enabled
2299 if ( $config->get( 'ResponsiveImages' ) ) {
2300 $coreModules[] = 'mediawiki.hidpi';
2301 }
2302
2303 $this->addModules( $coreModules );
2304 foreach ( $modules as $group ) {
2305 $this->addModules( $group );
2306 }
2307 MWDebug::addModules( $this );
2308
2309 // Hook that allows last minute changes to the output page, e.g.
2310 // adding of CSS or Javascript by extensions.
2311 Hooks::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2312
2313 $sk->outputPage();
2314 }
2315
2316 // This hook allows last minute changes to final overall output by modifying output buffer
2317 Hooks::run( 'AfterFinalPageOutput', array( $this ) );
2318
2319 $this->sendCacheControl();
2320
2321 ob_end_flush();
2322
2323 }
2324
2325 /**
2326 * Actually output something with print.
2327 *
2328 * @param string $ins The string to output
2329 * @deprecated since 1.22 Use echo yourself.
2330 */
2331 public function out( $ins ) {
2332 wfDeprecated( __METHOD__, '1.22' );
2333 print $ins;
2334 }
2335
2336 /**
2337 * Produce a "user is blocked" page.
2338 * @deprecated since 1.18
2339 */
2340 function blockedPage() {
2341 throw new UserBlockedError( $this->getUser()->mBlock );
2342 }
2343
2344 /**
2345 * Prepare this object to display an error page; disable caching and
2346 * indexing, clear the current text and redirect, set the page's title
2347 * and optionally an custom HTML title (content of the "<title>" tag).
2348 *
2349 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2350 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2351 * optional, if not passed the "<title>" attribute will be
2352 * based on $pageTitle
2353 */
2354 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2355 $this->setPageTitle( $pageTitle );
2356 if ( $htmlTitle !== false ) {
2357 $this->setHTMLTitle( $htmlTitle );
2358 }
2359 $this->setRobotPolicy( 'noindex,nofollow' );
2360 $this->setArticleRelated( false );
2361 $this->enableClientCache( false );
2362 $this->mRedirect = '';
2363 $this->clearSubtitle();
2364 $this->clearHTML();
2365 }
2366
2367 /**
2368 * Output a standard error page
2369 *
2370 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2371 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2372 * showErrorPage( 'titlemsg', $messageObject );
2373 * showErrorPage( $titleMessageObject, $messageObject );
2374 *
2375 * @param string|Message $title Message key (string) for page title, or a Message object
2376 * @param string|Message $msg Message key (string) for page text, or a Message object
2377 * @param array $params Message parameters; ignored if $msg is a Message object
2378 */
2379 public function showErrorPage( $title, $msg, $params = array() ) {
2380 if ( !$title instanceof Message ) {
2381 $title = $this->msg( $title );
2382 }
2383
2384 $this->prepareErrorPage( $title );
2385
2386 if ( $msg instanceof Message ) {
2387 if ( $params !== array() ) {
2388 trigger_error( 'Argument ignored: $params. The message parameters argument '
2389 . 'is discarded when the $msg argument is a Message object instead of '
2390 . 'a string.', E_USER_NOTICE );
2391 }
2392 $this->addHTML( $msg->parseAsBlock() );
2393 } else {
2394 $this->addWikiMsgArray( $msg, $params );
2395 }
2396
2397 $this->returnToMain();
2398 }
2399
2400 /**
2401 * Output a standard permission error page
2402 *
2403 * @param array $errors Error message keys
2404 * @param string $action Action that was denied or null if unknown
2405 */
2406 public function showPermissionsErrorPage( array $errors, $action = null ) {
2407 // For some action (read, edit, create and upload), display a "login to do this action"
2408 // error if all of the following conditions are met:
2409 // 1. the user is not logged in
2410 // 2. the only error is insufficient permissions (i.e. no block or something else)
2411 // 3. the error can be avoided simply by logging in
2412 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2413 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2414 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2415 && ( User::groupHasPermission( 'user', $action )
2416 || User::groupHasPermission( 'autoconfirmed', $action ) )
2417 ) {
2418 $displayReturnto = null;
2419
2420 # Due to bug 32276, if a user does not have read permissions,
2421 # $this->getTitle() will just give Special:Badtitle, which is
2422 # not especially useful as a returnto parameter. Use the title
2423 # from the request instead, if there was one.
2424 $request = $this->getRequest();
2425 $returnto = Title::newFromURL( $request->getVal( 'title', '' ) );
2426 if ( $action == 'edit' ) {
2427 $msg = 'whitelistedittext';
2428 $displayReturnto = $returnto;
2429 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2430 $msg = 'nocreatetext';
2431 } elseif ( $action == 'upload' ) {
2432 $msg = 'uploadnologintext';
2433 } else { # Read
2434 $msg = 'loginreqpagetext';
2435 $displayReturnto = Title::newMainPage();
2436 }
2437
2438 $query = array();
2439
2440 if ( $returnto ) {
2441 $query['returnto'] = $returnto->getPrefixedText();
2442
2443 if ( !$request->wasPosted() ) {
2444 $returntoquery = $request->getValues();
2445 unset( $returntoquery['title'] );
2446 unset( $returntoquery['returnto'] );
2447 unset( $returntoquery['returntoquery'] );
2448 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2449 }
2450 }
2451 $loginLink = Linker::linkKnown(
2452 SpecialPage::getTitleFor( 'Userlogin' ),
2453 $this->msg( 'loginreqlink' )->escaped(),
2454 array(),
2455 $query
2456 );
2457
2458 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2459 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2460
2461 # Don't return to a page the user can't read otherwise
2462 # we'll end up in a pointless loop
2463 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2464 $this->returnToMain( null, $displayReturnto );
2465 }
2466 } else {
2467 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2468 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2469 }
2470 }
2471
2472 /**
2473 * Display an error page indicating that a given version of MediaWiki is
2474 * required to use it
2475 *
2476 * @param mixed $version The version of MediaWiki needed to use the page
2477 */
2478 public function versionRequired( $version ) {
2479 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2480
2481 $this->addWikiMsg( 'versionrequiredtext', $version );
2482 $this->returnToMain();
2483 }
2484
2485 /**
2486 * Display an error page noting that a given permission bit is required.
2487 * @deprecated since 1.18, just throw the exception directly
2488 * @param string $permission Key required
2489 * @throws PermissionsError
2490 */
2491 public function permissionRequired( $permission ) {
2492 throw new PermissionsError( $permission );
2493 }
2494
2495 /**
2496 * Produce the stock "please login to use the wiki" page
2497 *
2498 * @deprecated since 1.19; throw the exception directly
2499 */
2500 public function loginToUse() {
2501 throw new PermissionsError( 'read' );
2502 }
2503
2504 /**
2505 * Format a list of error messages
2506 *
2507 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2508 * @param string $action Action that was denied or null if unknown
2509 * @return string The wikitext error-messages, formatted into a list.
2510 */
2511 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2512 if ( $action == null ) {
2513 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2514 } else {
2515 $action_desc = $this->msg( "action-$action" )->plain();
2516 $text = $this->msg(
2517 'permissionserrorstext-withaction',
2518 count( $errors ),
2519 $action_desc
2520 )->plain() . "\n\n";
2521 }
2522
2523 if ( count( $errors ) > 1 ) {
2524 $text .= '<ul class="permissions-errors">' . "\n";
2525
2526 foreach ( $errors as $error ) {
2527 $text .= '<li>';
2528 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2529 $text .= "</li>\n";
2530 }
2531 $text .= '</ul>';
2532 } else {
2533 $text .= "<div class=\"permissions-errors\">\n" .
2534 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2535 "\n</div>";
2536 }
2537
2538 return $text;
2539 }
2540
2541 /**
2542 * Display a page stating that the Wiki is in read-only mode.
2543 * Should only be called after wfReadOnly() has returned true.
2544 *
2545 * Historically, this function was used to show the source of the page that the user
2546 * was trying to edit and _also_ permissions error messages. The relevant code was
2547 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2548 *
2549 * @deprecated since 1.25; throw the exception directly
2550 * @throws ReadOnlyError
2551 */
2552 public function readOnlyPage() {
2553 if ( func_num_args() > 0 ) {
2554 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2555 }
2556
2557 throw new ReadOnlyError;
2558 }
2559
2560 /**
2561 * Turn off regular page output and return an error response
2562 * for when rate limiting has triggered.
2563 *
2564 * @deprecated since 1.25; throw the exception directly
2565 */
2566 public function rateLimited() {
2567 wfDeprecated( __METHOD__, '1.25' );
2568 throw new ThrottledError;
2569 }
2570
2571 /**
2572 * Show a warning about slave lag
2573 *
2574 * If the lag is higher than $wgSlaveLagCritical seconds,
2575 * then the warning is a bit more obvious. If the lag is
2576 * lower than $wgSlaveLagWarning, then no warning is shown.
2577 *
2578 * @param int $lag Slave lag
2579 */
2580 public function showLagWarning( $lag ) {
2581 $config = $this->getConfig();
2582 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2583 $message = $lag < $config->get( 'SlaveLagCritical' )
2584 ? 'lag-warn-normal'
2585 : 'lag-warn-high';
2586 $wrap = Html::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2587 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2588 }
2589 }
2590
2591 public function showFatalError( $message ) {
2592 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2593
2594 $this->addHTML( $message );
2595 }
2596
2597 public function showUnexpectedValueError( $name, $val ) {
2598 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2599 }
2600
2601 public function showFileCopyError( $old, $new ) {
2602 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2603 }
2604
2605 public function showFileRenameError( $old, $new ) {
2606 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2607 }
2608
2609 public function showFileDeleteError( $name ) {
2610 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2611 }
2612
2613 public function showFileNotFoundError( $name ) {
2614 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2615 }
2616
2617 /**
2618 * Add a "return to" link pointing to a specified title
2619 *
2620 * @param Title $title Title to link
2621 * @param array $query Query string parameters
2622 * @param string $text Text of the link (input is not escaped)
2623 * @param array $options Options array to pass to Linker
2624 */
2625 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2626 $link = $this->msg( 'returnto' )->rawParams(
2627 Linker::link( $title, $text, array(), $query, $options ) )->escaped();
2628 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2629 }
2630
2631 /**
2632 * Add a "return to" link pointing to a specified title,
2633 * or the title indicated in the request, or else the main page
2634 *
2635 * @param mixed $unused
2636 * @param Title|string $returnto Title or String to return to
2637 * @param string $returntoquery Query string for the return to link
2638 */
2639 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2640 if ( $returnto == null ) {
2641 $returnto = $this->getRequest()->getText( 'returnto' );
2642 }
2643
2644 if ( $returntoquery == null ) {
2645 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2646 }
2647
2648 if ( $returnto === '' ) {
2649 $returnto = Title::newMainPage();
2650 }
2651
2652 if ( is_object( $returnto ) ) {
2653 $titleObj = $returnto;
2654 } else {
2655 $titleObj = Title::newFromText( $returnto );
2656 }
2657 if ( !is_object( $titleObj ) ) {
2658 $titleObj = Title::newMainPage();
2659 }
2660
2661 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2662 }
2663
2664 /**
2665 * @param Skin $sk The given Skin
2666 * @param bool $includeStyle Unused
2667 * @return string The doctype, opening "<html>", and head element.
2668 */
2669 public function headElement( Skin $sk, $includeStyle = true ) {
2670 global $wgContLang;
2671
2672 $userdir = $this->getLanguage()->getDir();
2673 $sitedir = $wgContLang->getDir();
2674
2675 $ret = Html::htmlHeader( $sk->getHtmlElementAttributes() );
2676
2677 if ( $this->getHTMLTitle() == '' ) {
2678 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2679 }
2680
2681 $openHead = Html::openElement( 'head' );
2682 if ( $openHead ) {
2683 # Don't bother with the newline if $head == ''
2684 $ret .= "$openHead\n";
2685 }
2686
2687 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2688 // Add <meta charset="UTF-8">
2689 // This should be before <title> since it defines the charset used by
2690 // text including the text inside <title>.
2691 // The spec recommends defining XHTML5's charset using the XML declaration
2692 // instead of meta.
2693 // Our XML declaration is output by Html::htmlHeader.
2694 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2695 // http://www.whatwg.org/html/semantics.html#charset
2696 $ret .= Html::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2697 }
2698
2699 $ret .= Html::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2700
2701 foreach ( $this->getHeadLinksArray() as $item ) {
2702 $ret .= $item . "\n";
2703 }
2704
2705 $ret .= $this->buildCssLinks() . "\n";
2706
2707 $ret .= $this->getHeadScripts() . "\n";
2708
2709 foreach ( $this->mHeadItems as $item ) {
2710 $ret .= $item . "\n";
2711 }
2712
2713 $closeHead = Html::closeElement( 'head' );
2714 if ( $closeHead ) {
2715 $ret .= "$closeHead\n";
2716 }
2717
2718 $bodyClasses = array();
2719 $bodyClasses[] = 'mediawiki';
2720
2721 # Classes for LTR/RTL directionality support
2722 $bodyClasses[] = $userdir;
2723 $bodyClasses[] = "sitedir-$sitedir";
2724
2725 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2726 # A <body> class is probably not the best way to do this . . .
2727 $bodyClasses[] = 'capitalize-all-nouns';
2728 }
2729
2730 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2731 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2732 $bodyClasses[] =
2733 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2734
2735 $bodyAttrs = array();
2736 // While the implode() is not strictly needed, it's used for backwards compatibility
2737 // (this used to be built as a string and hooks likely still expect that).
2738 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2739
2740 // Allow skins and extensions to add body attributes they need
2741 $sk->addToBodyAttributes( $this, $bodyAttrs );
2742 Hooks::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2743
2744 $ret .= Html::openElement( 'body', $bodyAttrs ) . "\n";
2745
2746 return $ret;
2747 }
2748
2749 /**
2750 * Get a ResourceLoader object associated with this OutputPage
2751 *
2752 * @return ResourceLoader
2753 */
2754 public function getResourceLoader() {
2755 if ( is_null( $this->mResourceLoader ) ) {
2756 $this->mResourceLoader = new ResourceLoader(
2757 $this->getConfig(),
2758 LoggerFactory::getInstance( 'resourceloader' )
2759 );
2760 }
2761 return $this->mResourceLoader;
2762 }
2763
2764 /**
2765 * @todo Document
2766 * @param array|string $modules One or more module names
2767 * @param string $only ResourceLoaderModule TYPE_ class constant
2768 * @param array $extraQuery Array with extra query parameters to add to each
2769 * request. array( param => value ).
2770 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2771 * call rather than a "<script src='...'>" tag.
2772 * @return string The html "<script>", "<link>" and "<style>" tags
2773 */
2774 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = array(),
2775 $loadCall = false
2776 ) {
2777 $modules = (array)$modules;
2778
2779 $links = array(
2780 // List of html strings
2781 'html' => array(),
2782 // Associative array of module names and their states
2783 'states' => array(),
2784 );
2785
2786 if ( !count( $modules ) ) {
2787 return $links;
2788 }
2789
2790 if ( count( $modules ) > 1 ) {
2791 // Remove duplicate module requests
2792 $modules = array_unique( $modules );
2793 // Sort module names so requests are more uniform
2794 sort( $modules );
2795
2796 if ( ResourceLoader::inDebugMode() ) {
2797 // Recursively call us for every item
2798 foreach ( $modules as $name ) {
2799 $link = $this->makeResourceLoaderLink( $name, $only );
2800 $links['html'] = array_merge( $links['html'], $link['html'] );
2801 $links['states'] += $link['states'];
2802 }
2803 return $links;
2804 }
2805 }
2806
2807 if ( !is_null( $this->mTarget ) ) {
2808 $extraQuery['target'] = $this->mTarget;
2809 }
2810
2811 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2812 $sortedModules = array();
2813 $resourceLoader = $this->getResourceLoader();
2814 foreach ( $modules as $name ) {
2815 $module = $resourceLoader->getModule( $name );
2816 # Check that we're allowed to include this module on this page
2817 if ( !$module
2818 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_SCRIPTS )
2819 && $only == ResourceLoaderModule::TYPE_SCRIPTS )
2820 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_STYLES )
2821 && $only == ResourceLoaderModule::TYPE_STYLES )
2822 || ( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule::TYPE_COMBINED )
2823 && $only == ResourceLoaderModule::TYPE_COMBINED )
2824 || ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) )
2825 ) {
2826 continue;
2827 }
2828
2829 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2830 }
2831
2832 foreach ( $sortedModules as $source => $groups ) {
2833 foreach ( $groups as $group => $grpModules ) {
2834 // Special handling for user-specific groups
2835 $user = null;
2836 if ( ( $group === 'user' || $group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2837 $user = $this->getUser()->getName();
2838 }
2839
2840 // Create a fake request based on the one we are about to make so modules return
2841 // correct timestamp and emptiness data
2842 $query = ResourceLoader::makeLoaderQuery(
2843 array(), // modules; not determined yet
2844 $this->getLanguage()->getCode(),
2845 $this->getSkin()->getSkinName(),
2846 $user,
2847 null, // version; not determined yet
2848 ResourceLoader::inDebugMode(),
2849 $only === ResourceLoaderModule::TYPE_COMBINED ? null : $only,
2850 $this->isPrintable(),
2851 $this->getRequest()->getBool( 'handheld' ),
2852 $extraQuery
2853 );
2854 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2855
2856 // Extract modules that know they're empty and see if we have one or more
2857 // raw modules
2858 $isRaw = false;
2859 foreach ( $grpModules as $key => $module ) {
2860 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2861 // If we're only getting the styles, we don't need to do anything for empty modules.
2862 if ( $module->isKnownEmpty( $context ) ) {
2863 unset( $grpModules[$key] );
2864 if ( $only !== ResourceLoaderModule::TYPE_STYLES ) {
2865 $links['states'][$key] = 'ready';
2866 }
2867 }
2868
2869 $isRaw |= $module->isRaw();
2870 }
2871
2872 // If there are no non-empty modules, skip this group
2873 if ( count( $grpModules ) === 0 ) {
2874 continue;
2875 }
2876
2877 // Inline private modules. These can't be loaded through load.php for security
2878 // reasons, see bug 34907. Note that these modules should be loaded from
2879 // getHeadScripts() before the first loader call. Otherwise other modules can't
2880 // properly use them as dependencies (bug 30914)
2881 if ( $group === 'private' ) {
2882 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
2883 $links['html'][] = Html::inlineStyle(
2884 $resourceLoader->makeModuleResponse( $context, $grpModules )
2885 );
2886 } else {
2887 $links['html'][] = ResourceLoader::makeInlineScript(
2888 $resourceLoader->makeModuleResponse( $context, $grpModules )
2889 );
2890 }
2891 continue;
2892 }
2893
2894 // Special handling for the user group; because users might change their stuff
2895 // on-wiki like user pages, or user preferences; we need to find the highest
2896 // timestamp of these user-changeable modules so we can ensure cache misses on change
2897 // This should NOT be done for the site group (bug 27564) because anons get that too
2898 // and we shouldn't be putting timestamps in Squid-cached HTML
2899 $version = null;
2900 if ( $group === 'user' ) {
2901 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2902 }
2903
2904 $query['modules'] = ResourceLoader::makePackedModulesString( array_keys( $grpModules ) );
2905 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2906 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2907
2908 // Automatically select style/script elements
2909 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
2910 $link = Html::linkedStyle( $url );
2911 } elseif ( $loadCall ) {
2912 $link = ResourceLoader::makeInlineScript(
2913 Xml::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2914 );
2915 } else {
2916 $link = Html::linkedScript( $url );
2917 if ( !$context->getRaw() && !$isRaw ) {
2918 // Wrap only=script / only=combined requests in a conditional as
2919 // browsers not supported by the startup module would unconditionally
2920 // execute this module. Otherwise users will get "ReferenceError: mw is
2921 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2922 $link = ResourceLoader::makeInlineScript(
2923 Xml::encodeJsCall( 'document.write', array( $link ) )
2924 );
2925 }
2926
2927 // For modules requested directly in the html via <link> or <script>,
2928 // tell mw.loader they are being loading to prevent duplicate requests.
2929 foreach ( $grpModules as $key => $module ) {
2930 // Don't output state=loading for the startup module..
2931 if ( $key !== 'startup' ) {
2932 $links['states'][$key] = 'loading';
2933 }
2934 }
2935 }
2936
2937 if ( $group == 'noscript' ) {
2938 $links['html'][] = Html::rawElement( 'noscript', array(), $link );
2939 } else {
2940 $links['html'][] = $link;
2941 }
2942 }
2943 }
2944
2945 return $links;
2946 }
2947
2948 /**
2949 * Build html output from an array of links from makeResourceLoaderLink.
2950 * @param array $links
2951 * @return string HTML
2952 */
2953 protected static function getHtmlFromLoaderLinks( array $links ) {
2954 $html = array();
2955 $states = array();
2956 foreach ( $links as $link ) {
2957 if ( !is_array( $link ) ) {
2958 $html[] = $link;
2959 } else {
2960 $html = array_merge( $html, $link['html'] );
2961 $states += $link['states'];
2962 }
2963 }
2964 // Filter out empty values
2965 $html = array_filter( $html, 'strlen' );
2966
2967 if ( count( $states ) ) {
2968 array_unshift( $html, ResourceLoader::makeInlineScript(
2969 ResourceLoader::makeLoaderStateScript( $states )
2970 ) );
2971 }
2972
2973 return WrappedString::join( "\n", $html );
2974 }
2975
2976 /**
2977 * JS stuff to put in the "<head>". This is the startup module, config
2978 * vars and modules marked with position 'top'
2979 *
2980 * @return string HTML fragment
2981 */
2982 function getHeadScripts() {
2983 // Startup - this will immediately load jquery and mediawiki modules
2984 $links = array();
2985 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule::TYPE_SCRIPTS );
2986
2987 // Load config before anything else
2988 $links[] = ResourceLoader::makeInlineScript(
2989 ResourceLoader::makeConfigSetScript( $this->getJSVars() )
2990 );
2991
2992 // Load embeddable private modules before any loader links
2993 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2994 // in mw.loader.implement() calls and deferred until mw.user is available
2995 $embedScripts = array( 'user.options' );
2996 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule::TYPE_COMBINED );
2997 // Separate user.tokens as otherwise caching will be allowed (T84960)
2998 $links[] = $this->makeResourceLoaderLink( 'user.tokens', ResourceLoaderModule::TYPE_COMBINED );
2999
3000 // Modules requests - let the client calculate dependencies and batch requests as it likes
3001 // Only load modules that have marked themselves for loading at the top
3002 $modules = $this->getModules( true, 'top' );
3003 if ( $modules ) {
3004 $links[] = ResourceLoader::makeInlineScript(
3005 Xml::encodeJsCall( 'mw.loader.load', array( $modules ) )
3006 );
3007 }
3008
3009 // "Scripts only" modules marked for top inclusion
3010 $links[] = $this->makeResourceLoaderLink(
3011 $this->getModuleScripts( true, 'top' ),
3012 ResourceLoaderModule::TYPE_SCRIPTS
3013 );
3014
3015 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3016 $links[] = $this->getScriptsForBottomQueue( true );
3017 }
3018
3019 return self::getHtmlFromLoaderLinks( $links );
3020 }
3021
3022 /**
3023 * JS stuff to put at the 'bottom', which can either be the bottom of the
3024 * "<body>" or the bottom of the "<head>" depending on
3025 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3026 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3027 * and user JS.
3028 *
3029 * @param bool $inHead If true, this HTML goes into the "<head>",
3030 * if false it goes into the "<body>".
3031 * @return string
3032 */
3033 function getScriptsForBottomQueue( $inHead ) {
3034 // Scripts "only" requests marked for bottom inclusion
3035 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3036 $links = array();
3037
3038 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3039 ResourceLoaderModule::TYPE_SCRIPTS, /* $extraQuery = */ array(),
3040 /* $loadCall = */ $inHead
3041 );
3042
3043 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3044 ResourceLoaderModule::TYPE_STYLES, /* $extraQuery = */ array(),
3045 /* $loadCall = */ $inHead
3046 );
3047
3048 // Modules requests - let the client calculate dependencies and batch requests as it likes
3049 // Only load modules that have marked themselves for loading at the bottom
3050 $modules = $this->getModules( true, 'bottom' );
3051 if ( $modules ) {
3052 $links[] = ResourceLoader::makeInlineScript(
3053 Xml::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3054 );
3055 }
3056
3057 // Legacy Scripts
3058 $links[] = $this->mScripts;
3059
3060 // Add user JS if enabled
3061 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3062 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3063 if ( $this->getConfig()->get( 'AllowUserJs' )
3064 && $this->getUser()->isLoggedIn()
3065 && $this->getTitle()
3066 && $this->getTitle()->isJsSubpage()
3067 && $this->userCanPreview()
3068 ) {
3069 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3070 // and include the draft contents as a raw script instead.
3071 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3072 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3073 );
3074 // Load the previewed JS
3075 $links[] = ResourceLoader::makeInlineScript(
3076 Xml::encodeJsCall( 'mw.loader.using', array(
3077 array( 'user', 'site' ),
3078 new XmlJsCode(
3079 'function () {'
3080 . Xml::encodeJsCall( '$.globalEval', array(
3081 $this->getRequest()->getText( 'wpTextbox1' )
3082 ) )
3083 . '}'
3084 )
3085 ) )
3086 );
3087
3088 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3089 // asynchronously and may arrive *after* the inline script here. So the previewed code
3090 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3091 // Similarly, when previewing ./common.js and the user module does arrive first, it will
3092 // arrive without common.js and the inline script runs after. Thus running common after
3093 // the excluded subpage.
3094 } else {
3095 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3096 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3097 /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3098 );
3099 }
3100
3101 // Group JS is only enabled if site JS is enabled.
3102 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule::TYPE_COMBINED,
3103 /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3104 );
3105
3106 return self::getHtmlFromLoaderLinks( $links );
3107 }
3108
3109 /**
3110 * JS stuff to put at the bottom of the "<body>"
3111 * @return string
3112 */
3113 function getBottomScripts() {
3114 // In case the skin wants to add bottom CSS
3115 $this->getSkin()->setupSkinUserCss( $this );
3116
3117 // Optimise jQuery ready event cross-browser.
3118 // This also enforces $.isReady to be true at </body> which fixes the
3119 // mw.loader bug in Firefox with using document.write between </body>
3120 // and the DOMContentReady event (bug 47457).
3121 $html = Html::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3122
3123 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3124 $html .= $this->getScriptsForBottomQueue( false );
3125 }
3126
3127 return $html;
3128 }
3129
3130 /**
3131 * Get the javascript config vars to include on this page
3132 *
3133 * @return array Array of javascript config vars
3134 * @since 1.23
3135 */
3136 public function getJsConfigVars() {
3137 return $this->mJsConfigVars;
3138 }
3139
3140 /**
3141 * Add one or more variables to be set in mw.config in JavaScript
3142 *
3143 * @param string|array $keys Key or array of key/value pairs
3144 * @param mixed $value [optional] Value of the configuration variable
3145 */
3146 public function addJsConfigVars( $keys, $value = null ) {
3147 if ( is_array( $keys ) ) {
3148 foreach ( $keys as $key => $value ) {
3149 $this->mJsConfigVars[$key] = $value;
3150 }
3151 return;
3152 }
3153
3154 $this->mJsConfigVars[$keys] = $value;
3155 }
3156
3157 /**
3158 * Get an array containing the variables to be set in mw.config in JavaScript.
3159 *
3160 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3161 * - in other words, page-independent/site-wide variables (without state).
3162 * You will only be adding bloat to the html page and causing page caches to
3163 * have to be purged on configuration changes.
3164 * @return array
3165 */
3166 public function getJSVars() {
3167 global $wgContLang;
3168
3169 $curRevisionId = 0;
3170 $articleId = 0;
3171 $canonicalSpecialPageName = false; # bug 21115
3172
3173 $title = $this->getTitle();
3174 $ns = $title->getNamespace();
3175 $canonicalNamespace = MWNamespace::exists( $ns )
3176 ? MWNamespace::getCanonicalName( $ns )
3177 : $title->getNsText();
3178
3179 $sk = $this->getSkin();
3180 // Get the relevant title so that AJAX features can use the correct page name
3181 // when making API requests from certain special pages (bug 34972).
3182 $relevantTitle = $sk->getRelevantTitle();
3183 $relevantUser = $sk->getRelevantUser();
3184
3185 if ( $ns == NS_SPECIAL ) {
3186 list( $canonicalSpecialPageName, /*...*/ ) =
3187 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3188 } elseif ( $this->canUseWikiPage() ) {
3189 $wikiPage = $this->getWikiPage();
3190 $curRevisionId = $wikiPage->getLatest();
3191 $articleId = $wikiPage->getId();
3192 }
3193
3194 $lang = $title->getPageLanguage();
3195
3196 // Pre-process information
3197 $separatorTransTable = $lang->separatorTransformTable();
3198 $separatorTransTable = $separatorTransTable ? $separatorTransTable : array();
3199 $compactSeparatorTransTable = array(
3200 implode( "\t", array_keys( $separatorTransTable ) ),
3201 implode( "\t", $separatorTransTable ),
3202 );
3203 $digitTransTable = $lang->digitTransformTable();
3204 $digitTransTable = $digitTransTable ? $digitTransTable : array();
3205 $compactDigitTransTable = array(
3206 implode( "\t", array_keys( $digitTransTable ) ),
3207 implode( "\t", $digitTransTable ),
3208 );
3209
3210 $user = $this->getUser();
3211
3212 $vars = array(
3213 'wgCanonicalNamespace' => $canonicalNamespace,
3214 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3215 'wgNamespaceNumber' => $title->getNamespace(),
3216 'wgPageName' => $title->getPrefixedDBkey(),
3217 'wgTitle' => $title->getText(),
3218 'wgCurRevisionId' => $curRevisionId,
3219 'wgRevisionId' => (int)$this->getRevisionId(),
3220 'wgArticleId' => $articleId,
3221 'wgIsArticle' => $this->isArticle(),
3222 'wgIsRedirect' => $title->isRedirect(),
3223 'wgAction' => Action::getActionName( $this->getContext() ),
3224 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3225 'wgUserGroups' => $user->getEffectiveGroups(),
3226 'wgCategories' => $this->getCategories(),
3227 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3228 'wgPageContentLanguage' => $lang->getCode(),
3229 'wgPageContentModel' => $title->getContentModel(),
3230 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3231 'wgDigitTransformTable' => $compactDigitTransTable,
3232 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3233 'wgMonthNames' => $lang->getMonthNamesArray(),
3234 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3235 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3236 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3237 );
3238
3239 if ( $user->isLoggedIn() ) {
3240 $vars['wgUserId'] = $user->getId();
3241 $vars['wgUserEditCount'] = $user->getEditCount();
3242 $userReg = wfTimestampOrNull( TS_UNIX, $user->getRegistration() );
3243 $vars['wgUserRegistration'] = $userReg !== null ? ( $userReg * 1000 ) : null;
3244 // Get the revision ID of the oldest new message on the user's talk
3245 // page. This can be used for constructing new message alerts on
3246 // the client side.
3247 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3248 }
3249
3250 if ( $wgContLang->hasVariants() ) {
3251 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3252 }
3253 // Same test as SkinTemplate
3254 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3255 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3256
3257 foreach ( $title->getRestrictionTypes() as $type ) {
3258 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3259 }
3260
3261 if ( $title->isMainPage() ) {
3262 $vars['wgIsMainPage'] = true;
3263 }
3264
3265 if ( $this->mRedirectedFrom ) {
3266 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3267 }
3268
3269 if ( $relevantUser ) {
3270 $vars['wgRelevantUserName'] = $relevantUser->getName();
3271 }
3272
3273 // Allow extensions to add their custom variables to the mw.config map.
3274 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3275 // page-dependant but site-wide (without state).
3276 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3277 Hooks::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3278
3279 // Merge in variables from addJsConfigVars last
3280 return array_merge( $vars, $this->getJsConfigVars() );
3281 }
3282
3283 /**
3284 * To make it harder for someone to slip a user a fake
3285 * user-JavaScript or user-CSS preview, a random token
3286 * is associated with the login session. If it's not
3287 * passed back with the preview request, we won't render
3288 * the code.
3289 *
3290 * @return bool
3291 */
3292 public function userCanPreview() {
3293 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3294 || !$this->getRequest()->wasPosted()
3295 || !$this->getUser()->matchEditToken(
3296 $this->getRequest()->getVal( 'wpEditToken' ) )
3297 ) {
3298 return false;
3299 }
3300 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3301 return false;
3302 }
3303 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3304 // Don't execute another user's CSS or JS on preview (T85855)
3305 return false;
3306 }
3307
3308 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3309 }
3310
3311 /**
3312 * @return array Array in format "link name or number => 'link html'".
3313 */
3314 public function getHeadLinksArray() {
3315 global $wgVersion;
3316
3317 $tags = array();
3318 $config = $this->getConfig();
3319
3320 $canonicalUrl = $this->mCanonicalUrl;
3321
3322 $tags['meta-generator'] = Html::element( 'meta', array(
3323 'name' => 'generator',
3324 'content' => "MediaWiki $wgVersion",
3325 ) );
3326
3327 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3328 $tags['meta-referrer'] = Html::element( 'meta', array(
3329 'name' => 'referrer',
3330 'content' => $config->get( 'ReferrerPolicy' )
3331 ) );
3332 }
3333
3334 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3335 if ( $p !== 'index,follow' ) {
3336 // http://www.robotstxt.org/wc/meta-user.html
3337 // Only show if it's different from the default robots policy
3338 $tags['meta-robots'] = Html::element( 'meta', array(
3339 'name' => 'robots',
3340 'content' => $p,
3341 ) );
3342 }
3343
3344 foreach ( $this->mMetatags as $tag ) {
3345 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3346 $a = 'http-equiv';
3347 $tag[0] = substr( $tag[0], 5 );
3348 } else {
3349 $a = 'name';
3350 }
3351 $tagName = "meta-{$tag[0]}";
3352 if ( isset( $tags[$tagName] ) ) {
3353 $tagName .= $tag[1];
3354 }
3355 $tags[$tagName] = Html::element( 'meta',
3356 array(
3357 $a => $tag[0],
3358 'content' => $tag[1]
3359 )
3360 );
3361 }
3362
3363 foreach ( $this->mLinktags as $tag ) {
3364 $tags[] = Html::element( 'link', $tag );
3365 }
3366
3367 # Universal edit button
3368 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3369 $user = $this->getUser();
3370 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3371 && ( $this->getTitle()->exists() || $this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3372 // Original UniversalEditButton
3373 $msg = $this->msg( 'edit' )->text();
3374 $tags['universal-edit-button'] = Html::element( 'link', array(
3375 'rel' => 'alternate',
3376 'type' => 'application/x-wiki',
3377 'title' => $msg,
3378 'href' => $this->getTitle()->getEditURL(),
3379 ) );
3380 // Alternate edit link
3381 $tags['alternative-edit'] = Html::element( 'link', array(
3382 'rel' => 'edit',
3383 'title' => $msg,
3384 'href' => $this->getTitle()->getEditURL(),
3385 ) );
3386 }
3387 }
3388
3389 # Generally the order of the favicon and apple-touch-icon links
3390 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3391 # uses whichever one appears later in the HTML source. Make sure
3392 # apple-touch-icon is specified first to avoid this.
3393 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3394 $tags['apple-touch-icon'] = Html::element( 'link', array(
3395 'rel' => 'apple-touch-icon',
3396 'href' => $config->get( 'AppleTouchIcon' )
3397 ) );
3398 }
3399
3400 if ( $config->get( 'Favicon' ) !== false ) {
3401 $tags['favicon'] = Html::element( 'link', array(
3402 'rel' => 'shortcut icon',
3403 'href' => $config->get( 'Favicon' )
3404 ) );
3405 }
3406
3407 # OpenSearch description link
3408 $tags['opensearch'] = Html::element( 'link', array(
3409 'rel' => 'search',
3410 'type' => 'application/opensearchdescription+xml',
3411 'href' => wfScript( 'opensearch_desc' ),
3412 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3413 ) );
3414
3415 if ( $config->get( 'EnableAPI' ) ) {
3416 # Real Simple Discovery link, provides auto-discovery information
3417 # for the MediaWiki API (and potentially additional custom API
3418 # support such as WordPress or Twitter-compatible APIs for a
3419 # blogging extension, etc)
3420 $tags['rsd'] = Html::element( 'link', array(
3421 'rel' => 'EditURI',
3422 'type' => 'application/rsd+xml',
3423 // Output a protocol-relative URL here if $wgServer is protocol-relative
3424 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3425 'href' => wfExpandUrl( wfAppendQuery(
3426 wfScript( 'api' ),
3427 array( 'action' => 'rsd' ) ),
3428 PROTO_RELATIVE
3429 ),
3430 ) );
3431 }
3432
3433 # Language variants
3434 if ( !$config->get( 'DisableLangConversion' ) ) {
3435 $lang = $this->getTitle()->getPageLanguage();
3436 if ( $lang->hasVariants() ) {
3437 $variants = $lang->getVariants();
3438 foreach ( $variants as $variant ) {
3439 $tags["variant-$variant"] = Html::element( 'link', array(
3440 'rel' => 'alternate',
3441 'hreflang' => wfBCP47( $variant ),
3442 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $variant ) ) )
3443 );
3444 }
3445 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3446 $tags["variant-x-default"] = Html::element( 'link', array(
3447 'rel' => 'alternate',
3448 'hreflang' => 'x-default',
3449 'href' => $this->getTitle()->getLocalURL() ) );
3450 }
3451 }
3452
3453 # Copyright
3454 if ( $this->copyrightUrl !== null ) {
3455 $copyright = $this->copyrightUrl;
3456 } else {
3457 $copyright = '';
3458 if ( $config->get( 'RightsPage' ) ) {
3459 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3460
3461 if ( $copy ) {
3462 $copyright = $copy->getLocalURL();
3463 }
3464 }
3465
3466 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3467 $copyright = $config->get( 'RightsUrl' );
3468 }
3469 }
3470
3471 if ( $copyright ) {
3472 $tags['copyright'] = Html::element( 'link', array(
3473 'rel' => 'copyright',
3474 'href' => $copyright )
3475 );
3476 }
3477
3478 # Feeds
3479 if ( $config->get( 'Feed' ) ) {
3480 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3481 # Use the page name for the title. In principle, this could
3482 # lead to issues with having the same name for different feeds
3483 # corresponding to the same page, but we can't avoid that at
3484 # this low a level.
3485
3486 $tags[] = $this->feedLink(
3487 $format,
3488 $link,
3489 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3490 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3491 );
3492 }
3493
3494 # Recent changes feed should appear on every page (except recentchanges,
3495 # that would be redundant). Put it after the per-page feed to avoid
3496 # changing existing behavior. It's still available, probably via a
3497 # menu in your browser. Some sites might have a different feed they'd
3498 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3499 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3500 # If so, use it instead.
3501 $sitename = $config->get( 'Sitename' );
3502 if ( $config->get( 'OverrideSiteFeed' ) ) {
3503 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3504 // Note, this->feedLink escapes the url.
3505 $tags[] = $this->feedLink(
3506 $type,
3507 $feedUrl,
3508 $this->msg( "site-{$type}-feed", $sitename )->text()
3509 );
3510 }
3511 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3512 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3513 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3514 $tags[] = $this->feedLink(
3515 $format,
3516 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3517 # For grep: 'site-rss-feed', 'site-atom-feed'
3518 $this->msg( "site-{$format}-feed", $sitename )->text()
3519 );
3520 }
3521 }
3522 }
3523
3524 # Canonical URL
3525 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3526 if ( $canonicalUrl !== false ) {
3527 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL );
3528 } else {
3529 if ( $this->isArticleRelated() ) {
3530 // This affects all requests where "setArticleRelated" is true. This is
3531 // typically all requests that show content (query title, curid, oldid, diff),
3532 // and all wikipage actions (edit, delete, purge, info, history etc.).
3533 // It does not apply to File pages and Special pages.
3534 // 'history' and 'info' actions address page metadata rather than the page
3535 // content itself, so they may not be canonicalized to the view page url.
3536 // TODO: this ought to be better encapsulated in the Action class.
3537 $action = Action::getActionName( $this->getContext() );
3538 if ( in_array( $action, array( 'history', 'info' ) ) ) {
3539 $query = "action={$action}";
3540 } else {
3541 $query = '';
3542 }
3543 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3544 } else {
3545 $reqUrl = $this->getRequest()->getRequestURL();
3546 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL );
3547 }
3548 }
3549 }
3550 if ( $canonicalUrl !== false ) {
3551 $tags[] = Html::element( 'link', array(
3552 'rel' => 'canonical',
3553 'href' => $canonicalUrl
3554 ) );
3555 }
3556
3557 return $tags;
3558 }
3559
3560 /**
3561 * @return string HTML tag links to be put in the header.
3562 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3563 * OutputPage::getHeadLinksArray directly.
3564 */
3565 public function getHeadLinks() {
3566 wfDeprecated( __METHOD__, '1.24' );
3567 return implode( "\n", $this->getHeadLinksArray() );
3568 }
3569
3570 /**
3571 * Generate a "<link rel/>" for a feed.
3572 *
3573 * @param string $type Feed type
3574 * @param string $url URL to the feed
3575 * @param string $text Value of the "title" attribute
3576 * @return string HTML fragment
3577 */
3578 private function feedLink( $type, $url, $text ) {
3579 return Html::element( 'link', array(
3580 'rel' => 'alternate',
3581 'type' => "application/$type+xml",
3582 'title' => $text,
3583 'href' => $url )
3584 );
3585 }
3586
3587 /**
3588 * Add a local or specified stylesheet, with the given media options.
3589 * Meant primarily for internal use...
3590 *
3591 * @param string $style URL to the file
3592 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3593 * @param string $condition For IE conditional comments, specifying an IE version
3594 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3595 */
3596 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3597 $options = array();
3598 // Even though we expect the media type to be lowercase, but here we
3599 // force it to lowercase to be safe.
3600 if ( $media ) {
3601 $options['media'] = $media;
3602 }
3603 if ( $condition ) {
3604 $options['condition'] = $condition;
3605 }
3606 if ( $dir ) {
3607 $options['dir'] = $dir;
3608 }
3609 $this->styles[$style] = $options;
3610 }
3611
3612 /**
3613 * Adds inline CSS styles
3614 * @param mixed $style_css Inline CSS
3615 * @param string $flip Set to 'flip' to flip the CSS if needed
3616 */
3617 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3618 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3619 # If wanted, and the interface is right-to-left, flip the CSS
3620 $style_css = CSSJanus::transform( $style_css, true, false );
3621 }
3622 $this->mInlineStyles .= Html::inlineStyle( $style_css ) . "\n";
3623 }
3624
3625 /**
3626 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3627 * These will be applied to various media & IE conditionals.
3628 *
3629 * @return string
3630 */
3631 public function buildCssLinks() {
3632 global $wgContLang;
3633
3634 $this->getSkin()->setupSkinUserCss( $this );
3635
3636 // Add ResourceLoader styles
3637 // Split the styles into these groups
3638 $styles = array(
3639 'other' => array(),
3640 'user' => array(),
3641 'site' => array(),
3642 'private' => array(),
3643 'noscript' => array()
3644 );
3645 $links = array();
3646 $otherTags = array(); // Tags to append after the normal <link> tags
3647 $resourceLoader = $this->getResourceLoader();
3648
3649 $moduleStyles = $this->getModuleStyles( true, 'top' );
3650
3651 // Per-site custom styles
3652 $moduleStyles[] = 'site';
3653 $moduleStyles[] = 'noscript';
3654 $moduleStyles[] = 'user.groups';
3655
3656 // Per-user custom styles
3657 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3658 && $this->userCanPreview()
3659 ) {
3660 // We're on a preview of a CSS subpage
3661 // Exclude this page from the user module in case it's in there (bug 26283)
3662 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_STYLES,
3663 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3664 );
3665 $otherTags = array_merge( $otherTags, $link['html'] );
3666
3667 // Load the previewed CSS
3668 // If needed, Janus it first. This is user-supplied CSS, so it's
3669 // assumed to be right for the content language directionality.
3670 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3671 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3672 $previewedCSS = CSSJanus::transform( $previewedCSS, true, false );
3673 }
3674 $otherTags[] = Html::inlineStyle( $previewedCSS ) . "\n";
3675 } else {
3676 // Load the user styles normally
3677 $moduleStyles[] = 'user';
3678 }
3679
3680 // Per-user preference styles
3681 $moduleStyles[] = 'user.cssprefs';
3682
3683 foreach ( $moduleStyles as $name ) {
3684 $module = $resourceLoader->getModule( $name );
3685 if ( !$module ) {
3686 continue;
3687 }
3688 if ( $name === 'site' ) {
3689 // HACK: The site module shouldn't be fragmented with a cache group and
3690 // http request. But in order to ensure its styles are separated and after the
3691 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3692 // The scripts remain ungrouped and rides the bottom queue.
3693 $styles['site'][] = $name;
3694 continue;
3695 }
3696 $group = $module->getGroup();
3697 // Modules in groups other than the ones needing special treatment (see $styles assignment)
3698 // will be placed in the "other" style category.
3699 $styles[isset( $styles[$group] ) ? $group : 'other'][] = $name;
3700 }
3701
3702 // We want site, private and user styles to override dynamically added
3703 // styles from modules, but we want dynamically added styles to override
3704 // statically added styles from other modules. So the order has to be
3705 // other, dynamic, site, private, user. Add statically added styles for
3706 // other modules
3707 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule::TYPE_STYLES );
3708 // Add normal styles added through addStyle()/addInlineStyle() here
3709 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles;
3710 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3711 // We use a <meta> tag with a made-up name for this because that's valid HTML
3712 $links[] = Html::element(
3713 'meta',
3714 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3715 );
3716
3717 // Add site-specific and user-specific styles
3718 // 'private' at present only contains user.options, so put that before 'user'
3719 // Any future private modules will likely have a similar user-specific character
3720 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3721 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3722 ResourceLoaderModule::TYPE_STYLES
3723 );
3724 }
3725
3726 // Add stuff in $otherTags (previewed user CSS if applicable)
3727 return self::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3728 }
3729
3730 /**
3731 * @return array
3732 */
3733 public function buildCssLinksArray() {
3734 $links = array();
3735
3736 // Add any extension CSS
3737 foreach ( $this->mExtStyles as $url ) {
3738 $this->addStyle( $url );
3739 }
3740 $this->mExtStyles = array();
3741
3742 foreach ( $this->styles as $file => $options ) {
3743 $link = $this->styleLink( $file, $options );
3744 if ( $link ) {
3745 $links[$file] = $link;
3746 }
3747 }
3748 return $links;
3749 }
3750
3751 /**
3752 * Generate \<link\> tags for stylesheets
3753 *
3754 * @param string $style URL to the file
3755 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3756 * @return string HTML fragment
3757 */
3758 protected function styleLink( $style, array $options ) {
3759 if ( isset( $options['dir'] ) ) {
3760 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3761 return '';
3762 }
3763 }
3764
3765 if ( isset( $options['media'] ) ) {
3766 $media = self::transformCssMedia( $options['media'] );
3767 if ( is_null( $media ) ) {
3768 return '';
3769 }
3770 } else {
3771 $media = 'all';
3772 }
3773
3774 if ( substr( $style, 0, 1 ) == '/' ||
3775 substr( $style, 0, 5 ) == 'http:' ||
3776 substr( $style, 0, 6 ) == 'https:' ) {
3777 $url = $style;
3778 } else {
3779 $config = $this->getConfig();
3780 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3781 }
3782
3783 $link = Html::linkedStyle( $url, $media );
3784
3785 if ( isset( $options['condition'] ) ) {
3786 $condition = htmlspecialchars( $options['condition'] );
3787 $link = "<!--[if $condition]>$link<![endif]-->";
3788 }
3789 return $link;
3790 }
3791
3792 /**
3793 * Transform "media" attribute based on request parameters
3794 *
3795 * @param string $media Current value of the "media" attribute
3796 * @return string Modified value of the "media" attribute, or null to skip
3797 * this stylesheet
3798 */
3799 public static function transformCssMedia( $media ) {
3800 global $wgRequest;
3801
3802 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3803 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3804
3805 // Switch in on-screen display for media testing
3806 $switches = array(
3807 'printable' => 'print',
3808 'handheld' => 'handheld',
3809 );
3810 foreach ( $switches as $switch => $targetMedia ) {
3811 if ( $wgRequest->getBool( $switch ) ) {
3812 if ( $media == $targetMedia ) {
3813 $media = '';
3814 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3815 // This regex will not attempt to understand a comma-separated media_query_list
3816 //
3817 // Example supported values for $media:
3818 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3819 // Example NOT supported value for $media:
3820 // '3d-glasses, screen, print and resolution > 90dpi'
3821 //
3822 // If it's a print request, we never want any kind of screen stylesheets
3823 // If it's a handheld request (currently the only other choice with a switch),
3824 // we don't want simple 'screen' but we might want screen queries that
3825 // have a max-width or something, so we'll pass all others on and let the
3826 // client do the query.
3827 if ( $targetMedia == 'print' || $media == 'screen' ) {
3828 return null;
3829 }
3830 }
3831 }
3832 }
3833
3834 return $media;
3835 }
3836
3837 /**
3838 * Add a wikitext-formatted message to the output.
3839 * This is equivalent to:
3840 *
3841 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3842 */
3843 public function addWikiMsg( /*...*/ ) {
3844 $args = func_get_args();
3845 $name = array_shift( $args );
3846 $this->addWikiMsgArray( $name, $args );
3847 }
3848
3849 /**
3850 * Add a wikitext-formatted message to the output.
3851 * Like addWikiMsg() except the parameters are taken as an array
3852 * instead of a variable argument list.
3853 *
3854 * @param string $name
3855 * @param array $args
3856 */
3857 public function addWikiMsgArray( $name, $args ) {
3858 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3859 }
3860
3861 /**
3862 * This function takes a number of message/argument specifications, wraps them in
3863 * some overall structure, and then parses the result and adds it to the output.
3864 *
3865 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3866 * and so on. The subsequent arguments may be either
3867 * 1) strings, in which case they are message names, or
3868 * 2) arrays, in which case, within each array, the first element is the message
3869 * name, and subsequent elements are the parameters to that message.
3870 *
3871 * Don't use this for messages that are not in the user's interface language.
3872 *
3873 * For example:
3874 *
3875 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3876 *
3877 * Is equivalent to:
3878 *
3879 * $wgOut->addWikiText( "<div class='error'>\n"
3880 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3881 *
3882 * The newline after the opening div is needed in some wikitext. See bug 19226.
3883 *
3884 * @param string $wrap
3885 */
3886 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3887 $msgSpecs = func_get_args();
3888 array_shift( $msgSpecs );
3889 $msgSpecs = array_values( $msgSpecs );
3890 $s = $wrap;
3891 foreach ( $msgSpecs as $n => $spec ) {
3892 if ( is_array( $spec ) ) {
3893 $args = $spec;
3894 $name = array_shift( $args );
3895 if ( isset( $args['options'] ) ) {
3896 unset( $args['options'] );
3897 wfDeprecated(
3898 'Adding "options" to ' . __METHOD__ . ' is no longer supported',
3899 '1.20'
3900 );
3901 }
3902 } else {
3903 $args = array();
3904 $name = $spec;
3905 }
3906 $s = str_replace( '$' . ( $n + 1 ), $this->msg( $name, $args )->plain(), $s );
3907 }
3908 $this->addWikiText( $s );
3909 }
3910
3911 /**
3912 * Include jQuery core. Use this to avoid loading it multiple times
3913 * before we get a usable script loader.
3914 *
3915 * @param array $modules List of jQuery modules which should be loaded
3916 * @return array The list of modules which were not loaded.
3917 * @since 1.16
3918 * @deprecated since 1.17
3919 */
3920 public function includeJQuery( array $modules = array() ) {
3921 return array();
3922 }
3923
3924 /**
3925 * Enables/disables TOC, doesn't override __NOTOC__
3926 * @param bool $flag
3927 * @since 1.22
3928 */
3929 public function enableTOC( $flag = true ) {
3930 $this->mEnableTOC = $flag;
3931 }
3932
3933 /**
3934 * @return bool
3935 * @since 1.22
3936 */
3937 public function isTOCEnabled() {
3938 return $this->mEnableTOC;
3939 }
3940
3941 /**
3942 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3943 * @param bool $flag
3944 * @since 1.23
3945 */
3946 public function enableSectionEditLinks( $flag = true ) {
3947 $this->mEnableSectionEditLinks = $flag;
3948 }
3949
3950 /**
3951 * @return bool
3952 * @since 1.23
3953 */
3954 public function sectionEditLinksEnabled() {
3955 return $this->mEnableSectionEditLinks;
3956 }
3957
3958 /**
3959 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3960 * MediaWiki and this OutputPage instance.
3961 *
3962 * @since 1.25
3963 */
3964 public function enableOOUI() {
3965 $themes = ExtensionRegistry::getInstance()->getAttribute( 'SkinOOUIThemes' );
3966 // Make keys (skin names) lowercase for case-insensitive matching.
3967 $themes = array_change_key_case( $themes, CASE_LOWER );
3968 $skinName = strtolower( $this->getSkin()->getSkinName() );
3969 $theme = isset( $themes[ $skinName ] ) ? $themes[ $skinName ] : 'MediaWiki';
3970 // For example, 'OOUI\MediaWikiTheme'.
3971 $themeClass = "OOUI\\{$theme}Theme";
3972 OOUI\Theme::setSingleton( new $themeClass() );
3973 OOUI\Element::setDefaultDir( $this->getLanguage()->getDir() );
3974 $this->addModuleStyles( array(
3975 'oojs-ui.styles',
3976 'oojs-ui.styles.icons',
3977 'oojs-ui.styles.indicators',
3978 'oojs-ui.styles.textures',
3979 'mediawiki.widgets.styles',
3980 ) );
3981 }
3982 }