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