3 * Preparation for the final page rendering.
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.
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.
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
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.
28 * This class is used to prepare the final rendering. A skin is then
29 * applied to the output parameters (links, javascript, html, categories ...).
31 * @todo FIXME: Another class handles sending the whole page to the client.
33 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
38 class OutputPage
extends ContextSource
{
39 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
40 protected $mMetatags = array();
43 protected $mLinktags = array();
46 protected $mCanonicalUrl = false;
49 * @var array Additional stylesheets. Looks like this is for extensions.
50 * Might be replaced by resource loader.
52 protected $mExtStyles = array();
55 * @var string Should be private - has getter and setter. Contains
57 public $mPagetitle = '';
60 * @var string Contains all of the "<body>" content. Should be private we
61 * got set/get accessors and the append() method.
63 public $mBodytext = '';
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.
70 public $mDebugtext = '';
72 /** @var string Stores contents of "<title>" tag */
73 private $mHTMLtitle = '';
76 * @var bool Is the displayed content related to the source of the
77 * corresponding wiki article.
79 private $mIsarticle = false;
81 /** @var bool Stores "article flag" toggle. */
82 private $mIsArticleRelated = true;
85 * @var bool We have to set isPrintable(). Some pages should
86 * never be printed (ex: redirections).
88 private $mPrintable = false;
91 * @var array Contains the page subtitle. Special pages usually have some
92 * links here. Don't confuse with site subtitle added by skins.
94 private $mSubtitle = array();
97 public $mRedirect = '';
100 protected $mStatusCode;
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.
106 protected $mLastModified = '';
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.
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
117 private $mETag = false;
120 protected $mCategoryLinks = array();
123 protected $mCategories = array();
126 protected $mIndicators = array();
128 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
129 private $mLanguageLinks = array();
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.
137 private $mScripts = '';
139 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
140 protected $mInlineStyles = '';
143 private $mLinkColours;
146 * @var string Used by skin template.
147 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
149 public $mPageLinkTitle = '';
151 /** @var array Array of elements in "<head>". Parser might add its own headers! */
152 protected $mHeadItems = array();
154 // @todo FIXME: Next 5 variables probably come from the resource loader
157 protected $mModules = array();
160 protected $mModuleScripts = array();
163 protected $mModuleStyles = array();
166 protected $mModuleMessages = array();
168 /** @var ResourceLoader */
169 protected $mResourceLoader;
172 protected $mJsConfigVars = array();
175 protected $mTemplateIds = array();
178 protected $mImageTimeKeys = array();
181 public $mRedirectCode = '';
183 protected $mFeedLinksAppendQuery = null;
187 * The level of 'untrustworthiness' allowed for modules loaded on this page.
188 * @see ResourceLoaderModule::$origin
190 protected $mAllowedModuleOrigin = ResourceLoaderModule
::ORIGIN_ALL
;
192 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
193 protected $mDoNothing = false;
201 private $mContainsOldMagic = 0;
204 protected $mContainsNewMagic = 0;
207 * lazy initialised, use parserOptions()
210 protected $mParserOptions = null;
213 * Handles the Atom / RSS links.
214 * We probably only support Atom in 2011.
215 * @see $wgAdvertisedFeedTypes
217 private $mFeedLinks = array();
219 // Gwicke work on squid caching? Roughly from 2003.
220 protected $mEnableClientCache = true;
222 /** @var bool Flag if output should only contain the body of the article. */
223 private $mArticleBodyOnly = false;
226 protected $mNewSectionLink = false;
229 protected $mHideNewSectionLink = false;
232 * @var bool Comes from the parser. This was probably made to load CSS/JS
233 * only if we had "<gallery>". Used directly in CategoryPage.php.
234 * Looks like resource loader can replace this.
236 public $mNoGallery = false;
239 private $mPageTitleActionText = '';
242 private $mParseWarnings = array();
244 /** @var int Cache stuff. Looks like mEnableClientCache */
245 protected $mSquidMaxage = 0;
251 protected $mPreventClickjacking = true;
253 /** @var int To include the variable {{REVISIONID}} */
254 private $mRevisionId = null;
257 private $mRevisionTimestamp = null;
260 protected $mFileVersion = null;
263 * @var array An array of stylesheet filenames (relative from skins path),
264 * with options for CSS media, IE conditions, and RTL/LTR direction.
265 * For internal use; add settings in the skin via $this->addStyle()
267 * Style again! This seems like a code duplication since we already have
268 * mStyles. This is what makes Open Source amazing.
270 protected $styles = array();
273 * Whether jQuery is already handled.
275 protected $mJQueryDone = false;
277 private $mIndexPolicy = 'index';
278 private $mFollowPolicy = 'follow';
279 private $mVaryHeader = array(
280 'Accept-Encoding' => array( 'list-contains=gzip' ),
284 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
289 private $mRedirectedFrom = null;
292 * Additional key => value data
294 private $mProperties = array();
297 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
299 private $mTarget = null;
302 * @var bool Whether parser output should contain table of contents
304 private $mEnableTOC = true;
307 * @var bool Whether parser output should contain section edit links
309 private $mEnableSectionEditLinks = true;
312 * Constructor for OutputPage. This should not be called directly.
313 * Instead a new RequestContext should be created and it will implicitly create
314 * a OutputPage tied to that context.
315 * @param IContextSource|null $context
317 function __construct( IContextSource
$context = null ) {
318 if ( $context === null ) {
319 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
320 wfDeprecated( __METHOD__
, '1.18' );
322 $this->setContext( $context );
327 * Redirect to $url rather than displaying the normal page
329 * @param string $url URL
330 * @param string $responsecode HTTP status code
332 public function redirect( $url, $responsecode = '302' ) {
333 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
334 $this->mRedirect
= str_replace( "\n", '', $url );
335 $this->mRedirectCode
= $responsecode;
339 * Get the URL to redirect to, or an empty string if not redirect URL set
343 public function getRedirect() {
344 return $this->mRedirect
;
348 * Set the HTTP status code to send with the output.
350 * @param int $statusCode
352 public function setStatusCode( $statusCode ) {
353 $this->mStatusCode
= $statusCode;
357 * Add a new "<meta>" tag
358 * To add an http-equiv meta tag, precede the name with "http:"
360 * @param string $name Tag name
361 * @param string $val Tag value
363 function addMeta( $name, $val ) {
364 array_push( $this->mMetatags
, array( $name, $val ) );
368 * Add a new \<link\> tag to the page header.
370 * Note: use setCanonicalUrl() for rel=canonical.
372 * @param array $linkarr Associative array of attributes.
374 function addLink( array $linkarr ) {
375 array_push( $this->mLinktags
, $linkarr );
379 * Add a new \<link\> with "rel" attribute set to "meta"
381 * @param array $linkarr Associative array mapping attribute names to their
382 * values, both keys and values will be escaped, and the
383 * "rel" attribute will be automatically added
385 function addMetadataLink( array $linkarr ) {
386 $linkarr['rel'] = $this->getMetadataAttribute();
387 $this->addLink( $linkarr );
391 * Set the URL to be used for the <link rel=canonical>. This should be used
392 * in preference to addLink(), to avoid duplicate link tags.
395 function setCanonicalUrl( $url ) {
396 $this->mCanonicalUrl
= $url;
400 * Get the value of the "rel" attribute for metadata links
404 public function getMetadataAttribute() {
405 # note: buggy CC software only reads first "meta" link
406 static $haveMeta = false;
408 return 'alternate meta';
416 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
418 * @param string $script Raw HTML
420 function addScript( $script ) {
421 $this->mScripts
.= $script . "\n";
425 * Register and add a stylesheet from an extension directory.
427 * @param string $url Path to sheet. Provide either a full url (beginning
428 * with 'http', etc) or a relative path from the document root
429 * (beginning with '/'). Otherwise it behaves identically to
430 * addStyle() and draws from the /skins folder.
432 public function addExtensionStyle( $url ) {
433 array_push( $this->mExtStyles
, $url );
437 * Get all styles added by extensions
441 function getExtStyle() {
442 return $this->mExtStyles
;
446 * Add a JavaScript file out of skins/common, or a given relative path.
448 * @param string $file Filename in skins/common or complete on-server path
450 * @param string $version Style version of the file. Defaults to $wgStyleVersion
452 public function addScriptFile( $file, $version = null ) {
453 // See if $file parameter is an absolute URL or begins with a slash
454 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
457 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
459 if ( is_null( $version ) ) {
460 $version = $this->getConfig()->get( 'StyleVersion' );
462 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
466 * Add a self-contained script tag with the given contents
468 * @param string $script JavaScript text, no "<script>" tags
470 public function addInlineScript( $script ) {
471 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
475 * Get all registered JS and CSS tags for the header.
478 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
480 function getScript() {
481 wfDeprecated( __METHOD__
, '1.24' );
482 return $this->mScripts
. $this->getHeadItems();
486 * Filter an array of modules to remove insufficiently trustworthy members, and modules
487 * which are no longer registered (eg a page is cached before an extension is disabled)
488 * @param array $modules
489 * @param string|null $position If not null, only return modules with this position
490 * @param string $type
493 protected function filterModules( array $modules, $position = null,
494 $type = ResourceLoaderModule
::TYPE_COMBINED
496 $resourceLoader = $this->getResourceLoader();
497 $filteredModules = array();
498 foreach ( $modules as $val ) {
499 $module = $resourceLoader->getModule( $val );
500 if ( $module instanceof ResourceLoaderModule
501 && $module->getOrigin() <= $this->getAllowedModules( $type )
502 && ( is_null( $position ) ||
$module->getPosition() == $position )
503 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
505 $filteredModules[] = $val;
508 return $filteredModules;
512 * Get the list of modules to include on this page
514 * @param bool $filter Whether to filter out insufficiently trustworthy modules
515 * @param string|null $position If not null, only return modules with this position
516 * @param string $param
517 * @return array Array of module names
519 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
520 $modules = array_values( array_unique( $this->$param ) );
522 ?
$this->filterModules( $modules, $position )
527 * Add one or more modules recognized by the resource loader. Modules added
528 * through this function will be loaded by the resource loader when the
531 * @param string|array $modules Module name (string) or array of module names
533 public function addModules( $modules ) {
534 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
538 * Get the list of module JS to include on this page
540 * @param bool $filter
541 * @param string|null $position
543 * @return array Array of module names
545 public function getModuleScripts( $filter = false, $position = null ) {
546 return $this->getModules( $filter, $position, 'mModuleScripts' );
550 * Add only JS of one or more modules recognized by the resource loader. Module
551 * scripts added through this function will be loaded by the resource loader when
554 * @param string|array $modules Module name (string) or array of module names
556 public function addModuleScripts( $modules ) {
557 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
561 * Get the list of module CSS to include on this page
563 * @param bool $filter
564 * @param string|null $position
566 * @return array Array of module names
568 public function getModuleStyles( $filter = false, $position = null ) {
569 return $this->getModules( $filter, $position, 'mModuleStyles' );
573 * Add only CSS of one or more modules recognized by the resource loader.
575 * Module styles added through this function will be added using standard link CSS
576 * tags, rather than as a combined Javascript and CSS package. Thus, they will
577 * load when JavaScript is disabled (unless CSS also happens to be disabled).
579 * @param string|array $modules Module name (string) or array of module names
581 public function addModuleStyles( $modules ) {
582 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
586 * Get the list of module messages to include on this page
588 * @param bool $filter
589 * @param string|null $position
591 * @return array Array of module names
593 public function getModuleMessages( $filter = false, $position = null ) {
594 return $this->getModules( $filter, $position, 'mModuleMessages' );
598 * Add only messages of one or more modules recognized by the resource loader.
599 * Module messages added through this function will be loaded by the resource
600 * loader when the page loads.
602 * @param string|array $modules Module name (string) or array of module names
604 public function addModuleMessages( $modules ) {
605 $this->mModuleMessages
= array_merge( $this->mModuleMessages
, (array)$modules );
609 * @return null|string ResourceLoader target
611 public function getTarget() {
612 return $this->mTarget
;
616 * Sets ResourceLoader target for load.php links. If null, will be omitted
618 * @param string|null $target
620 public function setTarget( $target ) {
621 $this->mTarget
= $target;
625 * Get an array of head items
629 function getHeadItemsArray() {
630 return $this->mHeadItems
;
634 * Get all header items in a string
637 * @deprecated since 1.24 Use OutputPage::headElement or
638 * if absolutely necessary use OutputPage::getHeadItemsArray
640 function getHeadItems() {
641 wfDeprecated( __METHOD__
, '1.24' );
643 foreach ( $this->mHeadItems
as $item ) {
650 * Add or replace an header item to the output
652 * @param string $name Item name
653 * @param string $value Raw HTML
655 public function addHeadItem( $name, $value ) {
656 $this->mHeadItems
[$name] = $value;
660 * Check if the header item $name is already set
662 * @param string $name Item name
665 public function hasHeadItem( $name ) {
666 return isset( $this->mHeadItems
[$name] );
670 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
672 * @param string $tag Value of "ETag" header
674 function setETag( $tag ) {
679 * Set whether the output should only contain the body of the article,
680 * without any skin, sidebar, etc.
681 * Used e.g. when calling with "action=render".
683 * @param bool $only Whether to output only the body of the article
685 public function setArticleBodyOnly( $only ) {
686 $this->mArticleBodyOnly
= $only;
690 * Return whether the output will contain only the body of the article
694 public function getArticleBodyOnly() {
695 return $this->mArticleBodyOnly
;
699 * Set an additional output property
702 * @param string $name
703 * @param mixed $value
705 public function setProperty( $name, $value ) {
706 $this->mProperties
[$name] = $value;
710 * Get an additional output property
713 * @param string $name
714 * @return mixed Property value or null if not found
716 public function getProperty( $name ) {
717 if ( isset( $this->mProperties
[$name] ) ) {
718 return $this->mProperties
[$name];
725 * checkLastModified tells the client to use the client-cached page if
726 * possible. If successful, the OutputPage is disabled so that
727 * any future call to OutputPage->output() have no effect.
729 * Side effect: sets mLastModified for Last-Modified header
731 * @param string $timestamp
733 * @return bool True if cache-ok headers was sent.
735 public function checkLastModified( $timestamp ) {
736 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
737 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
740 $config = $this->getConfig();
741 if ( !$config->get( 'CachePages' ) ) {
742 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
746 $timestamp = wfTimestamp( TS_MW
, $timestamp );
747 $modifiedTimes = array(
748 'page' => $timestamp,
749 'user' => $this->getUser()->getTouched(),
750 'epoch' => $config->get( 'CacheEpoch' )
752 if ( $config->get( 'UseSquid' ) ) {
753 // bug 44570: the core page itself may not change, but resources might
754 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
756 wfRunHooks( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
758 $maxModified = max( $modifiedTimes );
759 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
761 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
762 if ( $clientHeader === false ) {
763 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
767 # IE sends sizes after the date like this:
768 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
769 # this breaks strtotime().
770 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
772 wfSuppressWarnings(); // E_STRICT system time bitching
773 $clientHeaderTime = strtotime( $clientHeader );
775 if ( !$clientHeaderTime ) {
777 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
780 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
784 foreach ( $modifiedTimes as $name => $value ) {
785 if ( $info !== '' ) {
788 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
791 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
792 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
793 wfDebug( __METHOD__
. ": effective Last-Modified: " .
794 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
795 if ( $clientHeaderTime < $maxModified ) {
796 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
801 # Give a 304 response code and disable body output
802 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
803 ini_set( 'zlib.output_compression', 0 );
804 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
805 $this->sendCacheControl();
808 // Don't output a compressed blob when using ob_gzhandler;
809 // it's technically against HTTP spec and seems to confuse
810 // Firefox when the response gets split over two packets.
811 wfClearOutputBuffers();
817 * Override the last modified timestamp
819 * @param string $timestamp New timestamp, in a format readable by
822 public function setLastModified( $timestamp ) {
823 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
827 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
829 * @param string $policy The literal string to output as the contents of
830 * the meta tag. Will be parsed according to the spec and output in
834 public function setRobotPolicy( $policy ) {
835 $policy = Article
::formatRobotPolicy( $policy );
837 if ( isset( $policy['index'] ) ) {
838 $this->setIndexPolicy( $policy['index'] );
840 if ( isset( $policy['follow'] ) ) {
841 $this->setFollowPolicy( $policy['follow'] );
846 * Set the index policy for the page, but leave the follow policy un-
849 * @param string $policy Either 'index' or 'noindex'.
852 public function setIndexPolicy( $policy ) {
853 $policy = trim( $policy );
854 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
855 $this->mIndexPolicy
= $policy;
860 * Set the follow policy for the page, but leave the index policy un-
863 * @param string $policy Either 'follow' or 'nofollow'.
866 public function setFollowPolicy( $policy ) {
867 $policy = trim( $policy );
868 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
869 $this->mFollowPolicy
= $policy;
874 * Set the new value of the "action text", this will be added to the
875 * "HTML title", separated from it with " - ".
877 * @param string $text New value of the "action text"
879 public function setPageTitleActionText( $text ) {
880 $this->mPageTitleActionText
= $text;
884 * Get the value of the "action text"
888 public function getPageTitleActionText() {
889 return $this->mPageTitleActionText
;
893 * "HTML title" means the contents of "<title>".
894 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
896 * @param string|Message $name
898 public function setHTMLTitle( $name ) {
899 if ( $name instanceof Message
) {
900 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
902 $this->mHTMLtitle
= $name;
907 * Return the "HTML title", i.e. the content of the "<title>" tag.
911 public function getHTMLTitle() {
912 return $this->mHTMLtitle
;
916 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
920 public function setRedirectedFrom( $t ) {
921 $this->mRedirectedFrom
= $t;
925 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
926 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
927 * but not bad tags like \<script\>. This function automatically sets
928 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
929 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
930 * good tags like \<i\> will be dropped entirely.
932 * @param string|Message $name
934 public function setPageTitle( $name ) {
935 if ( $name instanceof Message
) {
936 $name = $name->setContext( $this->getContext() )->text();
939 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
940 # but leave "<i>foobar</i>" alone
941 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
942 $this->mPagetitle
= $nameWithTags;
944 # change "<i>foo&bar</i>" to "foo&bar"
946 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
947 ->inContentLanguage()
952 * Return the "page title", i.e. the content of the \<h1\> tag.
956 public function getPageTitle() {
957 return $this->mPagetitle
;
961 * Set the Title object to use
965 public function setTitle( Title
$t ) {
966 $this->getContext()->setTitle( $t );
970 * Replace the subtitle with $str
972 * @param string|Message $str New value of the subtitle. String should be safe HTML.
974 public function setSubtitle( $str ) {
975 $this->clearSubtitle();
976 $this->addSubtitle( $str );
980 * Add $str to the subtitle
982 * @deprecated since 1.19; use addSubtitle() instead
983 * @param string|Message $str String or Message to add to the subtitle
985 public function appendSubtitle( $str ) {
986 $this->addSubtitle( $str );
990 * Add $str to the subtitle
992 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
994 public function addSubtitle( $str ) {
995 if ( $str instanceof Message
) {
996 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
998 $this->mSubtitle
[] = $str;
1003 * Add a subtitle containing a backlink to a page
1005 * @param Title $title Title to link to
1006 * @param array $query Array of additional parameters to include in the link
1008 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1009 if ( $title->isRedirect() ) {
1010 $query['redirect'] = 'no';
1012 $this->addSubtitle( $this->msg( 'backlinksubtitle' )
1013 ->rawParams( Linker
::link( $title, null, array(), $query ) ) );
1017 * Clear the subtitles
1019 public function clearSubtitle() {
1020 $this->mSubtitle
= array();
1028 public function getSubtitle() {
1029 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1033 * Set the page as printable, i.e. it'll be displayed with with all
1034 * print styles included
1036 public function setPrintable() {
1037 $this->mPrintable
= true;
1041 * Return whether the page is "printable"
1045 public function isPrintable() {
1046 return $this->mPrintable
;
1050 * Disable output completely, i.e. calling output() will have no effect
1052 public function disable() {
1053 $this->mDoNothing
= true;
1057 * Return whether the output will be completely disabled
1061 public function isDisabled() {
1062 return $this->mDoNothing
;
1066 * Show an "add new section" link?
1070 public function showNewSectionLink() {
1071 return $this->mNewSectionLink
;
1075 * Forcibly hide the new section link?
1079 public function forceHideNewSectionLink() {
1080 return $this->mHideNewSectionLink
;
1084 * Add or remove feed links in the page header
1085 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1086 * for the new version
1087 * @see addFeedLink()
1089 * @param bool $show True: add default feeds, false: remove all feeds
1091 public function setSyndicated( $show = true ) {
1093 $this->setFeedAppendQuery( false );
1095 $this->mFeedLinks
= array();
1100 * Add default feeds to the page header
1101 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1102 * for the new version
1103 * @see addFeedLink()
1105 * @param string $val Query to append to feed links or false to output
1108 public function setFeedAppendQuery( $val ) {
1109 $this->mFeedLinks
= array();
1111 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1112 $query = "feed=$type";
1113 if ( is_string( $val ) ) {
1114 $query .= '&' . $val;
1116 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1121 * Add a feed link to the page header
1123 * @param string $format Feed type, should be a key of $wgFeedClasses
1124 * @param string $href URL
1126 public function addFeedLink( $format, $href ) {
1127 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1128 $this->mFeedLinks
[$format] = $href;
1133 * Should we output feed links for this page?
1136 public function isSyndicated() {
1137 return count( $this->mFeedLinks
) > 0;
1141 * Return URLs for each supported syndication format for this page.
1142 * @return array Associating format keys with URLs
1144 public function getSyndicationLinks() {
1145 return $this->mFeedLinks
;
1149 * Will currently always return null
1153 public function getFeedAppendQuery() {
1154 return $this->mFeedLinksAppendQuery
;
1158 * Set whether the displayed content is related to the source of the
1159 * corresponding article on the wiki
1160 * Setting true will cause the change "article related" toggle to true
1164 public function setArticleFlag( $v ) {
1165 $this->mIsarticle
= $v;
1167 $this->mIsArticleRelated
= $v;
1172 * Return whether the content displayed page is related to the source of
1173 * the corresponding article on the wiki
1177 public function isArticle() {
1178 return $this->mIsarticle
;
1182 * Set whether this page is related an article on the wiki
1183 * Setting false will cause the change of "article flag" toggle to false
1187 public function setArticleRelated( $v ) {
1188 $this->mIsArticleRelated
= $v;
1190 $this->mIsarticle
= false;
1195 * Return whether this page is related an article on the wiki
1199 public function isArticleRelated() {
1200 return $this->mIsArticleRelated
;
1204 * Add new language links
1206 * @param array $newLinkArray Associative array mapping language code to the page
1209 public function addLanguageLinks( array $newLinkArray ) {
1210 $this->mLanguageLinks +
= $newLinkArray;
1214 * Reset the language links and add new language links
1216 * @param array $newLinkArray Associative array mapping language code to the page
1219 public function setLanguageLinks( array $newLinkArray ) {
1220 $this->mLanguageLinks
= $newLinkArray;
1224 * Get the list of language links
1226 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1228 public function getLanguageLinks() {
1229 return $this->mLanguageLinks
;
1233 * Add an array of categories, with names in the keys
1235 * @param array $categories Mapping category name => sort key
1237 public function addCategoryLinks( array $categories ) {
1240 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1244 # Add the links to a LinkBatch
1245 $arr = array( NS_CATEGORY
=> $categories );
1246 $lb = new LinkBatch
;
1247 $lb->setArray( $arr );
1249 # Fetch existence plus the hiddencat property
1250 $dbr = wfGetDB( DB_SLAVE
);
1251 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1252 'page_is_redirect', 'page_latest', 'pp_value' );
1254 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1255 $fields[] = 'page_content_model';
1258 $res = $dbr->select( array( 'page', 'page_props' ),
1260 $lb->constructSet( 'page', $dbr ),
1263 array( 'page_props' => array( 'LEFT JOIN', array(
1264 'pp_propname' => 'hiddencat',
1269 # Add the results to the link cache
1270 $lb->addResultToCache( LinkCache
::singleton(), $res );
1272 # Set all the values to 'normal'.
1273 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1275 # Mark hidden categories
1276 foreach ( $res as $row ) {
1277 if ( isset( $row->pp_value
) ) {
1278 $categories[$row->page_title
] = 'hidden';
1282 # Add the remaining categories to the skin
1284 'OutputPageMakeCategoryLinks',
1285 array( &$this, $categories, &$this->mCategoryLinks
) )
1287 foreach ( $categories as $category => $type ) {
1288 $origcategory = $category;
1289 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1293 $wgContLang->findVariantLink( $category, $title, true );
1294 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1297 $text = $wgContLang->convertHtml( $title->getText() );
1298 $this->mCategories
[] = $title->getText();
1299 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1305 * Reset the category links (but not the category list) and add $categories
1307 * @param array $categories Mapping category name => sort key
1309 public function setCategoryLinks( array $categories ) {
1310 $this->mCategoryLinks
= array();
1311 $this->addCategoryLinks( $categories );
1315 * Get the list of category links, in a 2-D array with the following format:
1316 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1317 * hidden categories) and $link a HTML fragment with a link to the category
1322 public function getCategoryLinks() {
1323 return $this->mCategoryLinks
;
1327 * Get the list of category names this page belongs to
1329 * @return array Array of strings
1331 public function getCategories() {
1332 return $this->mCategories
;
1336 * Add an array of indicators, with their identifiers as array keys and HTML contents as values.
1338 * In case of duplicate keys, existing values are overwritten.
1340 * @param array $indicators
1343 public function setIndicators( array $indicators ) {
1344 $this->mIndicators
= $indicators +
$this->mIndicators
;
1345 // Keep ordered by key
1346 ksort( $this->mIndicators
);
1350 * Get the indicators associated with this page.
1352 * The array will be internally ordered by item keys.
1354 * @return array Keys: identifiers, values: HTML contents
1357 public function getIndicators() {
1358 return $this->mIndicators
;
1362 * Restrict the page to loading modules bundled the software.
1364 * Disallows the queue to contain any modules which can be modified by wiki
1365 * users to load on this page.
1367 public function disallowUserJs() {
1368 $this->reduceAllowedModuleOrigin( ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
);
1372 * Get the level of JavaScript / CSS untrustworthiness allowed on this page.
1374 * @see ResourceLoaderModule::$origin
1375 * @param string $type Unused: Module origin allowance used to be fragmented by
1376 * ResourceLoaderModule TYPE_ constants.
1377 * @return int ResourceLoaderModule ORIGIN_ class constant
1379 public function getAllowedModules( $type = null ) {
1380 return $this->mAllowedModuleOrigin
;
1384 * Set the highest level of CSS/JS untrustworthiness allowed
1386 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1387 * Use reduceAllowedModuleOrigin() instead.
1389 * @param string $type ResourceLoaderModule TYPE_ constant
1390 * @param int $level ResourceLoaderModule ORIGIN_ constant
1392 public function setAllowedModules( $type, $level ) {
1393 wfDeprecated( __METHOD__
, '1.24' );
1394 $this->reduceAllowedModuleOrigin( $level );
1398 * Limit the highest level of CSS/JS untrustworthiness allowed.
1400 * @deprecated since 1.24 Module allowance is no longer fragmented by content type.
1401 * Use reduceAllowedModuleOrigin() instead.
1403 * @param string $type ResourceLoaderModule TYPE_ constant
1404 * @param int $level ResourceLoaderModule ORIGIN_ class constant
1406 public function reduceAllowedModules( $type, $level ) {
1407 wfDeprecated( __METHOD__
, '1.24' );
1408 $this->reduceAllowedModuleOrigin( $level );
1412 * Limit the highest level of CSS/JS untrustworthiness allowed.
1414 * If passed the same or a higher level than the current level of untrustworthiness set, the
1415 * level will remain unchanged.
1417 * @param int $level ResourceLoaderModule class constant
1419 public function reduceAllowedModuleOrigin( $level ) {
1420 $this->mAllowedModuleOrigin
= min( $this->mAllowedModuleOrigin
, $level );
1424 * Prepend $text to the body HTML
1426 * @param string $text HTML
1428 public function prependHTML( $text ) {
1429 $this->mBodytext
= $text . $this->mBodytext
;
1433 * Append $text to the body HTML
1435 * @param string $text HTML
1437 public function addHTML( $text ) {
1438 $this->mBodytext
.= $text;
1442 * Shortcut for adding an Html::element via addHTML.
1446 * @param string $element
1447 * @param array $attribs
1448 * @param string $contents
1450 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1451 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1455 * Clear the body HTML
1457 public function clearHTML() {
1458 $this->mBodytext
= '';
1464 * @return string HTML
1466 public function getHTML() {
1467 return $this->mBodytext
;
1471 * Get/set the ParserOptions object to use for wikitext parsing
1473 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1474 * current ParserOption object
1475 * @return ParserOptions
1477 public function parserOptions( $options = null ) {
1478 if ( !$this->mParserOptions
) {
1479 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1480 $this->mParserOptions
->setEditSection( false );
1482 return wfSetVar( $this->mParserOptions
, $options );
1486 * Set the revision ID which will be seen by the wiki text parser
1487 * for things such as embedded {{REVISIONID}} variable use.
1489 * @param int|null $revid An positive integer, or null
1490 * @return mixed Previous value
1492 public function setRevisionId( $revid ) {
1493 $val = is_null( $revid ) ?
null : intval( $revid );
1494 return wfSetVar( $this->mRevisionId
, $val );
1498 * Get the displayed revision ID
1502 public function getRevisionId() {
1503 return $this->mRevisionId
;
1507 * Set the timestamp of the revision which will be displayed. This is used
1508 * to avoid a extra DB call in Skin::lastModified().
1510 * @param string|null $timestamp
1511 * @return mixed Previous value
1513 public function setRevisionTimestamp( $timestamp ) {
1514 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1518 * Get the timestamp of displayed revision.
1519 * This will be null if not filled by setRevisionTimestamp().
1521 * @return string|null
1523 public function getRevisionTimestamp() {
1524 return $this->mRevisionTimestamp
;
1528 * Set the displayed file version
1530 * @param File|bool $file
1531 * @return mixed Previous value
1533 public function setFileVersion( $file ) {
1535 if ( $file instanceof File
&& $file->exists() ) {
1536 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1538 return wfSetVar( $this->mFileVersion
, $val, true );
1542 * Get the displayed file version
1544 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1546 public function getFileVersion() {
1547 return $this->mFileVersion
;
1551 * Get the templates used on this page
1553 * @return array (namespace => dbKey => revId)
1556 public function getTemplateIds() {
1557 return $this->mTemplateIds
;
1561 * Get the files used on this page
1563 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1566 public function getFileSearchOptions() {
1567 return $this->mImageTimeKeys
;
1571 * Convert wikitext to HTML and add it to the buffer
1572 * Default assumes that the current page title will be used.
1574 * @param string $text
1575 * @param bool $linestart Is this the start of a line?
1576 * @param bool $interface Is this text in the user interface language?
1578 public function addWikiText( $text, $linestart = true, $interface = true ) {
1579 $title = $this->getTitle(); // Work around E_STRICT
1581 throw new MWException( 'Title is null' );
1583 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1587 * Add wikitext with a custom Title object
1589 * @param string $text Wikitext
1590 * @param Title $title
1591 * @param bool $linestart Is this the start of a line?
1593 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1594 $this->addWikiTextTitle( $text, $title, $linestart );
1598 * Add wikitext with a custom Title object and tidy enabled.
1600 * @param string $text Wikitext
1601 * @param Title $title
1602 * @param bool $linestart Is this the start of a line?
1604 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1605 $this->addWikiTextTitle( $text, $title, $linestart, true );
1609 * Add wikitext with tidy enabled
1611 * @param string $text Wikitext
1612 * @param bool $linestart Is this the start of a line?
1614 public function addWikiTextTidy( $text, $linestart = true ) {
1615 $title = $this->getTitle();
1616 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1620 * Add wikitext with a custom Title object
1622 * @param string $text Wikitext
1623 * @param Title $title
1624 * @param bool $linestart Is this the start of a line?
1625 * @param bool $tidy Whether to use tidy
1626 * @param bool $interface Whether it is an interface message
1627 * (for example disables conversion)
1629 public function addWikiTextTitle( $text, Title
$title, $linestart,
1630 $tidy = false, $interface = false
1634 wfProfileIn( __METHOD__
);
1636 $popts = $this->parserOptions();
1637 $oldTidy = $popts->setTidy( $tidy );
1638 $popts->setInterfaceMessage( (bool)$interface );
1640 $parserOutput = $wgParser->getFreshParser()->parse(
1641 $text, $title, $popts,
1642 $linestart, true, $this->mRevisionId
1645 $popts->setTidy( $oldTidy );
1647 $this->addParserOutput( $parserOutput );
1649 wfProfileOut( __METHOD__
);
1653 * Add a ParserOutput object, but without Html.
1655 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1656 * @param ParserOutput $parserOutput
1658 public function addParserOutputNoText( $parserOutput ) {
1659 $this->addParserOutputMetadata( $parserOutput );
1663 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1664 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1668 * @param ParserOutput $parserOutput
1670 public function addParserOutputMetadata( $parserOutput ) {
1671 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1672 $this->addCategoryLinks( $parserOutput->getCategories() );
1673 $this->setIndicators( $parserOutput->getIndicators() );
1674 $this->mNewSectionLink
= $parserOutput->getNewSection();
1675 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1677 $this->mParseWarnings
= $parserOutput->getWarnings();
1678 if ( !$parserOutput->isCacheable() ) {
1679 $this->enableClientCache( false );
1681 $this->mNoGallery
= $parserOutput->getNoGallery();
1682 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1683 $this->addModules( $parserOutput->getModules() );
1684 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1685 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1686 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1687 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1688 $this->mPreventClickjacking
= $this->mPreventClickjacking
1689 ||
$parserOutput->preventClickjacking();
1691 // Template versioning...
1692 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1693 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1694 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1696 $this->mTemplateIds
[$ns] = $dbks;
1699 // File versioning...
1700 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1701 $this->mImageTimeKeys
[$dbk] = $data;
1704 // Hooks registered in the object
1705 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1706 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1707 list( $hookName, $data ) = $hookInfo;
1708 if ( isset( $parserOutputHooks[$hookName] ) ) {
1709 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1713 // Link flags are ignored for now, but may in the future be
1714 // used to mark individual language links.
1715 $linkFlags = array();
1716 wfRunHooks( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1717 wfRunHooks( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1721 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1722 * ParserOutput object, without any other metadata.
1725 * @param ParserOutput $parserOutput
1727 public function addParserOutputContent( $parserOutput ) {
1728 $this->addParserOutputText( $parserOutput );
1730 $this->addModules( $parserOutput->getModules() );
1731 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1732 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1733 $this->addModuleMessages( $parserOutput->getModuleMessages() );
1735 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1739 * Add the HTML associated with a ParserOutput object, without any metadata.
1742 * @param ParserOutput $parserOutput
1744 public function addParserOutputText( $parserOutput ) {
1745 $text = $parserOutput->getText();
1746 wfRunHooks( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1747 $this->addHTML( $text );
1751 * Add everything from a ParserOutput object.
1753 * @param ParserOutput $parserOutput
1755 function addParserOutput( $parserOutput ) {
1756 $this->addParserOutputMetadata( $parserOutput );
1757 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1759 // Touch section edit links only if not previously disabled
1760 if ( $parserOutput->getEditSectionTokens() ) {
1761 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1764 $this->addParserOutputText( $parserOutput );
1768 * Add the output of a QuickTemplate to the output buffer
1770 * @param QuickTemplate $template
1772 public function addTemplate( &$template ) {
1773 $this->addHTML( $template->getHTML() );
1777 * Parse wikitext and return the HTML.
1779 * @param string $text
1780 * @param bool $linestart Is this the start of a line?
1781 * @param bool $interface Use interface language ($wgLang instead of
1782 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1783 * This also disables LanguageConverter.
1784 * @param Language $language Target language object, will override $interface
1785 * @throws MWException
1786 * @return string HTML
1788 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1791 if ( is_null( $this->getTitle() ) ) {
1792 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1795 $popts = $this->parserOptions();
1797 $popts->setInterfaceMessage( true );
1799 if ( $language !== null ) {
1800 $oldLang = $popts->setTargetLanguage( $language );
1803 $parserOutput = $wgParser->getFreshParser()->parse(
1804 $text, $this->getTitle(), $popts,
1805 $linestart, true, $this->mRevisionId
1809 $popts->setInterfaceMessage( false );
1811 if ( $language !== null ) {
1812 $popts->setTargetLanguage( $oldLang );
1815 return $parserOutput->getText();
1819 * Parse wikitext, strip paragraphs, and return the HTML.
1821 * @param string $text
1822 * @param bool $linestart Is this the start of a line?
1823 * @param bool $interface Use interface language ($wgLang instead of
1824 * $wgContLang) while parsing language sensitive magic
1825 * words like GRAMMAR and PLURAL
1826 * @return string HTML
1828 public function parseInline( $text, $linestart = true, $interface = false ) {
1829 $parsed = $this->parse( $text, $linestart, $interface );
1830 return Parser
::stripOuterParagraph( $parsed );
1834 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1836 * @param int $maxage Maximum cache time on the Squid, in seconds.
1838 public function setSquidMaxage( $maxage ) {
1839 $this->mSquidMaxage
= $maxage;
1843 * Use enableClientCache(false) to force it to send nocache headers
1845 * @param bool $state
1849 public function enableClientCache( $state ) {
1850 return wfSetVar( $this->mEnableClientCache
, $state );
1854 * Get the list of cookies that will influence on the cache
1858 function getCacheVaryCookies() {
1860 if ( $cookies === null ) {
1861 $config = $this->getConfig();
1862 $cookies = array_merge(
1864 $config->get( 'CookiePrefix' ) . 'Token',
1865 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1869 $config->get( 'CacheVaryCookies' )
1871 wfRunHooks( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1877 * Check if the request has a cache-varying cookie header
1878 * If it does, it's very important that we don't allow public caching
1882 function haveCacheVaryCookies() {
1883 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1884 if ( $cookieHeader === false ) {
1887 $cvCookies = $this->getCacheVaryCookies();
1888 foreach ( $cvCookies as $cookieName ) {
1889 # Check for a simple string match, like the way squid does it
1890 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1891 wfDebug( __METHOD__
. ": found $cookieName\n" );
1895 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1900 * Add an HTTP header that will influence on the cache
1902 * @param string $header Header name
1903 * @param array|null $option
1904 * @todo FIXME: Document the $option parameter; it appears to be for
1905 * X-Vary-Options but what format is acceptable?
1907 public function addVaryHeader( $header, $option = null ) {
1908 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1909 $this->mVaryHeader
[$header] = (array)$option;
1910 } elseif ( is_array( $option ) ) {
1911 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1912 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
1914 $this->mVaryHeader
[$header] = $option;
1917 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
1921 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
1922 * such as Accept-Encoding or Cookie
1926 public function getVaryHeader() {
1927 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
1931 * Get a complete X-Vary-Options header
1935 public function getXVO() {
1936 $cvCookies = $this->getCacheVaryCookies();
1938 $cookiesOption = array();
1939 foreach ( $cvCookies as $cookieName ) {
1940 $cookiesOption[] = 'string-contains=' . $cookieName;
1942 $this->addVaryHeader( 'Cookie', $cookiesOption );
1945 foreach ( $this->mVaryHeader
as $header => $option ) {
1946 $newheader = $header;
1947 if ( is_array( $option ) && count( $option ) > 0 ) {
1948 $newheader .= ';' . implode( ';', $option );
1950 $headers[] = $newheader;
1952 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
1958 * bug 21672: Add Accept-Language to Vary and XVO headers
1959 * if there's no 'variant' parameter existed in GET.
1962 * /w/index.php?title=Main_page should always be served; but
1963 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
1965 function addAcceptLanguage() {
1966 $title = $this->getTitle();
1967 if ( !$title instanceof Title
) {
1971 $lang = $title->getPageLanguage();
1972 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
1973 $variants = $lang->getVariants();
1974 $aloption = array();
1975 foreach ( $variants as $variant ) {
1976 if ( $variant === $lang->getCode() ) {
1979 $aloption[] = 'string-contains=' . $variant;
1981 // IE and some other browsers use BCP 47 standards in
1982 // their Accept-Language header, like "zh-CN" or "zh-Hant".
1983 // We should handle these too.
1984 $variantBCP47 = wfBCP47( $variant );
1985 if ( $variantBCP47 !== $variant ) {
1986 $aloption[] = 'string-contains=' . $variantBCP47;
1990 $this->addVaryHeader( 'Accept-Language', $aloption );
1995 * Set a flag which will cause an X-Frame-Options header appropriate for
1996 * edit pages to be sent. The header value is controlled by
1997 * $wgEditPageFrameOptions.
1999 * This is the default for special pages. If you display a CSRF-protected
2000 * form on an ordinary view page, then you need to call this function.
2002 * @param bool $enable
2004 public function preventClickjacking( $enable = true ) {
2005 $this->mPreventClickjacking
= $enable;
2009 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2010 * This can be called from pages which do not contain any CSRF-protected
2013 public function allowClickjacking() {
2014 $this->mPreventClickjacking
= false;
2018 * Get the prevent-clickjacking flag
2023 public function getPreventClickjacking() {
2024 return $this->mPreventClickjacking
;
2028 * Get the X-Frame-Options header value (without the name part), or false
2029 * if there isn't one. This is used by Skin to determine whether to enable
2030 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2034 public function getFrameOptions() {
2035 $config = $this->getConfig();
2036 if ( $config->get( 'BreakFrames' ) ) {
2038 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2039 return $config->get( 'EditPageFrameOptions' );
2045 * Send cache control HTTP headers
2047 public function sendCacheControl() {
2048 $response = $this->getRequest()->response();
2049 $config = $this->getConfig();
2050 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2051 $response->header( "ETag: $this->mETag" );
2054 $this->addVaryHeader( 'Cookie' );
2055 $this->addAcceptLanguage();
2057 # don't serve compressed data to clients who can't handle it
2058 # maintain different caches for logged-in users and non-logged in ones
2059 $response->header( $this->getVaryHeader() );
2061 if ( $config->get( 'UseXVO' ) ) {
2062 # Add an X-Vary-Options header for Squid with Wikimedia patches
2063 $response->header( $this->getXVO() );
2066 if ( $this->mEnableClientCache
) {
2068 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2069 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2071 if ( $config->get( 'UseESI' ) ) {
2072 # We'll purge the proxy cache explicitly, but require end user agents
2073 # to revalidate against the proxy on each visit.
2074 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2075 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2076 # start with a shorter timeout for initial testing
2077 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2078 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2079 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2080 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2082 # We'll purge the proxy cache for anons explicitly, but require end user agents
2083 # to revalidate against the proxy on each visit.
2084 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2085 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2086 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2087 # start with a shorter timeout for initial testing
2088 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2089 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2090 . ', must-revalidate, max-age=0' );
2093 # We do want clients to cache if they can, but they *must* check for updates
2094 # on revisiting the page.
2095 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2096 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2097 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2099 if ( $this->mLastModified
) {
2100 $response->header( "Last-Modified: {$this->mLastModified}" );
2103 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2105 # In general, the absence of a last modified header should be enough to prevent
2106 # the client from using its cache. We send a few other things just to make sure.
2107 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2108 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2109 $response->header( 'Pragma: no-cache' );
2114 * Finally, all the text has been munged and accumulated into
2115 * the object, let's actually output it:
2117 public function output() {
2118 if ( $this->mDoNothing
) {
2122 wfProfileIn( __METHOD__
);
2124 $response = $this->getRequest()->response();
2125 $config = $this->getConfig();
2127 if ( $this->mRedirect
!= '' ) {
2128 # Standards require redirect URLs to be absolute
2129 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2131 $redirect = $this->mRedirect
;
2132 $code = $this->mRedirectCode
;
2134 if ( wfRunHooks( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2135 if ( $code == '301' ||
$code == '303' ) {
2136 if ( !$config->get( 'DebugRedirects' ) ) {
2137 $message = HttpStatus
::getMessage( $code );
2138 $response->header( "HTTP/1.1 $code $message" );
2140 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2142 if ( $config->get( 'VaryOnXFP' ) ) {
2143 $this->addVaryHeader( 'X-Forwarded-Proto' );
2145 $this->sendCacheControl();
2147 $response->header( "Content-Type: text/html; charset=utf-8" );
2148 if ( $config->get( 'DebugRedirects' ) ) {
2149 $url = htmlspecialchars( $redirect );
2150 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2151 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2152 print "</body>\n</html>\n";
2154 $response->header( 'Location: ' . $redirect );
2158 wfProfileOut( __METHOD__
);
2160 } elseif ( $this->mStatusCode
) {
2161 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2163 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2167 # Buffer output; final headers may depend on later processing
2170 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2171 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2173 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2174 // jQuery etc. can work correctly.
2175 $response->header( 'X-UA-Compatible: IE=Edge' );
2177 // Prevent framing, if requested
2178 $frameOptions = $this->getFrameOptions();
2179 if ( $frameOptions ) {
2180 $response->header( "X-Frame-Options: $frameOptions" );
2183 if ( $this->mArticleBodyOnly
) {
2184 echo $this->mBodytext
;
2187 $sk = $this->getSkin();
2188 // add skin specific modules
2189 $modules = $sk->getDefaultModules();
2191 // enforce various default modules for all skins
2192 $coreModules = array(
2193 // keep this list as small as possible
2194 'mediawiki.page.startup',
2198 // Support for high-density display images if enabled
2199 if ( $config->get( 'ResponsiveImages' ) ) {
2200 $coreModules[] = 'mediawiki.hidpi';
2203 $this->addModules( $coreModules );
2204 foreach ( $modules as $group ) {
2205 $this->addModules( $group );
2207 MWDebug
::addModules( $this );
2209 // Hook that allows last minute changes to the output page, e.g.
2210 // adding of CSS or Javascript by extensions.
2211 wfRunHooks( 'BeforePageDisplay', array( &$this, &$sk ) );
2213 wfProfileIn( 'Output-skin' );
2215 wfProfileOut( 'Output-skin' );
2218 // This hook allows last minute changes to final overall output by modifying output buffer
2219 wfRunHooks( 'AfterFinalPageOutput', array( $this ) );
2221 $this->sendCacheControl();
2225 wfProfileOut( __METHOD__
);
2229 * Actually output something with print.
2231 * @param string $ins The string to output
2232 * @deprecated since 1.22 Use echo yourself.
2234 public function out( $ins ) {
2235 wfDeprecated( __METHOD__
, '1.22' );
2240 * Produce a "user is blocked" page.
2241 * @deprecated since 1.18
2243 function blockedPage() {
2244 throw new UserBlockedError( $this->getUser()->mBlock
);
2248 * Prepare this object to display an error page; disable caching and
2249 * indexing, clear the current text and redirect, set the page's title
2250 * and optionally an custom HTML title (content of the "<title>" tag).
2252 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2253 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2254 * optional, if not passed the "<title>" attribute will be
2255 * based on $pageTitle
2257 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2258 $this->setPageTitle( $pageTitle );
2259 if ( $htmlTitle !== false ) {
2260 $this->setHTMLTitle( $htmlTitle );
2262 $this->setRobotPolicy( 'noindex,nofollow' );
2263 $this->setArticleRelated( false );
2264 $this->enableClientCache( false );
2265 $this->mRedirect
= '';
2266 $this->clearSubtitle();
2271 * Output a standard error page
2273 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2274 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2275 * showErrorPage( 'titlemsg', $messageObject );
2276 * showErrorPage( $titleMessageObject, $messageObject );
2278 * @param string|Message $title Message key (string) for page title, or a Message object
2279 * @param string|Message $msg Message key (string) for page text, or a Message object
2280 * @param array $params Message parameters; ignored if $msg is a Message object
2282 public function showErrorPage( $title, $msg, $params = array() ) {
2283 if ( !$title instanceof Message
) {
2284 $title = $this->msg( $title );
2287 $this->prepareErrorPage( $title );
2289 if ( $msg instanceof Message
) {
2290 if ( $params !== array() ) {
2291 trigger_error( 'Argument ignored: $params. The message parameters argument '
2292 . 'is discarded when the $msg argument is a Message object instead of '
2293 . 'a string.', E_USER_NOTICE
);
2295 $this->addHTML( $msg->parseAsBlock() );
2297 $this->addWikiMsgArray( $msg, $params );
2300 $this->returnToMain();
2304 * Output a standard permission error page
2306 * @param array $errors Error message keys
2307 * @param string $action Action that was denied or null if unknown
2309 public function showPermissionsErrorPage( array $errors, $action = null ) {
2310 // For some action (read, edit, create and upload), display a "login to do this action"
2311 // error if all of the following conditions are met:
2312 // 1. the user is not logged in
2313 // 2. the only error is insufficient permissions (i.e. no block or something else)
2314 // 3. the error can be avoided simply by logging in
2315 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2316 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2317 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2318 && ( User
::groupHasPermission( 'user', $action )
2319 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2321 $displayReturnto = null;
2323 # Due to bug 32276, if a user does not have read permissions,
2324 # $this->getTitle() will just give Special:Badtitle, which is
2325 # not especially useful as a returnto parameter. Use the title
2326 # from the request instead, if there was one.
2327 $request = $this->getRequest();
2328 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2329 if ( $action == 'edit' ) {
2330 $msg = 'whitelistedittext';
2331 $displayReturnto = $returnto;
2332 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2333 $msg = 'nocreatetext';
2334 } elseif ( $action == 'upload' ) {
2335 $msg = 'uploadnologintext';
2337 $msg = 'loginreqpagetext';
2338 $displayReturnto = Title
::newMainPage();
2344 $query['returnto'] = $returnto->getPrefixedText();
2346 if ( !$request->wasPosted() ) {
2347 $returntoquery = $request->getValues();
2348 unset( $returntoquery['title'] );
2349 unset( $returntoquery['returnto'] );
2350 unset( $returntoquery['returntoquery'] );
2351 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2354 $loginLink = Linker
::linkKnown(
2355 SpecialPage
::getTitleFor( 'Userlogin' ),
2356 $this->msg( 'loginreqlink' )->escaped(),
2361 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2362 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2364 # Don't return to a page the user can't read otherwise
2365 # we'll end up in a pointless loop
2366 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2367 $this->returnToMain( null, $displayReturnto );
2370 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2371 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2376 * Display an error page indicating that a given version of MediaWiki is
2377 * required to use it
2379 * @param mixed $version The version of MediaWiki needed to use the page
2381 public function versionRequired( $version ) {
2382 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2384 $this->addWikiMsg( 'versionrequiredtext', $version );
2385 $this->returnToMain();
2389 * Display an error page noting that a given permission bit is required.
2390 * @deprecated since 1.18, just throw the exception directly
2391 * @param string $permission Key required
2392 * @throws PermissionsError
2394 public function permissionRequired( $permission ) {
2395 throw new PermissionsError( $permission );
2399 * Produce the stock "please login to use the wiki" page
2401 * @deprecated since 1.19; throw the exception directly
2403 public function loginToUse() {
2404 throw new PermissionsError( 'read' );
2408 * Format a list of error messages
2410 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2411 * @param string $action Action that was denied or null if unknown
2412 * @return string The wikitext error-messages, formatted into a list.
2414 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2415 if ( $action == null ) {
2416 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2418 $action_desc = $this->msg( "action-$action" )->plain();
2420 'permissionserrorstext-withaction',
2423 )->plain() . "\n\n";
2426 if ( count( $errors ) > 1 ) {
2427 $text .= '<ul class="permissions-errors">' . "\n";
2429 foreach ( $errors as $error ) {
2431 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2436 $text .= "<div class=\"permissions-errors\">\n" .
2437 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2445 * Display a page stating that the Wiki is in read-only mode.
2446 * Should only be called after wfReadOnly() has returned true.
2448 * Historically, this function was used to show the source of the page that the user
2449 * was trying to edit and _also_ permissions error messages. The relevant code was
2450 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2452 * @deprecated since 1.25; throw the exception directly
2453 * @throws ReadOnlyError
2455 public function readOnlyPage() {
2456 if ( func_num_args() > 0 ) {
2457 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2460 throw new ReadOnlyError
;
2464 * Turn off regular page output and return an error response
2465 * for when rate limiting has triggered.
2467 * @deprecated since 1.25; throw the exception directly
2469 public function rateLimited() {
2470 wfDeprecated( __METHOD__
, '1.25' );
2471 throw new ThrottledError
;
2475 * Show a warning about slave lag
2477 * If the lag is higher than $wgSlaveLagCritical seconds,
2478 * then the warning is a bit more obvious. If the lag is
2479 * lower than $wgSlaveLagWarning, then no warning is shown.
2481 * @param int $lag Slave lag
2483 public function showLagWarning( $lag ) {
2484 $config = $this->getConfig();
2485 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2486 $message = $lag < $config->get( 'SlaveLagCritical' )
2489 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2490 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2494 public function showFatalError( $message ) {
2495 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2497 $this->addHTML( $message );
2500 public function showUnexpectedValueError( $name, $val ) {
2501 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2504 public function showFileCopyError( $old, $new ) {
2505 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2508 public function showFileRenameError( $old, $new ) {
2509 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2512 public function showFileDeleteError( $name ) {
2513 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2516 public function showFileNotFoundError( $name ) {
2517 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2521 * Add a "return to" link pointing to a specified title
2523 * @param Title $title Title to link
2524 * @param array $query Query string parameters
2525 * @param string $text Text of the link (input is not escaped)
2526 * @param array $options Options array to pass to Linker
2528 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2529 $link = $this->msg( 'returnto' )->rawParams(
2530 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2531 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2535 * Add a "return to" link pointing to a specified title,
2536 * or the title indicated in the request, or else the main page
2538 * @param mixed $unused
2539 * @param Title|string $returnto Title or String to return to
2540 * @param string $returntoquery Query string for the return to link
2542 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2543 if ( $returnto == null ) {
2544 $returnto = $this->getRequest()->getText( 'returnto' );
2547 if ( $returntoquery == null ) {
2548 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2551 if ( $returnto === '' ) {
2552 $returnto = Title
::newMainPage();
2555 if ( is_object( $returnto ) ) {
2556 $titleObj = $returnto;
2558 $titleObj = Title
::newFromText( $returnto );
2560 if ( !is_object( $titleObj ) ) {
2561 $titleObj = Title
::newMainPage();
2564 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2568 * @param Skin $sk The given Skin
2569 * @param bool $includeStyle Unused
2570 * @return string The doctype, opening "<html>", and head element.
2572 public function headElement( Skin
$sk, $includeStyle = true ) {
2575 $section = new ProfileSection( __METHOD__
);
2577 $userdir = $this->getLanguage()->getDir();
2578 $sitedir = $wgContLang->getDir();
2580 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2582 if ( $this->getHTMLTitle() == '' ) {
2583 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2586 $openHead = Html
::openElement( 'head' );
2588 # Don't bother with the newline if $head == ''
2589 $ret .= "$openHead\n";
2592 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2593 // Add <meta charset="UTF-8">
2594 // This should be before <title> since it defines the charset used by
2595 // text including the text inside <title>.
2596 // The spec recommends defining XHTML5's charset using the XML declaration
2598 // Our XML declaration is output by Html::htmlHeader.
2599 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2600 // http://www.whatwg.org/html/semantics.html#charset
2601 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2604 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2606 foreach ( $this->getHeadLinksArray() as $item ) {
2607 $ret .= $item . "\n";
2610 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2611 $ret .= $this->buildCssLinks();
2613 $ret .= $this->getHeadScripts() . "\n";
2615 foreach ( $this->mHeadItems
as $item ) {
2616 $ret .= $item . "\n";
2619 $closeHead = Html
::closeElement( 'head' );
2621 $ret .= "$closeHead\n";
2624 $bodyClasses = array();
2625 $bodyClasses[] = 'mediawiki';
2627 # Classes for LTR/RTL directionality support
2628 $bodyClasses[] = $userdir;
2629 $bodyClasses[] = "sitedir-$sitedir";
2631 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2632 # A <body> class is probably not the best way to do this . . .
2633 $bodyClasses[] = 'capitalize-all-nouns';
2636 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2637 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2639 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2641 $bodyAttrs = array();
2642 // While the implode() is not strictly needed, it's used for backwards compatibility
2643 // (this used to be built as a string and hooks likely still expect that).
2644 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2646 // Allow skins and extensions to add body attributes they need
2647 $sk->addToBodyAttributes( $this, $bodyAttrs );
2648 wfRunHooks( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2650 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2656 * Get a ResourceLoader object associated with this OutputPage
2658 * @return ResourceLoader
2660 public function getResourceLoader() {
2661 if ( is_null( $this->mResourceLoader
) ) {
2662 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2664 return $this->mResourceLoader
;
2669 * @param array|string $modules One or more module names
2670 * @param string $only ResourceLoaderModule TYPE_ class constant
2671 * @param bool $useESI
2672 * @param array $extraQuery Array with extra query parameters to add to each
2673 * request. array( param => value ).
2674 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2675 * call rather than a "<script src='...'>" tag.
2676 * @return string The html "<script>", "<link>" and "<style>" tags
2678 protected function makeResourceLoaderLink( $modules, $only, $useESI = false,
2679 array $extraQuery = array(), $loadCall = false
2681 $modules = (array)$modules;
2685 'states' => array(),
2688 if ( !count( $modules ) ) {
2692 if ( count( $modules ) > 1 ) {
2693 // Remove duplicate module requests
2694 $modules = array_unique( $modules );
2695 // Sort module names so requests are more uniform
2698 if ( ResourceLoader
::inDebugMode() ) {
2699 // Recursively call us for every item
2700 foreach ( $modules as $name ) {
2701 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2702 $links['html'] .= $link['html'];
2703 $links['states'] +
= $link['states'];
2709 if ( !is_null( $this->mTarget
) ) {
2710 $extraQuery['target'] = $this->mTarget
;
2713 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2714 $sortedModules = array();
2715 $resourceLoader = $this->getResourceLoader();
2716 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2717 foreach ( $modules as $name ) {
2718 $module = $resourceLoader->getModule( $name );
2719 # Check that we're allowed to include this module on this page
2721 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2722 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2723 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2724 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2725 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2726 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2727 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2732 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2735 foreach ( $sortedModules as $source => $groups ) {
2736 foreach ( $groups as $group => $grpModules ) {
2737 // Special handling for user-specific groups
2739 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2740 $user = $this->getUser()->getName();
2743 // Create a fake request based on the one we are about to make so modules return
2744 // correct timestamp and emptiness data
2745 $query = ResourceLoader
::makeLoaderQuery(
2746 array(), // modules; not determined yet
2747 $this->getLanguage()->getCode(),
2748 $this->getSkin()->getSkinName(),
2750 null, // version; not determined yet
2751 ResourceLoader
::inDebugMode(),
2752 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2753 $this->isPrintable(),
2754 $this->getRequest()->getBool( 'handheld' ),
2757 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2759 // Extract modules that know they're empty and see if we have one or more
2762 foreach ( $grpModules as $key => $module ) {
2763 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2764 // If we're only getting the styles, we don't need to do anything for empty modules.
2765 if ( $module->isKnownEmpty( $context ) ) {
2766 unset( $grpModules[$key] );
2767 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2768 $links['states'][$key] = 'ready';
2772 $isRaw |
= $module->isRaw();
2775 // If there are no non-empty modules, skip this group
2776 if ( count( $grpModules ) === 0 ) {
2780 // Inline private modules. These can't be loaded through load.php for security
2781 // reasons, see bug 34907. Note that these modules should be loaded from
2782 // getHeadScripts() before the first loader call. Otherwise other modules can't
2783 // properly use them as dependencies (bug 30914)
2784 if ( $group === 'private' ) {
2785 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2786 $links['html'] .= Html
::inlineStyle(
2787 $resourceLoader->makeModuleResponse( $context, $grpModules )
2790 $links['html'] .= Html
::inlineScript(
2791 ResourceLoader
::makeLoaderConditionalScript(
2792 $resourceLoader->makeModuleResponse( $context, $grpModules )
2796 $links['html'] .= "\n";
2800 // Special handling for the user group; because users might change their stuff
2801 // on-wiki like user pages, or user preferences; we need to find the highest
2802 // timestamp of these user-changeable modules so we can ensure cache misses on change
2803 // This should NOT be done for the site group (bug 27564) because anons get that too
2804 // and we shouldn't be putting timestamps in Squid-cached HTML
2806 if ( $group === 'user' ) {
2807 // Get the maximum timestamp
2809 foreach ( $grpModules as $module ) {
2810 $timestamp = max( $timestamp, $module->getModifiedTime( $context ) );
2812 // Add a version parameter so cache will break when things change
2813 $query['version'] = wfTimestamp( TS_ISO_8601_BASIC
, $timestamp );
2816 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2817 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2818 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2820 if ( $useESI && $resourceLoaderUseESI ) {
2821 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2822 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2823 $link = Html
::inlineStyle( $esi );
2825 $link = Html
::inlineScript( $esi );
2828 // Automatically select style/script elements
2829 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2830 $link = Html
::linkedStyle( $url );
2831 } elseif ( $loadCall ) {
2832 $link = Html
::inlineScript(
2833 ResourceLoader
::makeLoaderConditionalScript(
2834 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2838 $link = Html
::linkedScript( $url );
2839 if ( $context->getOnly() === 'scripts' && !$context->getRaw() && !$isRaw ) {
2840 // Wrap only=script requests in a conditional as browsers not supported
2841 // by the startup module would unconditionally execute this module.
2842 // Otherwise users will get "ReferenceError: mw is undefined" or
2843 // "jQuery is undefined" from e.g. a "site" module.
2844 $link = Html
::inlineScript(
2845 ResourceLoader
::makeLoaderConditionalScript(
2846 Xml
::encodeJsCall( 'document.write', array( $link ) )
2851 // For modules requested directly in the html via <link> or <script>,
2852 // tell mw.loader they are being loading to prevent duplicate requests.
2853 foreach ( $grpModules as $key => $module ) {
2854 // Don't output state=loading for the startup module..
2855 if ( $key !== 'startup' ) {
2856 $links['states'][$key] = 'loading';
2862 if ( $group == 'noscript' ) {
2863 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2865 $links['html'] .= $link . "\n";
2874 * Build html output from an array of links from makeResourceLoaderLink.
2875 * @param array $links
2876 * @return string HTML
2878 protected static function getHtmlFromLoaderLinks( array $links ) {
2881 foreach ( $links as $link ) {
2882 if ( !is_array( $link ) ) {
2885 $html .= $link['html'];
2886 $states +
= $link['states'];
2890 if ( count( $states ) ) {
2891 $html = Html
::inlineScript(
2892 ResourceLoader
::makeLoaderConditionalScript(
2893 ResourceLoader
::makeLoaderStateScript( $states )
2902 * JS stuff to put in the "<head>". This is the startup module, config
2903 * vars and modules marked with position 'top'
2905 * @return string HTML fragment
2907 function getHeadScripts() {
2908 // Startup - this will immediately load jquery and mediawiki modules
2910 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2912 // Load config before anything else
2913 $links[] = Html
::inlineScript(
2914 ResourceLoader
::makeLoaderConditionalScript(
2915 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2919 // Load embeddable private modules before any loader links
2920 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2921 // in mw.loader.implement() calls and deferred until mw.user is available
2922 $embedScripts = array( 'user.options', 'user.tokens' );
2923 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2925 // Scripts and messages "only" requests marked for top inclusion
2926 // Messages should go first
2927 $links[] = $this->makeResourceLoaderLink(
2928 $this->getModuleMessages( true, 'top' ),
2929 ResourceLoaderModule
::TYPE_MESSAGES
2931 $links[] = $this->makeResourceLoaderLink(
2932 $this->getModuleScripts( true, 'top' ),
2933 ResourceLoaderModule
::TYPE_SCRIPTS
2936 // Modules requests - let the client calculate dependencies and batch requests as it likes
2937 // Only load modules that have marked themselves for loading at the top
2938 $modules = $this->getModules( true, 'top' );
2940 $links[] = Html
::inlineScript(
2941 ResourceLoader
::makeLoaderConditionalScript(
2942 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
2947 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
2948 $links[] = $this->getScriptsForBottomQueue( true );
2951 return self
::getHtmlFromLoaderLinks( $links );
2955 * JS stuff to put at the 'bottom', which can either be the bottom of the
2956 * "<body>" or the bottom of the "<head>" depending on
2957 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
2958 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
2961 * @param bool $inHead If true, this HTML goes into the "<head>",
2962 * if false it goes into the "<body>".
2965 function getScriptsForBottomQueue( $inHead ) {
2966 // Scripts and messages "only" requests marked for bottom inclusion
2967 // If we're in the <head>, use load() calls rather than <script src="..."> tags
2968 // Messages should go first
2970 $links[] = $this->makeResourceLoaderLink( $this->getModuleMessages( true, 'bottom' ),
2971 ResourceLoaderModule
::TYPE_MESSAGES
, /* $useESI = */ false, /* $extraQuery = */ array(),
2972 /* $loadCall = */ $inHead
2974 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
2975 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
2976 /* $loadCall = */ $inHead
2979 // Modules requests - let the client calculate dependencies and batch requests as it likes
2980 // Only load modules that have marked themselves for loading at the bottom
2981 $modules = $this->getModules( true, 'bottom' );
2983 $links[] = Html
::inlineScript(
2984 ResourceLoader
::makeLoaderConditionalScript(
2985 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
2991 $links[] = "\n" . $this->mScripts
;
2993 // Add site JS if enabled
2994 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
2995 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
2998 // Add user JS if enabled
2999 if ( $this->getConfig()->get( 'AllowUserJs' )
3000 && $this->getUser()->isLoggedIn()
3001 && $this->getTitle()
3002 && $this->getTitle()->isJsSubpage()
3003 && $this->userCanPreview()
3005 # XXX: additional security check/prompt?
3006 // We're on a preview of a JS subpage
3007 // Exclude this page from the user module in case it's in there (bug 26283)
3008 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3009 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3011 // Load the previewed JS
3012 $links[] = Html
::inlineScript( "\n"
3013 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3015 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3016 // asynchronously and may arrive *after* the inline script here. So the previewed code
3017 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3019 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3020 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3021 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3025 // Group JS is only enabled if site JS is enabled.
3026 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3027 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3030 return self
::getHtmlFromLoaderLinks( $links );
3034 * JS stuff to put at the bottom of the "<body>"
3037 function getBottomScripts() {
3038 // Optimise jQuery ready event cross-browser.
3039 // This also enforces $.isReady to be true at </body> which fixes the
3040 // mw.loader bug in Firefox with using document.write between </body>
3041 // and the DOMContentReady event (bug 47457).
3042 $html = Html
::inlineScript( 'window.jQuery && jQuery.ready();' );
3044 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3045 $html .= $this->getScriptsForBottomQueue( false );
3052 * Get the javascript config vars to include on this page
3054 * @return array Array of javascript config vars
3057 public function getJsConfigVars() {
3058 return $this->mJsConfigVars
;
3062 * Add one or more variables to be set in mw.config in JavaScript
3064 * @param string|array $keys Key or array of key/value pairs
3065 * @param mixed $value [optional] Value of the configuration variable
3067 public function addJsConfigVars( $keys, $value = null ) {
3068 if ( is_array( $keys ) ) {
3069 foreach ( $keys as $key => $value ) {
3070 $this->mJsConfigVars
[$key] = $value;
3075 $this->mJsConfigVars
[$keys] = $value;
3079 * Get an array containing the variables to be set in mw.config in JavaScript.
3081 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3082 * - in other words, page-independent/site-wide variables (without state).
3083 * You will only be adding bloat to the html page and causing page caches to
3084 * have to be purged on configuration changes.
3087 private function getJSVars() {
3092 $canonicalSpecialPageName = false; # bug 21115
3094 $title = $this->getTitle();
3095 $ns = $title->getNamespace();
3096 $canonicalNamespace = MWNamespace
::exists( $ns )
3097 ? MWNamespace
::getCanonicalName( $ns )
3098 : $title->getNsText();
3100 $sk = $this->getSkin();
3101 // Get the relevant title so that AJAX features can use the correct page name
3102 // when making API requests from certain special pages (bug 34972).
3103 $relevantTitle = $sk->getRelevantTitle();
3104 $relevantUser = $sk->getRelevantUser();
3106 if ( $ns == NS_SPECIAL
) {
3107 list( $canonicalSpecialPageName, /*...*/ ) =
3108 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3109 } elseif ( $this->canUseWikiPage() ) {
3110 $wikiPage = $this->getWikiPage();
3111 $curRevisionId = $wikiPage->getLatest();
3112 $articleId = $wikiPage->getId();
3115 $lang = $title->getPageLanguage();
3117 // Pre-process information
3118 $separatorTransTable = $lang->separatorTransformTable();
3119 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3120 $compactSeparatorTransTable = array(
3121 implode( "\t", array_keys( $separatorTransTable ) ),
3122 implode( "\t", $separatorTransTable ),
3124 $digitTransTable = $lang->digitTransformTable();
3125 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3126 $compactDigitTransTable = array(
3127 implode( "\t", array_keys( $digitTransTable ) ),
3128 implode( "\t", $digitTransTable ),
3131 $user = $this->getUser();
3134 'wgCanonicalNamespace' => $canonicalNamespace,
3135 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3136 'wgNamespaceNumber' => $title->getNamespace(),
3137 'wgPageName' => $title->getPrefixedDBkey(),
3138 'wgTitle' => $title->getText(),
3139 'wgCurRevisionId' => $curRevisionId,
3140 'wgRevisionId' => (int)$this->getRevisionId(),
3141 'wgArticleId' => $articleId,
3142 'wgIsArticle' => $this->isArticle(),
3143 'wgIsRedirect' => $title->isRedirect(),
3144 'wgAction' => Action
::getActionName( $this->getContext() ),
3145 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3146 'wgUserGroups' => $user->getEffectiveGroups(),
3147 'wgCategories' => $this->getCategories(),
3148 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3149 'wgPageContentLanguage' => $lang->getCode(),
3150 'wgPageContentModel' => $title->getContentModel(),
3151 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3152 'wgDigitTransformTable' => $compactDigitTransTable,
3153 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3154 'wgMonthNames' => $lang->getMonthNamesArray(),
3155 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3156 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3159 if ( $user->isLoggedIn() ) {
3160 $vars['wgUserId'] = $user->getId();
3161 $vars['wgUserEditCount'] = $user->getEditCount();
3162 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3163 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3164 // Get the revision ID of the oldest new message on the user's talk
3165 // page. This can be used for constructing new message alerts on
3167 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3170 if ( $wgContLang->hasVariants() ) {
3171 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3173 // Same test as SkinTemplate
3174 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3175 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3177 foreach ( $title->getRestrictionTypes() as $type ) {
3178 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3181 if ( $title->isMainPage() ) {
3182 $vars['wgIsMainPage'] = true;
3185 if ( $this->mRedirectedFrom
) {
3186 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3189 if ( $relevantUser ) {
3190 $vars['wgRelevantUserName'] = $relevantUser->getName();
3193 // Allow extensions to add their custom variables to the mw.config map.
3194 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3195 // page-dependant but site-wide (without state).
3196 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3197 wfRunHooks( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3199 // Merge in variables from addJsConfigVars last
3200 return array_merge( $vars, $this->getJsConfigVars() );
3204 * To make it harder for someone to slip a user a fake
3205 * user-JavaScript or user-CSS preview, a random token
3206 * is associated with the login session. If it's not
3207 * passed back with the preview request, we won't render
3212 public function userCanPreview() {
3213 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3214 ||
!$this->getRequest()->wasPosted()
3215 ||
!$this->getUser()->matchEditToken(
3216 $this->getRequest()->getVal( 'wpEditToken' ) )
3220 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3224 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3228 * @return array Array in format "link name or number => 'link html'".
3230 public function getHeadLinksArray() {
3234 $config = $this->getConfig();
3236 $canonicalUrl = $this->mCanonicalUrl
;
3238 $tags['meta-generator'] = Html
::element( 'meta', array(
3239 'name' => 'generator',
3240 'content' => "MediaWiki $wgVersion",
3243 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3244 if ( $p !== 'index,follow' ) {
3245 // http://www.robotstxt.org/wc/meta-user.html
3246 // Only show if it's different from the default robots policy
3247 $tags['meta-robots'] = Html
::element( 'meta', array(
3253 foreach ( $this->mMetatags
as $tag ) {
3254 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3256 $tag[0] = substr( $tag[0], 5 );
3260 $tagName = "meta-{$tag[0]}";
3261 if ( isset( $tags[$tagName] ) ) {
3262 $tagName .= $tag[1];
3264 $tags[$tagName] = Html
::element( 'meta',
3267 'content' => $tag[1]
3272 foreach ( $this->mLinktags
as $tag ) {
3273 $tags[] = Html
::element( 'link', $tag );
3276 # Universal edit button
3277 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3278 $user = $this->getUser();
3279 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3280 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3281 // Original UniversalEditButton
3282 $msg = $this->msg( 'edit' )->text();
3283 $tags['universal-edit-button'] = Html
::element( 'link', array(
3284 'rel' => 'alternate',
3285 'type' => 'application/x-wiki',
3287 'href' => $this->getTitle()->getEditURL(),
3289 // Alternate edit link
3290 $tags['alternative-edit'] = Html
::element( 'link', array(
3293 'href' => $this->getTitle()->getEditURL(),
3298 # Generally the order of the favicon and apple-touch-icon links
3299 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3300 # uses whichever one appears later in the HTML source. Make sure
3301 # apple-touch-icon is specified first to avoid this.
3302 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3303 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3304 'rel' => 'apple-touch-icon',
3305 'href' => $config->get( 'AppleTouchIcon' )
3309 if ( $config->get( 'Favicon' ) !== false ) {
3310 $tags['favicon'] = Html
::element( 'link', array(
3311 'rel' => 'shortcut icon',
3312 'href' => $config->get( 'Favicon' )
3316 # OpenSearch description link
3317 $tags['opensearch'] = Html
::element( 'link', array(
3319 'type' => 'application/opensearchdescription+xml',
3320 'href' => wfScript( 'opensearch_desc' ),
3321 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3324 if ( $config->get( 'EnableAPI' ) ) {
3325 # Real Simple Discovery link, provides auto-discovery information
3326 # for the MediaWiki API (and potentially additional custom API
3327 # support such as WordPress or Twitter-compatible APIs for a
3328 # blogging extension, etc)
3329 $tags['rsd'] = Html
::element( 'link', array(
3331 'type' => 'application/rsd+xml',
3332 // Output a protocol-relative URL here if $wgServer is protocol-relative
3333 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3334 'href' => wfExpandUrl( wfAppendQuery(
3336 array( 'action' => 'rsd' ) ),
3343 if ( !$config->get( 'DisableLangConversion' ) ) {
3344 $lang = $this->getTitle()->getPageLanguage();
3345 if ( $lang->hasVariants() ) {
3346 $variants = $lang->getVariants();
3347 foreach ( $variants as $_v ) {
3348 $tags["variant-$_v"] = Html
::element( 'link', array(
3349 'rel' => 'alternate',
3350 'hreflang' => wfBCP47( $_v ),
3351 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3355 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3356 $tags["variant-x-default"] = Html
::element( 'link', array(
3357 'rel' => 'alternate',
3358 'hreflang' => 'x-default',
3359 'href' => $this->getTitle()->getLocalURL() ) );
3364 if ( $config->get( 'RightsPage' ) ) {
3365 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3368 $copyright = $copy->getLocalURL();
3372 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3373 $copyright = $config->get( 'RightsUrl' );
3377 $tags['copyright'] = Html
::element( 'link', array(
3378 'rel' => 'copyright',
3379 'href' => $copyright )
3384 if ( $config->get( 'Feed' ) ) {
3385 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3386 # Use the page name for the title. In principle, this could
3387 # lead to issues with having the same name for different feeds
3388 # corresponding to the same page, but we can't avoid that at
3391 $tags[] = $this->feedLink(
3394 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3395 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3399 # Recent changes feed should appear on every page (except recentchanges,
3400 # that would be redundant). Put it after the per-page feed to avoid
3401 # changing existing behavior. It's still available, probably via a
3402 # menu in your browser. Some sites might have a different feed they'd
3403 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3404 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3405 # If so, use it instead.
3406 $sitename = $config->get( 'Sitename' );
3407 if ( $config->get( 'OverrideSiteFeed' ) ) {
3408 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3409 // Note, this->feedLink escapes the url.
3410 $tags[] = $this->feedLink(
3413 $this->msg( "site-{$type}-feed", $sitename )->text()
3416 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3417 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3418 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3419 $tags[] = $this->feedLink(
3421 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3422 # For grep: 'site-rss-feed', 'site-atom-feed'
3423 $this->msg( "site-{$format}-feed", $sitename )->text()
3430 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3431 if ( $canonicalUrl !== false ) {
3432 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3434 $reqUrl = $this->getRequest()->getRequestURL();
3435 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3438 if ( $canonicalUrl !== false ) {
3439 $tags[] = Html
::element( 'link', array(
3440 'rel' => 'canonical',
3441 'href' => $canonicalUrl
3449 * @return string HTML tag links to be put in the header.
3450 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3451 * OutputPage::getHeadLinksArray directly.
3453 public function getHeadLinks() {
3454 wfDeprecated( __METHOD__
, '1.24' );
3455 return implode( "\n", $this->getHeadLinksArray() );
3459 * Generate a "<link rel/>" for a feed.
3461 * @param string $type Feed type
3462 * @param string $url URL to the feed
3463 * @param string $text Value of the "title" attribute
3464 * @return string HTML fragment
3466 private function feedLink( $type, $url, $text ) {
3467 return Html
::element( 'link', array(
3468 'rel' => 'alternate',
3469 'type' => "application/$type+xml",
3476 * Add a local or specified stylesheet, with the given media options.
3477 * Meant primarily for internal use...
3479 * @param string $style URL to the file
3480 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3481 * @param string $condition For IE conditional comments, specifying an IE version
3482 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3484 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3486 // Even though we expect the media type to be lowercase, but here we
3487 // force it to lowercase to be safe.
3489 $options['media'] = $media;
3492 $options['condition'] = $condition;
3495 $options['dir'] = $dir;
3497 $this->styles
[$style] = $options;
3501 * Adds inline CSS styles
3502 * @param mixed $style_css Inline CSS
3503 * @param string $flip Set to 'flip' to flip the CSS if needed
3505 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3506 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3507 # If wanted, and the interface is right-to-left, flip the CSS
3508 $style_css = CSSJanus
::transform( $style_css, true, false );
3510 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3514 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3515 * These will be applied to various media & IE conditionals.
3519 public function buildCssLinks() {
3522 $this->getSkin()->setupSkinUserCss( $this );
3524 // Add ResourceLoader styles
3525 // Split the styles into these groups
3530 'private' => array(),
3531 'noscript' => array()
3534 $otherTags = ''; // Tags to append after the normal <link> tags
3535 $resourceLoader = $this->getResourceLoader();
3537 $moduleStyles = $this->getModuleStyles();
3539 // Per-site custom styles
3540 $moduleStyles[] = 'site';
3541 $moduleStyles[] = 'noscript';
3542 $moduleStyles[] = 'user.groups';
3544 // Per-user custom styles
3545 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3546 && $this->userCanPreview()
3548 // We're on a preview of a CSS subpage
3549 // Exclude this page from the user module in case it's in there (bug 26283)
3550 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3551 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3553 $otherTags .= $link['html'];
3555 // Load the previewed CSS
3556 // If needed, Janus it first. This is user-supplied CSS, so it's
3557 // assumed to be right for the content language directionality.
3558 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3559 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3560 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3562 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3564 // Load the user styles normally
3565 $moduleStyles[] = 'user';
3568 // Per-user preference styles
3569 $moduleStyles[] = 'user.cssprefs';
3571 foreach ( $moduleStyles as $name ) {
3572 $module = $resourceLoader->getModule( $name );
3576 $group = $module->getGroup();
3577 // Modules in groups different than the ones listed on top (see $styles assignment)
3578 // will be placed in the "other" group
3579 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3582 // We want site, private and user styles to override dynamically added
3583 // styles from modules, but we want dynamically added styles to override
3584 // statically added styles from other modules. So the order has to be
3585 // other, dynamic, site, private, user. Add statically added styles for
3587 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3588 // Add normal styles added through addStyle()/addInlineStyle() here
3589 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3590 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3591 // We use a <meta> tag with a made-up name for this because that's valid HTML
3592 $links[] = Html
::element(
3594 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3597 // Add site, private and user styles
3598 // 'private' at present only contains user.options, so put that before 'user'
3599 // Any future private modules will likely have a similar user-specific character
3600 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3601 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3602 ResourceLoaderModule
::TYPE_STYLES
3606 // Add stuff in $otherTags (previewed user CSS if applicable)
3607 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3613 public function buildCssLinksArray() {
3616 // Add any extension CSS
3617 foreach ( $this->mExtStyles
as $url ) {
3618 $this->addStyle( $url );
3620 $this->mExtStyles
= array();
3622 foreach ( $this->styles
as $file => $options ) {
3623 $link = $this->styleLink( $file, $options );
3625 $links[$file] = $link;
3632 * Generate \<link\> tags for stylesheets
3634 * @param string $style URL to the file
3635 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3636 * @return string HTML fragment
3638 protected function styleLink( $style, array $options ) {
3639 if ( isset( $options['dir'] ) ) {
3640 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3645 if ( isset( $options['media'] ) ) {
3646 $media = self
::transformCssMedia( $options['media'] );
3647 if ( is_null( $media ) ) {
3654 if ( substr( $style, 0, 1 ) == '/' ||
3655 substr( $style, 0, 5 ) == 'http:' ||
3656 substr( $style, 0, 6 ) == 'https:' ) {
3659 $config = $this->getConfig();
3660 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3663 $link = Html
::linkedStyle( $url, $media );
3665 if ( isset( $options['condition'] ) ) {
3666 $condition = htmlspecialchars( $options['condition'] );
3667 $link = "<!--[if $condition]>$link<![endif]-->";
3673 * Transform "media" attribute based on request parameters
3675 * @param string $media Current value of the "media" attribute
3676 * @return string Modified value of the "media" attribute, or null to skip
3679 public static function transformCssMedia( $media ) {
3682 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3683 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3685 // Switch in on-screen display for media testing
3687 'printable' => 'print',
3688 'handheld' => 'handheld',
3690 foreach ( $switches as $switch => $targetMedia ) {
3691 if ( $wgRequest->getBool( $switch ) ) {
3692 if ( $media == $targetMedia ) {
3694 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3695 // This regex will not attempt to understand a comma-separated media_query_list
3697 // Example supported values for $media:
3698 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3699 // Example NOT supported value for $media:
3700 // '3d-glasses, screen, print and resolution > 90dpi'
3702 // If it's a print request, we never want any kind of screen stylesheets
3703 // If it's a handheld request (currently the only other choice with a switch),
3704 // we don't want simple 'screen' but we might want screen queries that
3705 // have a max-width or something, so we'll pass all others on and let the
3706 // client do the query.
3707 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3718 * Add a wikitext-formatted message to the output.
3719 * This is equivalent to:
3721 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3723 public function addWikiMsg( /*...*/ ) {
3724 $args = func_get_args();
3725 $name = array_shift( $args );
3726 $this->addWikiMsgArray( $name, $args );
3730 * Add a wikitext-formatted message to the output.
3731 * Like addWikiMsg() except the parameters are taken as an array
3732 * instead of a variable argument list.
3734 * @param string $name
3735 * @param array $args
3737 public function addWikiMsgArray( $name, $args ) {
3738 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3742 * This function takes a number of message/argument specifications, wraps them in
3743 * some overall structure, and then parses the result and adds it to the output.
3745 * In the $wrap, $1 is replaced with the first message, $2 with the second, and so
3746 * on. The subsequent arguments may either be strings, in which case they are the
3747 * message names, or arrays, in which case the first element is the message name,
3748 * and subsequent elements are the parameters to that message.
3750 * Don't use this for messages that are not in users interface language.
3754 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3758 * $wgOut->addWikiText( "<div class='error'>\n"
3759 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3761 * The newline after opening div is needed in some wikitext. See bug 19226.
3763 * @param string $wrap
3765 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3766 $msgSpecs = func_get_args();
3767 array_shift( $msgSpecs );
3768 $msgSpecs = array_values( $msgSpecs );
3770 foreach ( $msgSpecs as $n => $spec ) {
3771 if ( is_array( $spec ) ) {
3773 $name = array_shift( $args );
3774 if ( isset( $args['options'] ) ) {
3775 unset( $args['options'] );
3777 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3785 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3787 $this->addWikiText( $s );
3791 * Include jQuery core. Use this to avoid loading it multiple times
3792 * before we get a usable script loader.
3794 * @param array $modules List of jQuery modules which should be loaded
3795 * @return array The list of modules which were not loaded.
3797 * @deprecated since 1.17
3799 public function includeJQuery( array $modules = array() ) {
3804 * Enables/disables TOC, doesn't override __NOTOC__
3808 public function enableTOC( $flag = true ) {
3809 $this->mEnableTOC
= $flag;
3816 public function isTOCEnabled() {
3817 return $this->mEnableTOC
;
3821 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3825 public function enableSectionEditLinks( $flag = true ) {
3826 $this->mEnableSectionEditLinks
= $flag;
3833 public function sectionEditLinksEnabled() {
3834 return $this->mEnableSectionEditLinks
;