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