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();
165 /** @var ResourceLoader */
166 protected $mResourceLoader;
169 protected $mJsConfigVars = array();
172 protected $mTemplateIds = array();
175 protected $mImageTimeKeys = array();
178 public $mRedirectCode = '';
180 protected $mFeedLinksAppendQuery = null;
183 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
184 * @see ResourceLoaderModule::$origin
185 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 protected $mAllowedModules = array(
188 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
191 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
192 protected $mDoNothing = false;
197 protected $mContainsNewMagic = 0;
200 * lazy initialised, use parserOptions()
203 protected $mParserOptions = null;
206 * Handles the Atom / RSS links.
207 * We probably only support Atom in 2011.
208 * @see $wgAdvertisedFeedTypes
210 private $mFeedLinks = array();
212 // Gwicke work on squid caching? Roughly from 2003.
213 protected $mEnableClientCache = true;
215 /** @var bool Flag if output should only contain the body of the article. */
216 private $mArticleBodyOnly = false;
219 protected $mNewSectionLink = false;
222 protected $mHideNewSectionLink = false;
225 * @var bool Comes from the parser. This was probably made to load CSS/JS
226 * only if we had "<gallery>". Used directly in CategoryPage.php.
227 * Looks like resource loader can replace this.
229 public $mNoGallery = false;
232 private $mPageTitleActionText = '';
235 private $mParseWarnings = array();
237 /** @var int Cache stuff. Looks like mEnableClientCache */
238 protected $mSquidMaxage = 0;
241 * @var bool Controls if anti-clickjacking / frame-breaking headers will
242 * be sent. This should be done for pages where edit actions are possible.
243 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
245 protected $mPreventClickjacking = true;
247 /** @var int To include the variable {{REVISIONID}} */
248 private $mRevisionId = null;
251 private $mRevisionTimestamp = null;
254 protected $mFileVersion = null;
257 * @var array An array of stylesheet filenames (relative from skins path),
258 * with options for CSS media, IE conditions, and RTL/LTR direction.
259 * For internal use; add settings in the skin via $this->addStyle()
261 * Style again! This seems like a code duplication since we already have
262 * mStyles. This is what makes Open Source amazing.
264 protected $styles = array();
267 * Whether jQuery is already handled.
269 protected $mJQueryDone = false;
271 private $mIndexPolicy = 'index';
272 private $mFollowPolicy = 'follow';
273 private $mVaryHeader = array(
274 'Accept-Encoding' => array( 'list-contains=gzip' ),
278 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
283 private $mRedirectedFrom = null;
286 * Additional key => value data
288 private $mProperties = array();
291 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
293 private $mTarget = null;
296 * @var bool Whether parser output should contain table of contents
298 private $mEnableTOC = true;
301 * @var bool Whether parser output should contain section edit links
303 private $mEnableSectionEditLinks = true;
306 * Constructor for OutputPage. This should not be called directly.
307 * Instead a new RequestContext should be created and it will implicitly create
308 * a OutputPage tied to that context.
309 * @param IContextSource|null $context
311 function __construct( IContextSource
$context = null ) {
312 if ( $context === null ) {
313 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
314 wfDeprecated( __METHOD__
, '1.18' );
316 $this->setContext( $context );
321 * Redirect to $url rather than displaying the normal page
323 * @param string $url URL
324 * @param string $responsecode HTTP status code
326 public function redirect( $url, $responsecode = '302' ) {
327 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
328 $this->mRedirect
= str_replace( "\n", '', $url );
329 $this->mRedirectCode
= $responsecode;
333 * Get the URL to redirect to, or an empty string if not redirect URL set
337 public function getRedirect() {
338 return $this->mRedirect
;
342 * Set the HTTP status code to send with the output.
344 * @param int $statusCode
346 public function setStatusCode( $statusCode ) {
347 $this->mStatusCode
= $statusCode;
351 * Add a new "<meta>" tag
352 * To add an http-equiv meta tag, precede the name with "http:"
354 * @param string $name Tag name
355 * @param string $val Tag value
357 function addMeta( $name, $val ) {
358 array_push( $this->mMetatags
, array( $name, $val ) );
362 * Returns the current <meta> tags
367 public function getMetaTags() {
368 return $this->mMetatags
;
372 * Add a new \<link\> tag to the page header.
374 * Note: use setCanonicalUrl() for rel=canonical.
376 * @param array $linkarr Associative array of attributes.
378 function addLink( array $linkarr ) {
379 array_push( $this->mLinktags
, $linkarr );
383 * Returns the current <link> tags
388 public function getLinkTags() {
389 return $this->mLinktags
;
393 * Add a new \<link\> with "rel" attribute set to "meta"
395 * @param array $linkarr Associative array mapping attribute names to their
396 * values, both keys and values will be escaped, and the
397 * "rel" attribute will be automatically added
399 function addMetadataLink( array $linkarr ) {
400 $linkarr['rel'] = $this->getMetadataAttribute();
401 $this->addLink( $linkarr );
405 * Set the URL to be used for the <link rel=canonical>. This should be used
406 * in preference to addLink(), to avoid duplicate link tags.
409 function setCanonicalUrl( $url ) {
410 $this->mCanonicalUrl
= $url;
414 * Returns the URL to be used for the <link rel=canonical> if
418 * @return bool|string
420 public function getCanonicalUrl() {
421 return $this->mCanonicalUrl
;
425 * Get the value of the "rel" attribute for metadata links
429 public function getMetadataAttribute() {
430 # note: buggy CC software only reads first "meta" link
431 static $haveMeta = false;
433 return 'alternate meta';
441 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
443 * @param string $script Raw HTML
445 function addScript( $script ) {
446 $this->mScripts
.= $script . "\n";
450 * Register and add a stylesheet from an extension directory.
452 * @param string $url Path to sheet. Provide either a full url (beginning
453 * with 'http', etc) or a relative path from the document root
454 * (beginning with '/'). Otherwise it behaves identically to
455 * addStyle() and draws from the /skins folder.
457 public function addExtensionStyle( $url ) {
458 array_push( $this->mExtStyles
, $url );
462 * Get all styles added by extensions
466 function getExtStyle() {
467 return $this->mExtStyles
;
471 * Add a JavaScript file out of skins/common, or a given relative path.
473 * @param string $file Filename in skins/common or complete on-server path
475 * @param string $version Style version of the file. Defaults to $wgStyleVersion
477 public function addScriptFile( $file, $version = null ) {
478 // See if $file parameter is an absolute URL or begins with a slash
479 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
482 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
484 if ( is_null( $version ) ) {
485 $version = $this->getConfig()->get( 'StyleVersion' );
487 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
491 * Add a self-contained script tag with the given contents
493 * @param string $script JavaScript text, no "<script>" tags
495 public function addInlineScript( $script ) {
496 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
500 * Get all registered JS and CSS tags for the header.
503 * @deprecated since 1.24 Use OutputPage::headElement to build the full header.
505 function getScript() {
506 wfDeprecated( __METHOD__
, '1.24' );
507 return $this->mScripts
. $this->getHeadItems();
511 * Filter an array of modules to remove insufficiently trustworthy members, and modules
512 * which are no longer registered (eg a page is cached before an extension is disabled)
513 * @param array $modules
514 * @param string|null $position If not null, only return modules with this position
515 * @param string $type
518 protected function filterModules( array $modules, $position = null,
519 $type = ResourceLoaderModule
::TYPE_COMBINED
521 $resourceLoader = $this->getResourceLoader();
522 $filteredModules = array();
523 foreach ( $modules as $val ) {
524 $module = $resourceLoader->getModule( $val );
525 if ( $module instanceof ResourceLoaderModule
526 && $module->getOrigin() <= $this->getAllowedModules( $type )
527 && ( is_null( $position ) ||
$module->getPosition() == $position )
528 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
530 $filteredModules[] = $val;
533 return $filteredModules;
537 * Get the list of modules to include on this page
539 * @param bool $filter Whether to filter out insufficiently trustworthy modules
540 * @param string|null $position If not null, only return modules with this position
541 * @param string $param
542 * @return array Array of module names
544 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
545 $modules = array_values( array_unique( $this->$param ) );
547 ?
$this->filterModules( $modules, $position )
552 * Add one or more modules recognized by the resource loader. Modules added
553 * through this function will be loaded by the resource loader when the
556 * @param string|array $modules Module name (string) or array of module names
558 public function addModules( $modules ) {
559 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
563 * Get the list of module JS to include on this page
565 * @param bool $filter
566 * @param string|null $position
568 * @return array Array of module names
570 public function getModuleScripts( $filter = false, $position = null ) {
571 return $this->getModules( $filter, $position, 'mModuleScripts' );
575 * Add only JS of one or more modules recognized by the resource loader. Module
576 * scripts added through this function will be loaded by the resource loader when
579 * @param string|array $modules Module name (string) or array of module names
581 public function addModuleScripts( $modules ) {
582 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
586 * Get the list of module CSS to include on this page
588 * @param bool $filter
589 * @param string|null $position
591 * @return array Array of module names
593 public function getModuleStyles( $filter = false, $position = null ) {
595 $resourceLoader = $this->getResourceLoader();
597 foreach ( $this->mModuleStyles
as $val ) {
598 $module = $resourceLoader->getModule( $val );
600 if ( $module instanceof ResourceLoaderModule
&& $module->isPositionDefault() ) {
601 $warning = __METHOD__
. ': style module should define its position explicitly: ' . $val . ' ' . get_class( $module );
602 wfDebugLog( 'resourceloader', $warning );
603 wfLogWarning( $warning );
607 return $this->getModules( $filter, $position, 'mModuleStyles' );
611 * Add only CSS of one or more modules recognized by the resource loader.
613 * Module styles added through this function will be added using standard link CSS
614 * tags, rather than as a combined Javascript and CSS package. Thus, they will
615 * load when JavaScript is disabled (unless CSS also happens to be disabled).
617 * @param string|array $modules Module name (string) or array of module names
619 public function addModuleStyles( $modules ) {
620 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
624 * Get the list of module messages to include on this page
626 * @deprecated since 1.26 Obsolete
627 * @param bool $filter
628 * @param string|null $position
629 * @return array Array of module names
631 public function getModuleMessages( $filter = false, $position = null ) {
632 wfDeprecated( __METHOD__
, '1.26' );
637 * Load messages of one or more ResourceLoader modules.
639 * @deprecated since 1.26 Use addModules() instead
640 * @param string|array $modules Module name (string) or array of module names
642 public function addModuleMessages( $modules ) {
643 wfDeprecated( __METHOD__
, '1.26' );
647 * @return null|string ResourceLoader target
649 public function getTarget() {
650 return $this->mTarget
;
654 * Sets ResourceLoader target for load.php links. If null, will be omitted
656 * @param string|null $target
658 public function setTarget( $target ) {
659 $this->mTarget
= $target;
663 * Get an array of head items
667 function getHeadItemsArray() {
668 return $this->mHeadItems
;
672 * Get all header items in a string
675 * @deprecated since 1.24 Use OutputPage::headElement or
676 * if absolutely necessary use OutputPage::getHeadItemsArray
678 function getHeadItems() {
679 wfDeprecated( __METHOD__
, '1.24' );
681 foreach ( $this->mHeadItems
as $item ) {
688 * Add or replace an header item to the output
690 * @param string $name Item name
691 * @param string $value Raw HTML
693 public function addHeadItem( $name, $value ) {
694 $this->mHeadItems
[$name] = $value;
698 * Check if the header item $name is already set
700 * @param string $name Item name
703 public function hasHeadItem( $name ) {
704 return isset( $this->mHeadItems
[$name] );
708 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
710 * @param string $tag Value of "ETag" header
712 function setETag( $tag ) {
717 * Set whether the output should only contain the body of the article,
718 * without any skin, sidebar, etc.
719 * Used e.g. when calling with "action=render".
721 * @param bool $only Whether to output only the body of the article
723 public function setArticleBodyOnly( $only ) {
724 $this->mArticleBodyOnly
= $only;
728 * Return whether the output will contain only the body of the article
732 public function getArticleBodyOnly() {
733 return $this->mArticleBodyOnly
;
737 * Set an additional output property
740 * @param string $name
741 * @param mixed $value
743 public function setProperty( $name, $value ) {
744 $this->mProperties
[$name] = $value;
748 * Get an additional output property
751 * @param string $name
752 * @return mixed Property value or null if not found
754 public function getProperty( $name ) {
755 if ( isset( $this->mProperties
[$name] ) ) {
756 return $this->mProperties
[$name];
763 * checkLastModified tells the client to use the client-cached page if
764 * possible. If successful, the OutputPage is disabled so that
765 * any future call to OutputPage->output() have no effect.
767 * Side effect: sets mLastModified for Last-Modified header
769 * @param string $timestamp
771 * @return bool True if cache-ok headers was sent.
773 public function checkLastModified( $timestamp ) {
774 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
775 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
778 $config = $this->getConfig();
779 if ( !$config->get( 'CachePages' ) ) {
780 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
784 $timestamp = wfTimestamp( TS_MW
, $timestamp );
785 $modifiedTimes = array(
786 'page' => $timestamp,
787 'user' => $this->getUser()->getTouched(),
788 'epoch' => $config->get( 'CacheEpoch' )
790 if ( $config->get( 'UseSquid' ) ) {
791 // bug 44570: the core page itself may not change, but resources might
792 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
794 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
796 $maxModified = max( $modifiedTimes );
797 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
799 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
800 if ( $clientHeader === false ) {
801 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header\n", 'log' );
805 # IE sends sizes after the date like this:
806 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
807 # this breaks strtotime().
808 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
810 wfSuppressWarnings(); // E_STRICT system time bitching
811 $clientHeaderTime = strtotime( $clientHeader );
813 if ( !$clientHeaderTime ) {
815 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
818 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
822 foreach ( $modifiedTimes as $name => $value ) {
823 if ( $info !== '' ) {
826 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
829 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
830 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ) . "\n", 'log' );
831 wfDebug( __METHOD__
. ": effective Last-Modified: " .
832 wfTimestamp( TS_ISO_8601
, $maxModified ) . "\n", 'log' );
833 if ( $clientHeaderTime < $maxModified ) {
834 wfDebug( __METHOD__
. ": STALE, $info\n", 'log' );
839 # Give a 304 response code and disable body output
840 wfDebug( __METHOD__
. ": NOT MODIFIED, $info\n", 'log' );
841 ini_set( 'zlib.output_compression', 0 );
842 $this->getRequest()->response()->header( "HTTP/1.1 304 Not Modified" );
843 $this->sendCacheControl();
846 // Don't output a compressed blob when using ob_gzhandler;
847 // it's technically against HTTP spec and seems to confuse
848 // Firefox when the response gets split over two packets.
849 wfClearOutputBuffers();
855 * Override the last modified timestamp
857 * @param string $timestamp New timestamp, in a format readable by
860 public function setLastModified( $timestamp ) {
861 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
865 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
867 * @param string $policy The literal string to output as the contents of
868 * the meta tag. Will be parsed according to the spec and output in
872 public function setRobotPolicy( $policy ) {
873 $policy = Article
::formatRobotPolicy( $policy );
875 if ( isset( $policy['index'] ) ) {
876 $this->setIndexPolicy( $policy['index'] );
878 if ( isset( $policy['follow'] ) ) {
879 $this->setFollowPolicy( $policy['follow'] );
884 * Set the index policy for the page, but leave the follow policy un-
887 * @param string $policy Either 'index' or 'noindex'.
890 public function setIndexPolicy( $policy ) {
891 $policy = trim( $policy );
892 if ( in_array( $policy, array( 'index', 'noindex' ) ) ) {
893 $this->mIndexPolicy
= $policy;
898 * Set the follow policy for the page, but leave the index policy un-
901 * @param string $policy Either 'follow' or 'nofollow'.
904 public function setFollowPolicy( $policy ) {
905 $policy = trim( $policy );
906 if ( in_array( $policy, array( 'follow', 'nofollow' ) ) ) {
907 $this->mFollowPolicy
= $policy;
912 * Set the new value of the "action text", this will be added to the
913 * "HTML title", separated from it with " - ".
915 * @param string $text New value of the "action text"
917 public function setPageTitleActionText( $text ) {
918 $this->mPageTitleActionText
= $text;
922 * Get the value of the "action text"
926 public function getPageTitleActionText() {
927 return $this->mPageTitleActionText
;
931 * "HTML title" means the contents of "<title>".
932 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
934 * @param string|Message $name
936 public function setHTMLTitle( $name ) {
937 if ( $name instanceof Message
) {
938 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
940 $this->mHTMLtitle
= $name;
945 * Return the "HTML title", i.e. the content of the "<title>" tag.
949 public function getHTMLTitle() {
950 return $this->mHTMLtitle
;
954 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
958 public function setRedirectedFrom( $t ) {
959 $this->mRedirectedFrom
= $t;
963 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
964 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
965 * but not bad tags like \<script\>. This function automatically sets
966 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
967 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
968 * good tags like \<i\> will be dropped entirely.
970 * @param string|Message $name
972 public function setPageTitle( $name ) {
973 if ( $name instanceof Message
) {
974 $name = $name->setContext( $this->getContext() )->text();
977 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
978 # but leave "<i>foobar</i>" alone
979 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
980 $this->mPagetitle
= $nameWithTags;
982 # change "<i>foo&bar</i>" to "foo&bar"
984 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
985 ->inContentLanguage()
990 * Return the "page title", i.e. the content of the \<h1\> tag.
994 public function getPageTitle() {
995 return $this->mPagetitle
;
999 * Set the Title object to use
1003 public function setTitle( Title
$t ) {
1004 $this->getContext()->setTitle( $t );
1008 * Replace the subtitle with $str
1010 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1012 public function setSubtitle( $str ) {
1013 $this->clearSubtitle();
1014 $this->addSubtitle( $str );
1018 * Add $str to the subtitle
1020 * @deprecated since 1.19; use addSubtitle() instead
1021 * @param string|Message $str String or Message to add to the subtitle
1023 public function appendSubtitle( $str ) {
1024 $this->addSubtitle( $str );
1028 * Add $str to the subtitle
1030 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1032 public function addSubtitle( $str ) {
1033 if ( $str instanceof Message
) {
1034 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1036 $this->mSubtitle
[] = $str;
1041 * Build message object for a subtitle containing a backlink to a page
1043 * @param Title $title Title to link to
1044 * @param array $query Array of additional parameters to include in the link
1048 public static function buildBacklinkSubtitle( Title
$title, $query = array() ) {
1049 if ( $title->isRedirect() ) {
1050 $query['redirect'] = 'no';
1052 return wfMessage( 'backlinksubtitle' )
1053 ->rawParams( Linker
::link( $title, null, array(), $query ) );
1057 * Add a subtitle containing a backlink to a page
1059 * @param Title $title Title to link to
1060 * @param array $query Array of additional parameters to include in the link
1062 public function addBacklinkSubtitle( Title
$title, $query = array() ) {
1063 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1067 * Clear the subtitles
1069 public function clearSubtitle() {
1070 $this->mSubtitle
= array();
1078 public function getSubtitle() {
1079 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1083 * Set the page as printable, i.e. it'll be displayed with all
1084 * print styles included
1086 public function setPrintable() {
1087 $this->mPrintable
= true;
1091 * Return whether the page is "printable"
1095 public function isPrintable() {
1096 return $this->mPrintable
;
1100 * Disable output completely, i.e. calling output() will have no effect
1102 public function disable() {
1103 $this->mDoNothing
= true;
1107 * Return whether the output will be completely disabled
1111 public function isDisabled() {
1112 return $this->mDoNothing
;
1116 * Show an "add new section" link?
1120 public function showNewSectionLink() {
1121 return $this->mNewSectionLink
;
1125 * Forcibly hide the new section link?
1129 public function forceHideNewSectionLink() {
1130 return $this->mHideNewSectionLink
;
1134 * Add or remove feed links in the page header
1135 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1136 * for the new version
1137 * @see addFeedLink()
1139 * @param bool $show True: add default feeds, false: remove all feeds
1141 public function setSyndicated( $show = true ) {
1143 $this->setFeedAppendQuery( false );
1145 $this->mFeedLinks
= array();
1150 * Add default feeds to the page header
1151 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1152 * for the new version
1153 * @see addFeedLink()
1155 * @param string $val Query to append to feed links or false to output
1158 public function setFeedAppendQuery( $val ) {
1159 $this->mFeedLinks
= array();
1161 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1162 $query = "feed=$type";
1163 if ( is_string( $val ) ) {
1164 $query .= '&' . $val;
1166 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1171 * Add a feed link to the page header
1173 * @param string $format Feed type, should be a key of $wgFeedClasses
1174 * @param string $href URL
1176 public function addFeedLink( $format, $href ) {
1177 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1178 $this->mFeedLinks
[$format] = $href;
1183 * Should we output feed links for this page?
1186 public function isSyndicated() {
1187 return count( $this->mFeedLinks
) > 0;
1191 * Return URLs for each supported syndication format for this page.
1192 * @return array Associating format keys with URLs
1194 public function getSyndicationLinks() {
1195 return $this->mFeedLinks
;
1199 * Will currently always return null
1203 public function getFeedAppendQuery() {
1204 return $this->mFeedLinksAppendQuery
;
1208 * Set whether the displayed content is related to the source of the
1209 * corresponding article on the wiki
1210 * Setting true will cause the change "article related" toggle to true
1214 public function setArticleFlag( $v ) {
1215 $this->mIsarticle
= $v;
1217 $this->mIsArticleRelated
= $v;
1222 * Return whether the content displayed page is related to the source of
1223 * the corresponding article on the wiki
1227 public function isArticle() {
1228 return $this->mIsarticle
;
1232 * Set whether this page is related an article on the wiki
1233 * Setting false will cause the change of "article flag" toggle to false
1237 public function setArticleRelated( $v ) {
1238 $this->mIsArticleRelated
= $v;
1240 $this->mIsarticle
= false;
1245 * Return whether this page is related an article on the wiki
1249 public function isArticleRelated() {
1250 return $this->mIsArticleRelated
;
1254 * Add new language links
1256 * @param array $newLinkArray Associative array mapping language code to the page
1259 public function addLanguageLinks( array $newLinkArray ) {
1260 $this->mLanguageLinks +
= $newLinkArray;
1264 * Reset the language links and add new language links
1266 * @param array $newLinkArray Associative array mapping language code to the page
1269 public function setLanguageLinks( array $newLinkArray ) {
1270 $this->mLanguageLinks
= $newLinkArray;
1274 * Get the list of language links
1276 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1278 public function getLanguageLinks() {
1279 return $this->mLanguageLinks
;
1283 * Add an array of categories, with names in the keys
1285 * @param array $categories Mapping category name => sort key
1287 public function addCategoryLinks( array $categories ) {
1290 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1294 # Add the links to a LinkBatch
1295 $arr = array( NS_CATEGORY
=> $categories );
1296 $lb = new LinkBatch
;
1297 $lb->setArray( $arr );
1299 # Fetch existence plus the hiddencat property
1300 $dbr = wfGetDB( DB_SLAVE
);
1301 $fields = array( 'page_id', 'page_namespace', 'page_title', 'page_len',
1302 'page_is_redirect', 'page_latest', 'pp_value' );
1304 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1305 $fields[] = 'page_content_model';
1308 $res = $dbr->select( array( 'page', 'page_props' ),
1310 $lb->constructSet( 'page', $dbr ),
1313 array( 'page_props' => array( 'LEFT JOIN', array(
1314 'pp_propname' => 'hiddencat',
1319 # Add the results to the link cache
1320 $lb->addResultToCache( LinkCache
::singleton(), $res );
1322 # Set all the values to 'normal'.
1323 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1325 # Mark hidden categories
1326 foreach ( $res as $row ) {
1327 if ( isset( $row->pp_value
) ) {
1328 $categories[$row->page_title
] = 'hidden';
1332 # Add the remaining categories to the skin
1334 'OutputPageMakeCategoryLinks',
1335 array( &$this, $categories, &$this->mCategoryLinks
) )
1337 foreach ( $categories as $category => $type ) {
1338 $origcategory = $category;
1339 $title = Title
::makeTitleSafe( NS_CATEGORY
, $category );
1343 $wgContLang->findVariantLink( $category, $title, true );
1344 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1347 $text = $wgContLang->convertHtml( $title->getText() );
1348 $this->mCategories
[] = $title->getText();
1349 $this->mCategoryLinks
[$type][] = Linker
::link( $title, $text );
1355 * Reset the category links (but not the category list) and add $categories
1357 * @param array $categories Mapping category name => sort key
1359 public function setCategoryLinks( array $categories ) {
1360 $this->mCategoryLinks
= array();
1361 $this->addCategoryLinks( $categories );
1365 * Get the list of category links, in a 2-D array with the following format:
1366 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1367 * hidden categories) and $link a HTML fragment with a link to the category
1372 public function getCategoryLinks() {
1373 return $this->mCategoryLinks
;
1377 * Get the list of category names this page belongs to
1379 * @return array Array of strings
1381 public function getCategories() {
1382 return $this->mCategories
;
1386 * Add an array of indicators, with their identifiers as array
1387 * keys and HTML contents as values.
1389 * In case of duplicate keys, existing values are overwritten.
1391 * @param array $indicators
1394 public function setIndicators( array $indicators ) {
1395 $this->mIndicators
= $indicators +
$this->mIndicators
;
1396 // Keep ordered by key
1397 ksort( $this->mIndicators
);
1401 * Get the indicators associated with this page.
1403 * The array will be internally ordered by item keys.
1405 * @return array Keys: identifiers, values: HTML contents
1408 public function getIndicators() {
1409 return $this->mIndicators
;
1413 * Adds help link with an icon via page indicators.
1414 * Link target can be overridden by a local message containing a wikilink:
1415 * the message key is: lowercase action or special page name + '-helppage'.
1416 * @param string $to Target MediaWiki.org page title or encoded URL.
1417 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1420 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1421 $this->addModuleStyles( 'mediawiki.helplink' );
1422 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1424 if ( $overrideBaseUrl ) {
1427 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1428 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1431 $link = Html
::rawElement(
1435 'target' => '_blank',
1436 'class' => 'mw-helplink',
1441 $this->setIndicators( array( 'mw-helplink' => $link ) );
1445 * Do not allow scripts which can be modified by wiki users to load on this page;
1446 * only allow scripts bundled with, or generated by, the software.
1447 * Site-wide styles are controlled by a config setting, since they can be
1448 * used to create a custom skin/theme, but not user-specific ones.
1450 * @todo this should be given a more accurate name
1452 public function disallowUserJs() {
1453 $this->reduceAllowedModules(
1454 ResourceLoaderModule
::TYPE_SCRIPTS
,
1455 ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
1458 // Site-wide styles are controlled by a config setting, see bug 71621
1459 // for background on why. User styles are never allowed.
1460 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1461 $styleOrigin = ResourceLoaderModule
::ORIGIN_USER_SITEWIDE
;
1463 $styleOrigin = ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
;
1465 $this->reduceAllowedModules(
1466 ResourceLoaderModule
::TYPE_STYLES
,
1472 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1473 * @see ResourceLoaderModule::$origin
1474 * @param string $type ResourceLoaderModule TYPE_ constant
1475 * @return int ResourceLoaderModule ORIGIN_ class constant
1477 public function getAllowedModules( $type ) {
1478 if ( $type == ResourceLoaderModule
::TYPE_COMBINED
) {
1479 return min( array_values( $this->mAllowedModules
) );
1481 return isset( $this->mAllowedModules
[$type] )
1482 ?
$this->mAllowedModules
[$type]
1483 : ResourceLoaderModule
::ORIGIN_ALL
;
1488 * Set the highest level of CSS/JS untrustworthiness allowed
1490 * @deprecated since 1.24 Raising level of allowed untrusted content is no longer supported.
1491 * Use reduceAllowedModules() instead
1492 * @param string $type ResourceLoaderModule TYPE_ constant
1493 * @param int $level ResourceLoaderModule class constant
1495 public function setAllowedModules( $type, $level ) {
1496 wfDeprecated( __METHOD__
, '1.24' );
1497 $this->reduceAllowedModules( $type, $level );
1501 * Limit the highest level of CSS/JS untrustworthiness allowed.
1503 * If passed the same or a higher level than the current level of untrustworthiness set, the
1504 * level will remain unchanged.
1506 * @param string $type
1507 * @param int $level ResourceLoaderModule class constant
1509 public function reduceAllowedModules( $type, $level ) {
1510 $this->mAllowedModules
[$type] = min( $this->getAllowedModules( $type ), $level );
1514 * Prepend $text to the body HTML
1516 * @param string $text HTML
1518 public function prependHTML( $text ) {
1519 $this->mBodytext
= $text . $this->mBodytext
;
1523 * Append $text to the body HTML
1525 * @param string $text HTML
1527 public function addHTML( $text ) {
1528 $this->mBodytext
.= $text;
1532 * Shortcut for adding an Html::element via addHTML.
1536 * @param string $element
1537 * @param array $attribs
1538 * @param string $contents
1540 public function addElement( $element, array $attribs = array(), $contents = '' ) {
1541 $this->addHTML( Html
::element( $element, $attribs, $contents ) );
1545 * Clear the body HTML
1547 public function clearHTML() {
1548 $this->mBodytext
= '';
1554 * @return string HTML
1556 public function getHTML() {
1557 return $this->mBodytext
;
1561 * Get/set the ParserOptions object to use for wikitext parsing
1563 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1564 * current ParserOption object
1565 * @return ParserOptions
1567 public function parserOptions( $options = null ) {
1568 if ( !$this->mParserOptions
) {
1569 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1570 $this->mParserOptions
->setEditSection( false );
1572 return wfSetVar( $this->mParserOptions
, $options );
1576 * Set the revision ID which will be seen by the wiki text parser
1577 * for things such as embedded {{REVISIONID}} variable use.
1579 * @param int|null $revid An positive integer, or null
1580 * @return mixed Previous value
1582 public function setRevisionId( $revid ) {
1583 $val = is_null( $revid ) ?
null : intval( $revid );
1584 return wfSetVar( $this->mRevisionId
, $val );
1588 * Get the displayed revision ID
1592 public function getRevisionId() {
1593 return $this->mRevisionId
;
1597 * Set the timestamp of the revision which will be displayed. This is used
1598 * to avoid a extra DB call in Skin::lastModified().
1600 * @param string|null $timestamp
1601 * @return mixed Previous value
1603 public function setRevisionTimestamp( $timestamp ) {
1604 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1608 * Get the timestamp of displayed revision.
1609 * This will be null if not filled by setRevisionTimestamp().
1611 * @return string|null
1613 public function getRevisionTimestamp() {
1614 return $this->mRevisionTimestamp
;
1618 * Set the displayed file version
1620 * @param File|bool $file
1621 * @return mixed Previous value
1623 public function setFileVersion( $file ) {
1625 if ( $file instanceof File
&& $file->exists() ) {
1626 $val = array( 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() );
1628 return wfSetVar( $this->mFileVersion
, $val, true );
1632 * Get the displayed file version
1634 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1636 public function getFileVersion() {
1637 return $this->mFileVersion
;
1641 * Get the templates used on this page
1643 * @return array (namespace => dbKey => revId)
1646 public function getTemplateIds() {
1647 return $this->mTemplateIds
;
1651 * Get the files used on this page
1653 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1656 public function getFileSearchOptions() {
1657 return $this->mImageTimeKeys
;
1661 * Convert wikitext to HTML and add it to the buffer
1662 * Default assumes that the current page title will be used.
1664 * @param string $text
1665 * @param bool $linestart Is this the start of a line?
1666 * @param bool $interface Is this text in the user interface language?
1667 * @throws MWException
1669 public function addWikiText( $text, $linestart = true, $interface = true ) {
1670 $title = $this->getTitle(); // Work around E_STRICT
1672 throw new MWException( 'Title is null' );
1674 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1678 * Add wikitext with a custom Title object
1680 * @param string $text Wikitext
1681 * @param Title $title
1682 * @param bool $linestart Is this the start of a line?
1684 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1685 $this->addWikiTextTitle( $text, $title, $linestart );
1689 * Add wikitext with a custom Title object and tidy enabled.
1691 * @param string $text Wikitext
1692 * @param Title $title
1693 * @param bool $linestart Is this the start of a line?
1695 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1696 $this->addWikiTextTitle( $text, $title, $linestart, true );
1700 * Add wikitext with tidy enabled
1702 * @param string $text Wikitext
1703 * @param bool $linestart Is this the start of a line?
1705 public function addWikiTextTidy( $text, $linestart = true ) {
1706 $title = $this->getTitle();
1707 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1711 * Add wikitext with a custom Title object
1713 * @param string $text Wikitext
1714 * @param Title $title
1715 * @param bool $linestart Is this the start of a line?
1716 * @param bool $tidy Whether to use tidy
1717 * @param bool $interface Whether it is an interface message
1718 * (for example disables conversion)
1720 public function addWikiTextTitle( $text, Title
$title, $linestart,
1721 $tidy = false, $interface = false
1725 $popts = $this->parserOptions();
1726 $oldTidy = $popts->setTidy( $tidy );
1727 $popts->setInterfaceMessage( (bool)$interface );
1729 $parserOutput = $wgParser->getFreshParser()->parse(
1730 $text, $title, $popts,
1731 $linestart, true, $this->mRevisionId
1734 $popts->setTidy( $oldTidy );
1736 $this->addParserOutput( $parserOutput );
1741 * Add a ParserOutput object, but without Html.
1743 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1744 * @param ParserOutput $parserOutput
1746 public function addParserOutputNoText( $parserOutput ) {
1747 $this->addParserOutputMetadata( $parserOutput );
1751 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1752 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1756 * @param ParserOutput $parserOutput
1758 public function addParserOutputMetadata( $parserOutput ) {
1759 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1760 $this->addCategoryLinks( $parserOutput->getCategories() );
1761 $this->setIndicators( $parserOutput->getIndicators() );
1762 $this->mNewSectionLink
= $parserOutput->getNewSection();
1763 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1765 $this->mParseWarnings
= $parserOutput->getWarnings();
1766 if ( !$parserOutput->isCacheable() ) {
1767 $this->enableClientCache( false );
1769 $this->mNoGallery
= $parserOutput->getNoGallery();
1770 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1771 $this->addModules( $parserOutput->getModules() );
1772 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1773 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1774 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1775 $this->mPreventClickjacking
= $this->mPreventClickjacking
1776 ||
$parserOutput->preventClickjacking();
1778 // Template versioning...
1779 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1780 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1781 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1783 $this->mTemplateIds
[$ns] = $dbks;
1786 // File versioning...
1787 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1788 $this->mImageTimeKeys
[$dbk] = $data;
1791 // Hooks registered in the object
1792 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1793 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1794 list( $hookName, $data ) = $hookInfo;
1795 if ( isset( $parserOutputHooks[$hookName] ) ) {
1796 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1800 // Link flags are ignored for now, but may in the future be
1801 // used to mark individual language links.
1802 $linkFlags = array();
1803 Hooks
::run( 'LanguageLinks', array( $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ) );
1804 Hooks
::run( 'OutputPageParserOutput', array( &$this, $parserOutput ) );
1808 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1809 * ParserOutput object, without any other metadata.
1812 * @param ParserOutput $parserOutput
1814 public function addParserOutputContent( $parserOutput ) {
1815 $this->addParserOutputText( $parserOutput );
1817 $this->addModules( $parserOutput->getModules() );
1818 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1819 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1821 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1825 * Add the HTML associated with a ParserOutput object, without any metadata.
1828 * @param ParserOutput $parserOutput
1830 public function addParserOutputText( $parserOutput ) {
1831 $text = $parserOutput->getText();
1832 Hooks
::run( 'OutputPageBeforeHTML', array( &$this, &$text ) );
1833 $this->addHTML( $text );
1837 * Add everything from a ParserOutput object.
1839 * @param ParserOutput $parserOutput
1841 function addParserOutput( $parserOutput ) {
1842 $this->addParserOutputMetadata( $parserOutput );
1843 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1845 // Touch section edit links only if not previously disabled
1846 if ( $parserOutput->getEditSectionTokens() ) {
1847 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1850 $this->addParserOutputText( $parserOutput );
1854 * Add the output of a QuickTemplate to the output buffer
1856 * @param QuickTemplate $template
1858 public function addTemplate( &$template ) {
1859 $this->addHTML( $template->getHTML() );
1863 * Parse wikitext and return the HTML.
1865 * @param string $text
1866 * @param bool $linestart Is this the start of a line?
1867 * @param bool $interface Use interface language ($wgLang instead of
1868 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1869 * This also disables LanguageConverter.
1870 * @param Language $language Target language object, will override $interface
1871 * @throws MWException
1872 * @return string HTML
1874 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1877 if ( is_null( $this->getTitle() ) ) {
1878 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1881 $popts = $this->parserOptions();
1883 $popts->setInterfaceMessage( true );
1885 if ( $language !== null ) {
1886 $oldLang = $popts->setTargetLanguage( $language );
1889 $parserOutput = $wgParser->getFreshParser()->parse(
1890 $text, $this->getTitle(), $popts,
1891 $linestart, true, $this->mRevisionId
1895 $popts->setInterfaceMessage( false );
1897 if ( $language !== null ) {
1898 $popts->setTargetLanguage( $oldLang );
1901 return $parserOutput->getText();
1905 * Parse wikitext, strip paragraphs, and return the HTML.
1907 * @param string $text
1908 * @param bool $linestart Is this the start of a line?
1909 * @param bool $interface Use interface language ($wgLang instead of
1910 * $wgContLang) while parsing language sensitive magic
1911 * words like GRAMMAR and PLURAL
1912 * @return string HTML
1914 public function parseInline( $text, $linestart = true, $interface = false ) {
1915 $parsed = $this->parse( $text, $linestart, $interface );
1916 return Parser
::stripOuterParagraph( $parsed );
1920 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1922 * @param int $maxage Maximum cache time on the Squid, in seconds.
1924 public function setSquidMaxage( $maxage ) {
1925 $this->mSquidMaxage
= $maxage;
1929 * Use enableClientCache(false) to force it to send nocache headers
1931 * @param bool $state
1935 public function enableClientCache( $state ) {
1936 return wfSetVar( $this->mEnableClientCache
, $state );
1940 * Get the list of cookies that will influence on the cache
1944 function getCacheVaryCookies() {
1946 if ( $cookies === null ) {
1947 $config = $this->getConfig();
1948 $cookies = array_merge(
1950 $config->get( 'CookiePrefix' ) . 'Token',
1951 $config->get( 'CookiePrefix' ) . 'LoggedOut',
1955 $config->get( 'CacheVaryCookies' )
1957 Hooks
::run( 'GetCacheVaryCookies', array( $this, &$cookies ) );
1963 * Check if the request has a cache-varying cookie header
1964 * If it does, it's very important that we don't allow public caching
1968 function haveCacheVaryCookies() {
1969 $cookieHeader = $this->getRequest()->getHeader( 'cookie' );
1970 if ( $cookieHeader === false ) {
1973 $cvCookies = $this->getCacheVaryCookies();
1974 foreach ( $cvCookies as $cookieName ) {
1975 # Check for a simple string match, like the way squid does it
1976 if ( strpos( $cookieHeader, $cookieName ) !== false ) {
1977 wfDebug( __METHOD__
. ": found $cookieName\n" );
1981 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
1986 * Add an HTTP header that will influence on the cache
1988 * @param string $header Header name
1989 * @param array|null $option
1990 * @todo FIXME: Document the $option parameter; it appears to be for
1991 * X-Vary-Options but what format is acceptable?
1993 public function addVaryHeader( $header, $option = null ) {
1994 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
1995 $this->mVaryHeader
[$header] = (array)$option;
1996 } elseif ( is_array( $option ) ) {
1997 if ( is_array( $this->mVaryHeader
[$header] ) ) {
1998 $this->mVaryHeader
[$header] = array_merge( $this->mVaryHeader
[$header], $option );
2000 $this->mVaryHeader
[$header] = $option;
2003 $this->mVaryHeader
[$header] = array_unique( (array)$this->mVaryHeader
[$header] );
2007 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2008 * such as Accept-Encoding or Cookie
2012 public function getVaryHeader() {
2013 return 'Vary: ' . join( ', ', array_keys( $this->mVaryHeader
) );
2017 * Get a complete X-Vary-Options header
2021 public function getXVO() {
2022 $cvCookies = $this->getCacheVaryCookies();
2024 $cookiesOption = array();
2025 foreach ( $cvCookies as $cookieName ) {
2026 $cookiesOption[] = 'string-contains=' . $cookieName;
2028 $this->addVaryHeader( 'Cookie', $cookiesOption );
2031 foreach ( $this->mVaryHeader
as $header => $option ) {
2032 $newheader = $header;
2033 if ( is_array( $option ) && count( $option ) > 0 ) {
2034 $newheader .= ';' . implode( ';', $option );
2036 $headers[] = $newheader;
2038 $xvo = 'X-Vary-Options: ' . implode( ',', $headers );
2044 * bug 21672: Add Accept-Language to Vary and XVO headers
2045 * if there's no 'variant' parameter existed in GET.
2048 * /w/index.php?title=Main_page should always be served; but
2049 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2051 function addAcceptLanguage() {
2052 $title = $this->getTitle();
2053 if ( !$title instanceof Title
) {
2057 $lang = $title->getPageLanguage();
2058 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2059 $variants = $lang->getVariants();
2060 $aloption = array();
2061 foreach ( $variants as $variant ) {
2062 if ( $variant === $lang->getCode() ) {
2065 $aloption[] = 'string-contains=' . $variant;
2067 // IE and some other browsers use BCP 47 standards in
2068 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2069 // We should handle these too.
2070 $variantBCP47 = wfBCP47( $variant );
2071 if ( $variantBCP47 !== $variant ) {
2072 $aloption[] = 'string-contains=' . $variantBCP47;
2076 $this->addVaryHeader( 'Accept-Language', $aloption );
2081 * Set a flag which will cause an X-Frame-Options header appropriate for
2082 * edit pages to be sent. The header value is controlled by
2083 * $wgEditPageFrameOptions.
2085 * This is the default for special pages. If you display a CSRF-protected
2086 * form on an ordinary view page, then you need to call this function.
2088 * @param bool $enable
2090 public function preventClickjacking( $enable = true ) {
2091 $this->mPreventClickjacking
= $enable;
2095 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2096 * This can be called from pages which do not contain any CSRF-protected
2099 public function allowClickjacking() {
2100 $this->mPreventClickjacking
= false;
2104 * Get the prevent-clickjacking flag
2109 public function getPreventClickjacking() {
2110 return $this->mPreventClickjacking
;
2114 * Get the X-Frame-Options header value (without the name part), or false
2115 * if there isn't one. This is used by Skin to determine whether to enable
2116 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2120 public function getFrameOptions() {
2121 $config = $this->getConfig();
2122 if ( $config->get( 'BreakFrames' ) ) {
2124 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2125 return $config->get( 'EditPageFrameOptions' );
2131 * Send cache control HTTP headers
2133 public function sendCacheControl() {
2134 $response = $this->getRequest()->response();
2135 $config = $this->getConfig();
2136 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2137 $response->header( "ETag: $this->mETag" );
2140 $this->addVaryHeader( 'Cookie' );
2141 $this->addAcceptLanguage();
2143 # don't serve compressed data to clients who can't handle it
2144 # maintain different caches for logged-in users and non-logged in ones
2145 $response->header( $this->getVaryHeader() );
2147 if ( $config->get( 'UseXVO' ) ) {
2148 # Add an X-Vary-Options header for Squid with Wikimedia patches
2149 $response->header( $this->getXVO() );
2152 if ( $this->mEnableClientCache
) {
2154 $config->get( 'UseSquid' ) && session_id() == '' && !$this->isPrintable() &&
2155 $this->mSquidMaxage
!= 0 && !$this->haveCacheVaryCookies()
2157 if ( $config->get( 'UseESI' ) ) {
2158 # We'll purge the proxy cache explicitly, but require end user agents
2159 # to revalidate against the proxy on each visit.
2160 # Surrogate-Control controls our Squid, Cache-Control downstream caches
2161 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **\n", 'log' );
2162 # start with a shorter timeout for initial testing
2163 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2164 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2165 . '+' . $this->mSquidMaxage
. ', content="ESI/1.0"' );
2166 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2168 # We'll purge the proxy cache for anons explicitly, but require end user agents
2169 # to revalidate against the proxy on each visit.
2170 # IMPORTANT! The Squid needs to replace the Cache-Control header with
2171 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2172 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **\n", 'log' );
2173 # start with a shorter timeout for initial testing
2174 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2175 $response->header( 'Cache-Control: s-maxage=' . $this->mSquidMaxage
2176 . ', must-revalidate, max-age=0' );
2179 # We do want clients to cache if they can, but they *must* check for updates
2180 # on revisiting the page.
2181 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **\n", 'log' );
2182 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2183 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2185 if ( $this->mLastModified
) {
2186 $response->header( "Last-Modified: {$this->mLastModified}" );
2189 wfDebug( __METHOD__
. ": no caching **\n", 'log' );
2191 # In general, the absence of a last modified header should be enough to prevent
2192 # the client from using its cache. We send a few other things just to make sure.
2193 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2194 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2195 $response->header( 'Pragma: no-cache' );
2200 * Finally, all the text has been munged and accumulated into
2201 * the object, let's actually output it:
2203 public function output() {
2204 if ( $this->mDoNothing
) {
2208 $response = $this->getRequest()->response();
2209 $config = $this->getConfig();
2211 if ( $this->mRedirect
!= '' ) {
2212 # Standards require redirect URLs to be absolute
2213 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2215 $redirect = $this->mRedirect
;
2216 $code = $this->mRedirectCode
;
2218 if ( Hooks
::run( "BeforePageRedirect", array( $this, &$redirect, &$code ) ) ) {
2219 if ( $code == '301' ||
$code == '303' ) {
2220 if ( !$config->get( 'DebugRedirects' ) ) {
2221 $message = HttpStatus
::getMessage( $code );
2222 $response->header( "HTTP/1.1 $code $message" );
2224 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2226 if ( $config->get( 'VaryOnXFP' ) ) {
2227 $this->addVaryHeader( 'X-Forwarded-Proto' );
2229 $this->sendCacheControl();
2231 $response->header( "Content-Type: text/html; charset=utf-8" );
2232 if ( $config->get( 'DebugRedirects' ) ) {
2233 $url = htmlspecialchars( $redirect );
2234 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2235 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2236 print "</body>\n</html>\n";
2238 $response->header( 'Location: ' . $redirect );
2243 } elseif ( $this->mStatusCode
) {
2244 $message = HttpStatus
::getMessage( $this->mStatusCode
);
2246 $response->header( 'HTTP/1.1 ' . $this->mStatusCode
. ' ' . $message );
2250 # Buffer output; final headers may depend on later processing
2253 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2254 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2256 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2257 // jQuery etc. can work correctly.
2258 $response->header( 'X-UA-Compatible: IE=Edge' );
2260 // Prevent framing, if requested
2261 $frameOptions = $this->getFrameOptions();
2262 if ( $frameOptions ) {
2263 $response->header( "X-Frame-Options: $frameOptions" );
2266 if ( $this->mArticleBodyOnly
) {
2267 echo $this->mBodytext
;
2270 $sk = $this->getSkin();
2271 // add skin specific modules
2272 $modules = $sk->getDefaultModules();
2274 // enforce various default modules for all skins
2275 $coreModules = array(
2276 // keep this list as small as possible
2277 'mediawiki.page.startup',
2281 // Support for high-density display images if enabled
2282 if ( $config->get( 'ResponsiveImages' ) ) {
2283 $coreModules[] = 'mediawiki.hidpi';
2286 $this->addModules( $coreModules );
2287 foreach ( $modules as $group ) {
2288 $this->addModules( $group );
2290 MWDebug
::addModules( $this );
2292 // Hook that allows last minute changes to the output page, e.g.
2293 // adding of CSS or Javascript by extensions.
2294 Hooks
::run( 'BeforePageDisplay', array( &$this, &$sk ) );
2299 // This hook allows last minute changes to final overall output by modifying output buffer
2300 Hooks
::run( 'AfterFinalPageOutput', array( $this ) );
2302 $this->sendCacheControl();
2309 * Actually output something with print.
2311 * @param string $ins The string to output
2312 * @deprecated since 1.22 Use echo yourself.
2314 public function out( $ins ) {
2315 wfDeprecated( __METHOD__
, '1.22' );
2320 * Produce a "user is blocked" page.
2321 * @deprecated since 1.18
2323 function blockedPage() {
2324 throw new UserBlockedError( $this->getUser()->mBlock
);
2328 * Prepare this object to display an error page; disable caching and
2329 * indexing, clear the current text and redirect, set the page's title
2330 * and optionally an custom HTML title (content of the "<title>" tag).
2332 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2333 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2334 * optional, if not passed the "<title>" attribute will be
2335 * based on $pageTitle
2337 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2338 $this->setPageTitle( $pageTitle );
2339 if ( $htmlTitle !== false ) {
2340 $this->setHTMLTitle( $htmlTitle );
2342 $this->setRobotPolicy( 'noindex,nofollow' );
2343 $this->setArticleRelated( false );
2344 $this->enableClientCache( false );
2345 $this->mRedirect
= '';
2346 $this->clearSubtitle();
2351 * Output a standard error page
2353 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2354 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2355 * showErrorPage( 'titlemsg', $messageObject );
2356 * showErrorPage( $titleMessageObject, $messageObject );
2358 * @param string|Message $title Message key (string) for page title, or a Message object
2359 * @param string|Message $msg Message key (string) for page text, or a Message object
2360 * @param array $params Message parameters; ignored if $msg is a Message object
2362 public function showErrorPage( $title, $msg, $params = array() ) {
2363 if ( !$title instanceof Message
) {
2364 $title = $this->msg( $title );
2367 $this->prepareErrorPage( $title );
2369 if ( $msg instanceof Message
) {
2370 if ( $params !== array() ) {
2371 trigger_error( 'Argument ignored: $params. The message parameters argument '
2372 . 'is discarded when the $msg argument is a Message object instead of '
2373 . 'a string.', E_USER_NOTICE
);
2375 $this->addHTML( $msg->parseAsBlock() );
2377 $this->addWikiMsgArray( $msg, $params );
2380 $this->returnToMain();
2384 * Output a standard permission error page
2386 * @param array $errors Error message keys
2387 * @param string $action Action that was denied or null if unknown
2389 public function showPermissionsErrorPage( array $errors, $action = null ) {
2390 // For some action (read, edit, create and upload), display a "login to do this action"
2391 // error if all of the following conditions are met:
2392 // 1. the user is not logged in
2393 // 2. the only error is insufficient permissions (i.e. no block or something else)
2394 // 3. the error can be avoided simply by logging in
2395 if ( in_array( $action, array( 'read', 'edit', 'createpage', 'createtalk', 'upload' ) )
2396 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2397 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2398 && ( User
::groupHasPermission( 'user', $action )
2399 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2401 $displayReturnto = null;
2403 # Due to bug 32276, if a user does not have read permissions,
2404 # $this->getTitle() will just give Special:Badtitle, which is
2405 # not especially useful as a returnto parameter. Use the title
2406 # from the request instead, if there was one.
2407 $request = $this->getRequest();
2408 $returnto = Title
::newFromURL( $request->getVal( 'title', '' ) );
2409 if ( $action == 'edit' ) {
2410 $msg = 'whitelistedittext';
2411 $displayReturnto = $returnto;
2412 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2413 $msg = 'nocreatetext';
2414 } elseif ( $action == 'upload' ) {
2415 $msg = 'uploadnologintext';
2417 $msg = 'loginreqpagetext';
2418 $displayReturnto = Title
::newMainPage();
2424 $query['returnto'] = $returnto->getPrefixedText();
2426 if ( !$request->wasPosted() ) {
2427 $returntoquery = $request->getValues();
2428 unset( $returntoquery['title'] );
2429 unset( $returntoquery['returnto'] );
2430 unset( $returntoquery['returntoquery'] );
2431 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2434 $loginLink = Linker
::linkKnown(
2435 SpecialPage
::getTitleFor( 'Userlogin' ),
2436 $this->msg( 'loginreqlink' )->escaped(),
2441 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2442 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2444 # Don't return to a page the user can't read otherwise
2445 # we'll end up in a pointless loop
2446 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2447 $this->returnToMain( null, $displayReturnto );
2450 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2451 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2456 * Display an error page indicating that a given version of MediaWiki is
2457 * required to use it
2459 * @param mixed $version The version of MediaWiki needed to use the page
2461 public function versionRequired( $version ) {
2462 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2464 $this->addWikiMsg( 'versionrequiredtext', $version );
2465 $this->returnToMain();
2469 * Display an error page noting that a given permission bit is required.
2470 * @deprecated since 1.18, just throw the exception directly
2471 * @param string $permission Key required
2472 * @throws PermissionsError
2474 public function permissionRequired( $permission ) {
2475 throw new PermissionsError( $permission );
2479 * Produce the stock "please login to use the wiki" page
2481 * @deprecated since 1.19; throw the exception directly
2483 public function loginToUse() {
2484 throw new PermissionsError( 'read' );
2488 * Format a list of error messages
2490 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2491 * @param string $action Action that was denied or null if unknown
2492 * @return string The wikitext error-messages, formatted into a list.
2494 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2495 if ( $action == null ) {
2496 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2498 $action_desc = $this->msg( "action-$action" )->plain();
2500 'permissionserrorstext-withaction',
2503 )->plain() . "\n\n";
2506 if ( count( $errors ) > 1 ) {
2507 $text .= '<ul class="permissions-errors">' . "\n";
2509 foreach ( $errors as $error ) {
2511 $text .= call_user_func_array( array( $this, 'msg' ), $error )->plain();
2516 $text .= "<div class=\"permissions-errors\">\n" .
2517 call_user_func_array( array( $this, 'msg' ), reset( $errors ) )->plain() .
2525 * Display a page stating that the Wiki is in read-only mode.
2526 * Should only be called after wfReadOnly() has returned true.
2528 * Historically, this function was used to show the source of the page that the user
2529 * was trying to edit and _also_ permissions error messages. The relevant code was
2530 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2532 * @deprecated since 1.25; throw the exception directly
2533 * @throws ReadOnlyError
2535 public function readOnlyPage() {
2536 if ( func_num_args() > 0 ) {
2537 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2540 throw new ReadOnlyError
;
2544 * Turn off regular page output and return an error response
2545 * for when rate limiting has triggered.
2547 * @deprecated since 1.25; throw the exception directly
2549 public function rateLimited() {
2550 wfDeprecated( __METHOD__
, '1.25' );
2551 throw new ThrottledError
;
2555 * Show a warning about slave lag
2557 * If the lag is higher than $wgSlaveLagCritical seconds,
2558 * then the warning is a bit more obvious. If the lag is
2559 * lower than $wgSlaveLagWarning, then no warning is shown.
2561 * @param int $lag Slave lag
2563 public function showLagWarning( $lag ) {
2564 $config = $this->getConfig();
2565 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2566 $message = $lag < $config->get( 'SlaveLagCritical' )
2569 $wrap = Html
::rawElement( 'div', array( 'class' => "mw-{$message}" ), "\n$1\n" );
2570 $this->wrapWikiMsg( "$wrap\n", array( $message, $this->getLanguage()->formatNum( $lag ) ) );
2574 public function showFatalError( $message ) {
2575 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2577 $this->addHTML( $message );
2580 public function showUnexpectedValueError( $name, $val ) {
2581 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2584 public function showFileCopyError( $old, $new ) {
2585 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2588 public function showFileRenameError( $old, $new ) {
2589 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2592 public function showFileDeleteError( $name ) {
2593 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2596 public function showFileNotFoundError( $name ) {
2597 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2601 * Add a "return to" link pointing to a specified title
2603 * @param Title $title Title to link
2604 * @param array $query Query string parameters
2605 * @param string $text Text of the link (input is not escaped)
2606 * @param array $options Options array to pass to Linker
2608 public function addReturnTo( $title, array $query = array(), $text = null, $options = array() ) {
2609 $link = $this->msg( 'returnto' )->rawParams(
2610 Linker
::link( $title, $text, array(), $query, $options ) )->escaped();
2611 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2615 * Add a "return to" link pointing to a specified title,
2616 * or the title indicated in the request, or else the main page
2618 * @param mixed $unused
2619 * @param Title|string $returnto Title or String to return to
2620 * @param string $returntoquery Query string for the return to link
2622 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2623 if ( $returnto == null ) {
2624 $returnto = $this->getRequest()->getText( 'returnto' );
2627 if ( $returntoquery == null ) {
2628 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2631 if ( $returnto === '' ) {
2632 $returnto = Title
::newMainPage();
2635 if ( is_object( $returnto ) ) {
2636 $titleObj = $returnto;
2638 $titleObj = Title
::newFromText( $returnto );
2640 if ( !is_object( $titleObj ) ) {
2641 $titleObj = Title
::newMainPage();
2644 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2648 * @param Skin $sk The given Skin
2649 * @param bool $includeStyle Unused
2650 * @return string The doctype, opening "<html>", and head element.
2652 public function headElement( Skin
$sk, $includeStyle = true ) {
2655 $userdir = $this->getLanguage()->getDir();
2656 $sitedir = $wgContLang->getDir();
2658 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2660 if ( $this->getHTMLTitle() == '' ) {
2661 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2664 $openHead = Html
::openElement( 'head' );
2666 # Don't bother with the newline if $head == ''
2667 $ret .= "$openHead\n";
2670 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2671 // Add <meta charset="UTF-8">
2672 // This should be before <title> since it defines the charset used by
2673 // text including the text inside <title>.
2674 // The spec recommends defining XHTML5's charset using the XML declaration
2676 // Our XML declaration is output by Html::htmlHeader.
2677 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2678 // http://www.whatwg.org/html/semantics.html#charset
2679 $ret .= Html
::element( 'meta', array( 'charset' => 'UTF-8' ) ) . "\n";
2682 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2684 foreach ( $this->getHeadLinksArray() as $item ) {
2685 $ret .= $item . "\n";
2688 // No newline after buildCssLinks since makeResourceLoaderLink did that already
2689 $ret .= $this->buildCssLinks();
2691 $ret .= $this->getHeadScripts() . "\n";
2693 foreach ( $this->mHeadItems
as $item ) {
2694 $ret .= $item . "\n";
2697 $closeHead = Html
::closeElement( 'head' );
2699 $ret .= "$closeHead\n";
2702 $bodyClasses = array();
2703 $bodyClasses[] = 'mediawiki';
2705 # Classes for LTR/RTL directionality support
2706 $bodyClasses[] = $userdir;
2707 $bodyClasses[] = "sitedir-$sitedir";
2709 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2710 # A <body> class is probably not the best way to do this . . .
2711 $bodyClasses[] = 'capitalize-all-nouns';
2714 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2715 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2717 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2719 $bodyAttrs = array();
2720 // While the implode() is not strictly needed, it's used for backwards compatibility
2721 // (this used to be built as a string and hooks likely still expect that).
2722 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2724 // Allow skins and extensions to add body attributes they need
2725 $sk->addToBodyAttributes( $this, $bodyAttrs );
2726 Hooks
::run( 'OutputPageBodyAttributes', array( $this, $sk, &$bodyAttrs ) );
2728 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2734 * Get a ResourceLoader object associated with this OutputPage
2736 * @return ResourceLoader
2738 public function getResourceLoader() {
2739 if ( is_null( $this->mResourceLoader
) ) {
2740 $this->mResourceLoader
= new ResourceLoader( $this->getConfig() );
2742 return $this->mResourceLoader
;
2747 * @param array|string $modules One or more module names
2748 * @param string $only ResourceLoaderModule TYPE_ class constant
2749 * @param bool $useESI
2750 * @param array $extraQuery Array with extra query parameters to add to each
2751 * request. array( param => value ).
2752 * @param bool $loadCall If true, output an (asynchronous) mw.loader.load()
2753 * call rather than a "<script src='...'>" tag.
2754 * @return string The html "<script>", "<link>" and "<style>" tags
2756 public function makeResourceLoaderLink( $modules, $only, $useESI = false,
2757 array $extraQuery = array(), $loadCall = false
2759 $modules = (array)$modules;
2763 'states' => array(),
2766 if ( !count( $modules ) ) {
2770 if ( count( $modules ) > 1 ) {
2771 // Remove duplicate module requests
2772 $modules = array_unique( $modules );
2773 // Sort module names so requests are more uniform
2776 if ( ResourceLoader
::inDebugMode() ) {
2777 // Recursively call us for every item
2778 foreach ( $modules as $name ) {
2779 $link = $this->makeResourceLoaderLink( $name, $only, $useESI );
2780 $links['html'] .= $link['html'];
2781 $links['states'] +
= $link['states'];
2787 if ( !is_null( $this->mTarget
) ) {
2788 $extraQuery['target'] = $this->mTarget
;
2791 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2792 $sortedModules = array();
2793 $resourceLoader = $this->getResourceLoader();
2794 $resourceLoaderUseESI = $this->getConfig()->get( 'ResourceLoaderUseESI' );
2795 foreach ( $modules as $name ) {
2796 $module = $resourceLoader->getModule( $name );
2797 # Check that we're allowed to include this module on this page
2799 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2800 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2801 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2802 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2803 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2804 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2805 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2810 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2813 foreach ( $sortedModules as $source => $groups ) {
2814 foreach ( $groups as $group => $grpModules ) {
2815 // Special handling for user-specific groups
2817 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2818 $user = $this->getUser()->getName();
2821 // Create a fake request based on the one we are about to make so modules return
2822 // correct timestamp and emptiness data
2823 $query = ResourceLoader
::makeLoaderQuery(
2824 array(), // modules; not determined yet
2825 $this->getLanguage()->getCode(),
2826 $this->getSkin()->getSkinName(),
2828 null, // version; not determined yet
2829 ResourceLoader
::inDebugMode(),
2830 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2831 $this->isPrintable(),
2832 $this->getRequest()->getBool( 'handheld' ),
2835 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2837 // Extract modules that know they're empty and see if we have one or more
2840 foreach ( $grpModules as $key => $module ) {
2841 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2842 // If we're only getting the styles, we don't need to do anything for empty modules.
2843 if ( $module->isKnownEmpty( $context ) ) {
2844 unset( $grpModules[$key] );
2845 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2846 $links['states'][$key] = 'ready';
2850 $isRaw |
= $module->isRaw();
2853 // If there are no non-empty modules, skip this group
2854 if ( count( $grpModules ) === 0 ) {
2858 // Inline private modules. These can't be loaded through load.php for security
2859 // reasons, see bug 34907. Note that these modules should be loaded from
2860 // getHeadScripts() before the first loader call. Otherwise other modules can't
2861 // properly use them as dependencies (bug 30914)
2862 if ( $group === 'private' ) {
2863 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2864 $links['html'] .= Html
::inlineStyle(
2865 $resourceLoader->makeModuleResponse( $context, $grpModules )
2868 $links['html'] .= ResourceLoader
::makeInlineScript(
2869 $resourceLoader->makeModuleResponse( $context, $grpModules )
2872 $links['html'] .= "\n";
2876 // Special handling for the user group; because users might change their stuff
2877 // on-wiki like user pages, or user preferences; we need to find the highest
2878 // timestamp of these user-changeable modules so we can ensure cache misses on change
2879 // This should NOT be done for the site group (bug 27564) because anons get that too
2880 // and we shouldn't be putting timestamps in Squid-cached HTML
2882 if ( $group === 'user' ) {
2883 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2886 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2887 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2888 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2890 if ( $useESI && $resourceLoaderUseESI ) {
2891 $esi = Xml
::element( 'esi:include', array( 'src' => $url ) );
2892 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2893 $link = Html
::inlineStyle( $esi );
2895 $link = Html
::inlineScript( $esi );
2898 // Automatically select style/script elements
2899 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2900 $link = Html
::linkedStyle( $url );
2901 } elseif ( $loadCall ) {
2902 $link = ResourceLoader
::makeInlineScript(
2903 Xml
::encodeJsCall( 'mw.loader.load', array( $url, 'text/javascript', true ) )
2906 $link = Html
::linkedScript( $url );
2907 if ( !$context->getRaw() && !$isRaw ) {
2908 // Wrap only=script / only=combined requests in a conditional as
2909 // browsers not supported by the startup module would unconditionally
2910 // execute this module. Otherwise users will get "ReferenceError: mw is
2911 // undefined" or "jQuery is undefined" from e.g. a "site" module.
2912 $link = ResourceLoader
::makeInlineScript(
2913 Xml
::encodeJsCall( 'document.write', array( $link ) )
2917 // For modules requested directly in the html via <link> or <script>,
2918 // tell mw.loader they are being loading to prevent duplicate requests.
2919 foreach ( $grpModules as $key => $module ) {
2920 // Don't output state=loading for the startup module..
2921 if ( $key !== 'startup' ) {
2922 $links['states'][$key] = 'loading';
2928 if ( $group == 'noscript' ) {
2929 $links['html'] .= Html
::rawElement( 'noscript', array(), $link ) . "\n";
2931 $links['html'] .= $link . "\n";
2940 * Build html output from an array of links from makeResourceLoaderLink.
2941 * @param array $links
2942 * @return string HTML
2944 protected static function getHtmlFromLoaderLinks( array $links ) {
2947 foreach ( $links as $link ) {
2948 if ( !is_array( $link ) ) {
2951 $html .= $link['html'];
2952 $states +
= $link['states'];
2956 if ( count( $states ) ) {
2957 $html = ResourceLoader
::makeInlineScript(
2958 ResourceLoader
::makeLoaderStateScript( $states )
2966 * JS stuff to put in the "<head>". This is the startup module, config
2967 * vars and modules marked with position 'top'
2969 * @return string HTML fragment
2971 function getHeadScripts() {
2972 // Startup - this will immediately load jquery and mediawiki modules
2974 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
, true );
2976 // Load config before anything else
2977 $links[] = ResourceLoader
::makeInlineScript(
2978 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
2981 // Load embeddable private modules before any loader links
2982 // This needs to be TYPE_COMBINED so these modules are properly wrapped
2983 // in mw.loader.implement() calls and deferred until mw.user is available
2984 $embedScripts = array( 'user.options', 'user.tokens' );
2985 $links[] = $this->makeResourceLoaderLink( $embedScripts, ResourceLoaderModule
::TYPE_COMBINED
);
2987 // Scripts and messages "only" requests marked for top inclusion
2988 $links[] = $this->makeResourceLoaderLink(
2989 $this->getModuleScripts( true, 'top' ),
2990 ResourceLoaderModule
::TYPE_SCRIPTS
2993 // Modules requests - let the client calculate dependencies and batch requests as it likes
2994 // Only load modules that have marked themselves for loading at the top
2995 $modules = $this->getModules( true, 'top' );
2997 $links[] = ResourceLoader
::makeInlineScript(
2998 Xml
::encodeJsCall( 'mw.loader.load', array( $modules ) )
3002 if ( $this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3003 $links[] = $this->getScriptsForBottomQueue( true );
3006 return self
::getHtmlFromLoaderLinks( $links );
3010 * JS stuff to put at the 'bottom', which can either be the bottom of the
3011 * "<body>" or the bottom of the "<head>" depending on
3012 * $wgResourceLoaderExperimentalAsyncLoading: modules marked with position
3013 * 'bottom', legacy scripts ($this->mScripts), user preferences, site JS
3016 * @param bool $inHead If true, this HTML goes into the "<head>",
3017 * if false it goes into the "<body>".
3020 function getScriptsForBottomQueue( $inHead ) {
3021 // Scripts "only" requests marked for bottom inclusion
3022 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3025 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3026 ResourceLoaderModule
::TYPE_SCRIPTS
, /* $useESI = */ false, /* $extraQuery = */ array(),
3027 /* $loadCall = */ $inHead
3030 $links[] = $this->makeResourceLoaderLink( $this->getModuleStyles( true, 'bottom' ),
3031 ResourceLoaderModule
::TYPE_STYLES
, /* $useESI = */ false, /* $extraQuery = */ array(),
3032 /* $loadCall = */ $inHead
3035 // Modules requests - let the client calculate dependencies and batch requests as it likes
3036 // Only load modules that have marked themselves for loading at the bottom
3037 $modules = $this->getModules( true, 'bottom' );
3039 $links[] = ResourceLoader
::makeInlineScript(
3040 Xml
::encodeJsCall( 'mw.loader.load', array( $modules, null, true ) )
3045 $links[] = "\n" . $this->mScripts
;
3047 // Add site JS if enabled
3048 $links[] = $this->makeResourceLoaderLink( 'site', ResourceLoaderModule
::TYPE_SCRIPTS
,
3049 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3052 // Add user JS if enabled
3053 if ( $this->getConfig()->get( 'AllowUserJs' )
3054 && $this->getUser()->isLoggedIn()
3055 && $this->getTitle()
3056 && $this->getTitle()->isJsSubpage()
3057 && $this->userCanPreview()
3059 # XXX: additional security check/prompt?
3060 // We're on a preview of a JS subpage
3061 // Exclude this page from the user module in case it's in there (bug 26283)
3062 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
, false,
3063 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() ), $inHead
3065 // Load the previewed JS
3066 $links[] = Html
::inlineScript( "\n"
3067 . $this->getRequest()->getText( 'wpTextbox1' ) . "\n" ) . "\n";
3069 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3070 // asynchronously and may arrive *after* the inline script here. So the previewed code
3071 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js...
3073 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3074 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_SCRIPTS
,
3075 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3079 // Group JS is only enabled if site JS is enabled.
3080 $links[] = $this->makeResourceLoaderLink( 'user.groups', ResourceLoaderModule
::TYPE_COMBINED
,
3081 /* $useESI = */ false, /* $extraQuery = */ array(), /* $loadCall = */ $inHead
3084 return self
::getHtmlFromLoaderLinks( $links );
3088 * JS stuff to put at the bottom of the "<body>"
3091 function getBottomScripts() {
3092 // In case the skin wants to add bottom CSS
3093 $this->getSkin()->setupSkinUserCss( $this );
3095 // Optimise jQuery ready event cross-browser.
3096 // This also enforces $.isReady to be true at </body> which fixes the
3097 // mw.loader bug in Firefox with using document.write between </body>
3098 // and the DOMContentReady event (bug 47457).
3099 $html = Html
::inlineScript( 'if(window.jQuery)jQuery.ready();' );
3101 if ( !$this->getConfig()->get( 'ResourceLoaderExperimentalAsyncLoading' ) ) {
3102 $html .= $this->getScriptsForBottomQueue( false );
3109 * Get the javascript config vars to include on this page
3111 * @return array Array of javascript config vars
3114 public function getJsConfigVars() {
3115 return $this->mJsConfigVars
;
3119 * Add one or more variables to be set in mw.config in JavaScript
3121 * @param string|array $keys Key or array of key/value pairs
3122 * @param mixed $value [optional] Value of the configuration variable
3124 public function addJsConfigVars( $keys, $value = null ) {
3125 if ( is_array( $keys ) ) {
3126 foreach ( $keys as $key => $value ) {
3127 $this->mJsConfigVars
[$key] = $value;
3132 $this->mJsConfigVars
[$keys] = $value;
3136 * Get an array containing the variables to be set in mw.config in JavaScript.
3138 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3139 * - in other words, page-independent/site-wide variables (without state).
3140 * You will only be adding bloat to the html page and causing page caches to
3141 * have to be purged on configuration changes.
3144 public function getJSVars() {
3149 $canonicalSpecialPageName = false; # bug 21115
3151 $title = $this->getTitle();
3152 $ns = $title->getNamespace();
3153 $canonicalNamespace = MWNamespace
::exists( $ns )
3154 ? MWNamespace
::getCanonicalName( $ns )
3155 : $title->getNsText();
3157 $sk = $this->getSkin();
3158 // Get the relevant title so that AJAX features can use the correct page name
3159 // when making API requests from certain special pages (bug 34972).
3160 $relevantTitle = $sk->getRelevantTitle();
3161 $relevantUser = $sk->getRelevantUser();
3163 if ( $ns == NS_SPECIAL
) {
3164 list( $canonicalSpecialPageName, /*...*/ ) =
3165 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3166 } elseif ( $this->canUseWikiPage() ) {
3167 $wikiPage = $this->getWikiPage();
3168 $curRevisionId = $wikiPage->getLatest();
3169 $articleId = $wikiPage->getId();
3172 $lang = $title->getPageLanguage();
3174 // Pre-process information
3175 $separatorTransTable = $lang->separatorTransformTable();
3176 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : array();
3177 $compactSeparatorTransTable = array(
3178 implode( "\t", array_keys( $separatorTransTable ) ),
3179 implode( "\t", $separatorTransTable ),
3181 $digitTransTable = $lang->digitTransformTable();
3182 $digitTransTable = $digitTransTable ?
$digitTransTable : array();
3183 $compactDigitTransTable = array(
3184 implode( "\t", array_keys( $digitTransTable ) ),
3185 implode( "\t", $digitTransTable ),
3188 $user = $this->getUser();
3191 'wgCanonicalNamespace' => $canonicalNamespace,
3192 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3193 'wgNamespaceNumber' => $title->getNamespace(),
3194 'wgPageName' => $title->getPrefixedDBkey(),
3195 'wgTitle' => $title->getText(),
3196 'wgCurRevisionId' => $curRevisionId,
3197 'wgRevisionId' => (int)$this->getRevisionId(),
3198 'wgArticleId' => $articleId,
3199 'wgIsArticle' => $this->isArticle(),
3200 'wgIsRedirect' => $title->isRedirect(),
3201 'wgAction' => Action
::getActionName( $this->getContext() ),
3202 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3203 'wgUserGroups' => $user->getEffectiveGroups(),
3204 'wgCategories' => $this->getCategories(),
3205 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3206 'wgPageContentLanguage' => $lang->getCode(),
3207 'wgPageContentModel' => $title->getContentModel(),
3208 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3209 'wgDigitTransformTable' => $compactDigitTransTable,
3210 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3211 'wgMonthNames' => $lang->getMonthNamesArray(),
3212 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3213 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3214 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3217 if ( $user->isLoggedIn() ) {
3218 $vars['wgUserId'] = $user->getId();
3219 $vars['wgUserEditCount'] = $user->getEditCount();
3220 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3221 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3222 // Get the revision ID of the oldest new message on the user's talk
3223 // page. This can be used for constructing new message alerts on
3225 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3228 if ( $wgContLang->hasVariants() ) {
3229 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3231 // Same test as SkinTemplate
3232 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3233 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3235 foreach ( $title->getRestrictionTypes() as $type ) {
3236 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3239 if ( $title->isMainPage() ) {
3240 $vars['wgIsMainPage'] = true;
3243 if ( $this->mRedirectedFrom
) {
3244 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3247 if ( $relevantUser ) {
3248 $vars['wgRelevantUserName'] = $relevantUser->getName();
3251 // Allow extensions to add their custom variables to the mw.config map.
3252 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3253 // page-dependant but site-wide (without state).
3254 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3255 Hooks
::run( 'MakeGlobalVariablesScript', array( &$vars, $this ) );
3257 // Merge in variables from addJsConfigVars last
3258 return array_merge( $vars, $this->getJsConfigVars() );
3262 * To make it harder for someone to slip a user a fake
3263 * user-JavaScript or user-CSS preview, a random token
3264 * is associated with the login session. If it's not
3265 * passed back with the preview request, we won't render
3270 public function userCanPreview() {
3271 if ( $this->getRequest()->getVal( 'action' ) != 'submit'
3272 ||
!$this->getRequest()->wasPosted()
3273 ||
!$this->getUser()->matchEditToken(
3274 $this->getRequest()->getVal( 'wpEditToken' ) )
3278 if ( !$this->getTitle()->isJsSubpage() && !$this->getTitle()->isCssSubpage() ) {
3281 if ( !$this->getTitle()->isSubpageOf( $this->getUser()->getUserPage() ) ) {
3282 // Don't execute another user's CSS or JS on preview (T85855)
3286 return !count( $this->getTitle()->getUserPermissionsErrors( 'edit', $this->getUser() ) );
3290 * @return array Array in format "link name or number => 'link html'".
3292 public function getHeadLinksArray() {
3296 $config = $this->getConfig();
3298 $canonicalUrl = $this->mCanonicalUrl
;
3300 $tags['meta-generator'] = Html
::element( 'meta', array(
3301 'name' => 'generator',
3302 'content' => "MediaWiki $wgVersion",
3305 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3306 $tags['meta-referrer'] = Html
::element( 'meta', array(
3307 'name' => 'referrer',
3308 'content' => $config->get( 'ReferrerPolicy' )
3312 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3313 if ( $p !== 'index,follow' ) {
3314 // http://www.robotstxt.org/wc/meta-user.html
3315 // Only show if it's different from the default robots policy
3316 $tags['meta-robots'] = Html
::element( 'meta', array(
3322 foreach ( $this->mMetatags
as $tag ) {
3323 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3325 $tag[0] = substr( $tag[0], 5 );
3329 $tagName = "meta-{$tag[0]}";
3330 if ( isset( $tags[$tagName] ) ) {
3331 $tagName .= $tag[1];
3333 $tags[$tagName] = Html
::element( 'meta',
3336 'content' => $tag[1]
3341 foreach ( $this->mLinktags
as $tag ) {
3342 $tags[] = Html
::element( 'link', $tag );
3345 # Universal edit button
3346 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3347 $user = $this->getUser();
3348 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3349 && ( $this->getTitle()->exists() ||
$this->getTitle()->quickUserCan( 'create', $user ) ) ) {
3350 // Original UniversalEditButton
3351 $msg = $this->msg( 'edit' )->text();
3352 $tags['universal-edit-button'] = Html
::element( 'link', array(
3353 'rel' => 'alternate',
3354 'type' => 'application/x-wiki',
3356 'href' => $this->getTitle()->getEditURL(),
3358 // Alternate edit link
3359 $tags['alternative-edit'] = Html
::element( 'link', array(
3362 'href' => $this->getTitle()->getEditURL(),
3367 # Generally the order of the favicon and apple-touch-icon links
3368 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3369 # uses whichever one appears later in the HTML source. Make sure
3370 # apple-touch-icon is specified first to avoid this.
3371 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3372 $tags['apple-touch-icon'] = Html
::element( 'link', array(
3373 'rel' => 'apple-touch-icon',
3374 'href' => $config->get( 'AppleTouchIcon' )
3378 if ( $config->get( 'Favicon' ) !== false ) {
3379 $tags['favicon'] = Html
::element( 'link', array(
3380 'rel' => 'shortcut icon',
3381 'href' => $config->get( 'Favicon' )
3385 # OpenSearch description link
3386 $tags['opensearch'] = Html
::element( 'link', array(
3388 'type' => 'application/opensearchdescription+xml',
3389 'href' => wfScript( 'opensearch_desc' ),
3390 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3393 if ( $config->get( 'EnableAPI' ) ) {
3394 # Real Simple Discovery link, provides auto-discovery information
3395 # for the MediaWiki API (and potentially additional custom API
3396 # support such as WordPress or Twitter-compatible APIs for a
3397 # blogging extension, etc)
3398 $tags['rsd'] = Html
::element( 'link', array(
3400 'type' => 'application/rsd+xml',
3401 // Output a protocol-relative URL here if $wgServer is protocol-relative
3402 // Whether RSD accepts relative or protocol-relative URLs is completely undocumented, though
3403 'href' => wfExpandUrl( wfAppendQuery(
3405 array( 'action' => 'rsd' ) ),
3412 if ( !$config->get( 'DisableLangConversion' ) ) {
3413 $lang = $this->getTitle()->getPageLanguage();
3414 if ( $lang->hasVariants() ) {
3415 $variants = $lang->getVariants();
3416 foreach ( $variants as $_v ) {
3417 $tags["variant-$_v"] = Html
::element( 'link', array(
3418 'rel' => 'alternate',
3419 'hreflang' => wfBCP47( $_v ),
3420 'href' => $this->getTitle()->getLocalURL( array( 'variant' => $_v ) ) )
3424 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3425 $tags["variant-x-default"] = Html
::element( 'link', array(
3426 'rel' => 'alternate',
3427 'hreflang' => 'x-default',
3428 'href' => $this->getTitle()->getLocalURL() ) );
3433 if ( $config->get( 'RightsPage' ) ) {
3434 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3437 $copyright = $copy->getLocalURL();
3441 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3442 $copyright = $config->get( 'RightsUrl' );
3446 $tags['copyright'] = Html
::element( 'link', array(
3447 'rel' => 'copyright',
3448 'href' => $copyright )
3453 if ( $config->get( 'Feed' ) ) {
3454 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3455 # Use the page name for the title. In principle, this could
3456 # lead to issues with having the same name for different feeds
3457 # corresponding to the same page, but we can't avoid that at
3460 $tags[] = $this->feedLink(
3463 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3464 $this->msg( "page-{$format}-feed", $this->getTitle()->getPrefixedText() )->text()
3468 # Recent changes feed should appear on every page (except recentchanges,
3469 # that would be redundant). Put it after the per-page feed to avoid
3470 # changing existing behavior. It's still available, probably via a
3471 # menu in your browser. Some sites might have a different feed they'd
3472 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3473 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3474 # If so, use it instead.
3475 $sitename = $config->get( 'Sitename' );
3476 if ( $config->get( 'OverrideSiteFeed' ) ) {
3477 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3478 // Note, this->feedLink escapes the url.
3479 $tags[] = $this->feedLink(
3482 $this->msg( "site-{$type}-feed", $sitename )->text()
3485 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3486 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3487 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3488 $tags[] = $this->feedLink(
3490 $rctitle->getLocalURL( array( 'feed' => $format ) ),
3491 # For grep: 'site-rss-feed', 'site-atom-feed'
3492 $this->msg( "site-{$format}-feed", $sitename )->text()
3499 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3500 if ( $canonicalUrl !== false ) {
3501 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3503 $reqUrl = $this->getRequest()->getRequestURL();
3504 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3507 if ( $canonicalUrl !== false ) {
3508 $tags[] = Html
::element( 'link', array(
3509 'rel' => 'canonical',
3510 'href' => $canonicalUrl
3518 * @return string HTML tag links to be put in the header.
3519 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3520 * OutputPage::getHeadLinksArray directly.
3522 public function getHeadLinks() {
3523 wfDeprecated( __METHOD__
, '1.24' );
3524 return implode( "\n", $this->getHeadLinksArray() );
3528 * Generate a "<link rel/>" for a feed.
3530 * @param string $type Feed type
3531 * @param string $url URL to the feed
3532 * @param string $text Value of the "title" attribute
3533 * @return string HTML fragment
3535 private function feedLink( $type, $url, $text ) {
3536 return Html
::element( 'link', array(
3537 'rel' => 'alternate',
3538 'type' => "application/$type+xml",
3545 * Add a local or specified stylesheet, with the given media options.
3546 * Meant primarily for internal use...
3548 * @param string $style URL to the file
3549 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3550 * @param string $condition For IE conditional comments, specifying an IE version
3551 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3553 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3555 // Even though we expect the media type to be lowercase, but here we
3556 // force it to lowercase to be safe.
3558 $options['media'] = $media;
3561 $options['condition'] = $condition;
3564 $options['dir'] = $dir;
3566 $this->styles
[$style] = $options;
3570 * Adds inline CSS styles
3571 * @param mixed $style_css Inline CSS
3572 * @param string $flip Set to 'flip' to flip the CSS if needed
3574 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3575 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3576 # If wanted, and the interface is right-to-left, flip the CSS
3577 $style_css = CSSJanus
::transform( $style_css, true, false );
3579 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3583 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3584 * These will be applied to various media & IE conditionals.
3588 public function buildCssLinks() {
3591 $this->getSkin()->setupSkinUserCss( $this );
3593 // Add ResourceLoader styles
3594 // Split the styles into these groups
3599 'private' => array(),
3600 'noscript' => array()
3603 $otherTags = ''; // Tags to append after the normal <link> tags
3604 $resourceLoader = $this->getResourceLoader();
3606 $moduleStyles = $this->getModuleStyles( true, 'top' );
3608 // Per-site custom styles
3609 $moduleStyles[] = 'site';
3610 $moduleStyles[] = 'noscript';
3611 $moduleStyles[] = 'user.groups';
3613 // Per-user custom styles
3614 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3615 && $this->userCanPreview()
3617 // We're on a preview of a CSS subpage
3618 // Exclude this page from the user module in case it's in there (bug 26283)
3619 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
, false,
3620 array( 'excludepage' => $this->getTitle()->getPrefixedDBkey() )
3622 $otherTags .= $link['html'];
3624 // Load the previewed CSS
3625 // If needed, Janus it first. This is user-supplied CSS, so it's
3626 // assumed to be right for the content language directionality.
3627 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3628 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3629 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3631 $otherTags .= Html
::inlineStyle( $previewedCSS ) . "\n";
3633 // Load the user styles normally
3634 $moduleStyles[] = 'user';
3637 // Per-user preference styles
3638 $moduleStyles[] = 'user.cssprefs';
3640 foreach ( $moduleStyles as $name ) {
3641 $module = $resourceLoader->getModule( $name );
3645 $group = $module->getGroup();
3646 // Modules in groups different than the ones listed on top (see $styles assignment)
3647 // will be placed in the "other" group
3648 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3651 // We want site, private and user styles to override dynamically added
3652 // styles from modules, but we want dynamically added styles to override
3653 // statically added styles from other modules. So the order has to be
3654 // other, dynamic, site, private, user. Add statically added styles for
3656 $links[] = $this->makeResourceLoaderLink( $styles['other'], ResourceLoaderModule
::TYPE_STYLES
);
3657 // Add normal styles added through addStyle()/addInlineStyle() here
3658 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3659 // Add marker tag to mark the place where the client-side loader should inject dynamic styles
3660 // We use a <meta> tag with a made-up name for this because that's valid HTML
3661 $links[] = Html
::element(
3663 array( 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' )
3666 // Add site, private and user styles
3667 // 'private' at present only contains user.options, so put that before 'user'
3668 // Any future private modules will likely have a similar user-specific character
3669 foreach ( array( 'site', 'noscript', 'private', 'user' ) as $group ) {
3670 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3671 ResourceLoaderModule
::TYPE_STYLES
3675 // Add stuff in $otherTags (previewed user CSS if applicable)
3676 return self
::getHtmlFromLoaderLinks( $links ) . $otherTags;
3682 public function buildCssLinksArray() {
3685 // Add any extension CSS
3686 foreach ( $this->mExtStyles
as $url ) {
3687 $this->addStyle( $url );
3689 $this->mExtStyles
= array();
3691 foreach ( $this->styles
as $file => $options ) {
3692 $link = $this->styleLink( $file, $options );
3694 $links[$file] = $link;
3701 * Generate \<link\> tags for stylesheets
3703 * @param string $style URL to the file
3704 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3705 * @return string HTML fragment
3707 protected function styleLink( $style, array $options ) {
3708 if ( isset( $options['dir'] ) ) {
3709 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3714 if ( isset( $options['media'] ) ) {
3715 $media = self
::transformCssMedia( $options['media'] );
3716 if ( is_null( $media ) ) {
3723 if ( substr( $style, 0, 1 ) == '/' ||
3724 substr( $style, 0, 5 ) == 'http:' ||
3725 substr( $style, 0, 6 ) == 'https:' ) {
3728 $config = $this->getConfig();
3729 $url = $config->get( 'StylePath' ) . '/' . $style . '?' . $config->get( 'StyleVersion' );
3732 $link = Html
::linkedStyle( $url, $media );
3734 if ( isset( $options['condition'] ) ) {
3735 $condition = htmlspecialchars( $options['condition'] );
3736 $link = "<!--[if $condition]>$link<![endif]-->";
3742 * Transform "media" attribute based on request parameters
3744 * @param string $media Current value of the "media" attribute
3745 * @return string Modified value of the "media" attribute, or null to skip
3748 public static function transformCssMedia( $media ) {
3751 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3752 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3754 // Switch in on-screen display for media testing
3756 'printable' => 'print',
3757 'handheld' => 'handheld',
3759 foreach ( $switches as $switch => $targetMedia ) {
3760 if ( $wgRequest->getBool( $switch ) ) {
3761 if ( $media == $targetMedia ) {
3763 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3764 // This regex will not attempt to understand a comma-separated media_query_list
3766 // Example supported values for $media:
3767 // 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3768 // Example NOT supported value for $media:
3769 // '3d-glasses, screen, print and resolution > 90dpi'
3771 // If it's a print request, we never want any kind of screen stylesheets
3772 // If it's a handheld request (currently the only other choice with a switch),
3773 // we don't want simple 'screen' but we might want screen queries that
3774 // have a max-width or something, so we'll pass all others on and let the
3775 // client do the query.
3776 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3787 * Add a wikitext-formatted message to the output.
3788 * This is equivalent to:
3790 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3792 public function addWikiMsg( /*...*/ ) {
3793 $args = func_get_args();
3794 $name = array_shift( $args );
3795 $this->addWikiMsgArray( $name, $args );
3799 * Add a wikitext-formatted message to the output.
3800 * Like addWikiMsg() except the parameters are taken as an array
3801 * instead of a variable argument list.
3803 * @param string $name
3804 * @param array $args
3806 public function addWikiMsgArray( $name, $args ) {
3807 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3811 * This function takes a number of message/argument specifications, wraps them in
3812 * some overall structure, and then parses the result and adds it to the output.
3814 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3815 * and so on. The subsequent arguments may be either
3816 * 1) strings, in which case they are message names, or
3817 * 2) arrays, in which case, within each array, the first element is the message
3818 * name, and subsequent elements are the parameters to that message.
3820 * Don't use this for messages that are not in the user's interface language.
3824 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3828 * $wgOut->addWikiText( "<div class='error'>\n"
3829 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3831 * The newline after the opening div is needed in some wikitext. See bug 19226.
3833 * @param string $wrap
3835 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3836 $msgSpecs = func_get_args();
3837 array_shift( $msgSpecs );
3838 $msgSpecs = array_values( $msgSpecs );
3840 foreach ( $msgSpecs as $n => $spec ) {
3841 if ( is_array( $spec ) ) {
3843 $name = array_shift( $args );
3844 if ( isset( $args['options'] ) ) {
3845 unset( $args['options'] );
3847 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
3855 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
3857 $this->addWikiText( $s );
3861 * Include jQuery core. Use this to avoid loading it multiple times
3862 * before we get a usable script loader.
3864 * @param array $modules List of jQuery modules which should be loaded
3865 * @return array The list of modules which were not loaded.
3867 * @deprecated since 1.17
3869 public function includeJQuery( array $modules = array() ) {
3874 * Enables/disables TOC, doesn't override __NOTOC__
3878 public function enableTOC( $flag = true ) {
3879 $this->mEnableTOC
= $flag;
3886 public function isTOCEnabled() {
3887 return $this->mEnableTOC
;
3891 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
3895 public function enableSectionEditLinks( $flag = true ) {
3896 $this->mEnableSectionEditLinks
= $flag;
3903 public function sectionEditLinksEnabled() {
3904 return $this->mEnableSectionEditLinks
;
3908 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
3909 * MediaWiki and this OutputPage instance.
3913 public function enableOOUI() {
3914 OOUI\Theme
::setSingleton( new OOUI\
MediaWikiTheme() );
3915 OOUI\Element
::setDefaultDir( $this->getLanguage()->getDir() );
3916 $this->addModuleStyles( array(
3918 'oojs-ui.styles.icons',
3919 'oojs-ui.styles.indicators',
3920 'oojs-ui.styles.textures',