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
23 use MediaWiki\Logger\LoggerFactory
;
24 use MediaWiki\Session\SessionManager
;
25 use WrappedString\WrappedString
;
28 * This class should be covered by a general architecture document which does
29 * not exist as of January 2011. This is one of the Core classes and should
30 * be read at least once by any new developers.
32 * This class is used to prepare the final rendering. A skin is then
33 * applied to the output parameters (links, javascript, html, categories ...).
35 * @todo FIXME: Another class handles sending the whole page to the client.
37 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
42 class OutputPage
extends ContextSource
{
43 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
44 protected $mMetatags = [];
47 protected $mLinktags = [];
50 protected $mCanonicalUrl = false;
53 * @var array Additional stylesheets. Looks like this is for extensions.
54 * Might be replaced by ResourceLoader.
56 protected $mExtStyles = [];
59 * @var string Should be private - has getter and setter. Contains
61 public $mPagetitle = '';
64 * @var string Contains all of the "<body>" content. Should be private we
65 * got set/get accessors and the append() method.
67 public $mBodytext = '';
70 * Holds the debug lines that will be output as comments in page source if
71 * $wgDebugComments is enabled. See also $wgShowDebug.
72 * @deprecated since 1.20; use MWDebug class instead.
74 public $mDebugtext = '';
76 /** @var string Stores contents of "<title>" tag */
77 private $mHTMLtitle = '';
80 * @var bool Is the displayed content related to the source of the
81 * corresponding wiki article.
83 private $mIsarticle = false;
85 /** @var bool Stores "article flag" toggle. */
86 private $mIsArticleRelated = true;
89 * @var bool We have to set isPrintable(). Some pages should
90 * never be printed (ex: redirections).
92 private $mPrintable = false;
95 * @var array Contains the page subtitle. Special pages usually have some
96 * links here. Don't confuse with site subtitle added by skins.
98 private $mSubtitle = [];
101 public $mRedirect = '';
104 protected $mStatusCode;
107 * @var string Variable mLastModified and mEtag are used for sending cache control.
108 * The whole caching system should probably be moved into its own class.
110 protected $mLastModified = '';
113 * Contains an HTTP Entity Tags (see RFC 2616 section 3.13) which is used
114 * as a unique identifier for the content. It is later used by the client
115 * to compare its cached version with the server version. Client sends
116 * headers If-Match and If-None-Match containing its locally cached ETAG value.
118 * To get more information, you will have to look at HTTP/1.1 protocol which
119 * is properly described in RFC 2616 : http://tools.ietf.org/html/rfc2616
121 private $mETag = false;
124 protected $mCategoryLinks = [];
127 protected $mCategories = [];
130 protected $mIndicators = [];
132 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
133 private $mLanguageLinks = [];
136 * Used for JavaScript (predates ResourceLoader)
137 * @todo We should split JS / CSS.
138 * mScripts content is inserted as is in "<head>" by Skin. This might
139 * contain either a link to a stylesheet or inline CSS.
141 private $mScripts = '';
143 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
144 protected $mInlineStyles = '';
147 * @var string Used by skin template.
148 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
150 public $mPageLinkTitle = '';
152 /** @var array Array of elements in "<head>". Parser might add its own headers! */
153 protected $mHeadItems = [];
156 protected $mModules = [];
159 protected $mModuleScripts = [];
162 protected $mModuleStyles = [];
164 /** @var ResourceLoader */
165 protected $mResourceLoader;
168 protected $mJsConfigVars = [];
171 protected $mTemplateIds = [];
174 protected $mImageTimeKeys = [];
177 public $mRedirectCode = '';
179 protected $mFeedLinksAppendQuery = null;
182 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
183 * @see ResourceLoaderModule::$origin
184 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
186 protected $mAllowedModules = [
187 ResourceLoaderModule
::TYPE_COMBINED
=> ResourceLoaderModule
::ORIGIN_ALL
,
190 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
191 protected $mDoNothing = false;
196 protected $mContainsNewMagic = 0;
199 * lazy initialised, use parserOptions()
202 protected $mParserOptions = null;
205 * Handles the Atom / RSS links.
206 * We probably only support Atom in 2011.
207 * @see $wgAdvertisedFeedTypes
209 private $mFeedLinks = [];
211 // Gwicke work on squid caching? Roughly from 2003.
212 protected $mEnableClientCache = true;
214 /** @var bool Flag if output should only contain the body of the article. */
215 private $mArticleBodyOnly = false;
218 protected $mNewSectionLink = false;
221 protected $mHideNewSectionLink = false;
224 * @var bool Comes from the parser. This was probably made to load CSS/JS
225 * only if we had "<gallery>". Used directly in CategoryPage.php.
226 * Looks like ResourceLoader can replace this.
228 public $mNoGallery = false;
231 private $mPageTitleActionText = '';
233 /** @var int Cache stuff. Looks like mEnableClientCache */
234 protected $mCdnMaxage = 0;
235 /** @var int Upper limit on mCdnMaxage */
236 protected $mCdnMaxageLimit = INF
;
239 * @var bool Controls if anti-clickjacking / frame-breaking headers will
240 * be sent. This should be done for pages where edit actions are possible.
241 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
243 protected $mPreventClickjacking = true;
245 /** @var int To include the variable {{REVISIONID}} */
246 private $mRevisionId = null;
249 private $mRevisionTimestamp = null;
252 protected $mFileVersion = null;
255 * @var array An array of stylesheet filenames (relative from skins path),
256 * with options for CSS media, IE conditions, and RTL/LTR direction.
257 * For internal use; add settings in the skin via $this->addStyle()
259 * Style again! This seems like a code duplication since we already have
260 * mStyles. This is what makes Open Source amazing.
262 protected $styles = [];
265 * Whether jQuery is already handled.
267 protected $mJQueryDone = false;
269 private $mIndexPolicy = 'index';
270 private $mFollowPolicy = 'follow';
271 private $mVaryHeader = [
272 'Accept-Encoding' => [ 'match=gzip' ],
276 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
281 private $mRedirectedFrom = null;
284 * Additional key => value data
286 private $mProperties = [];
289 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
291 private $mTarget = null;
294 * @var bool Whether parser output should contain table of contents
296 private $mEnableTOC = true;
299 * @var bool Whether parser output should contain section edit links
301 private $mEnableSectionEditLinks = true;
304 * @var string|null The URL to send in a <link> element with rel=copyright
306 private $copyrightUrl;
309 * Constructor for OutputPage. This should not be called directly.
310 * Instead a new RequestContext should be created and it will implicitly create
311 * a OutputPage tied to that context.
312 * @param IContextSource|null $context
314 function __construct( IContextSource
$context = null ) {
315 if ( $context === null ) {
316 # Extensions should use `new RequestContext` instead of `new OutputPage` now.
317 wfDeprecated( __METHOD__
, '1.18' );
319 $this->setContext( $context );
324 * Redirect to $url rather than displaying the normal page
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect
= str_replace( "\n", '', $url );
332 $this->mRedirectCode
= $responsecode;
336 * Get the URL to redirect to, or an empty string if not redirect URL set
340 public function getRedirect() {
341 return $this->mRedirect
;
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
350 * @param string|null $url
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl
= $url;
357 * Set the HTTP status code to send with the output.
359 * @param int $statusCode
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode
= $statusCode;
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
369 * @param string $name Tag name
370 * @param string $val Tag value
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags
, [ $name, $val ] );
377 * Returns the current <meta> tags
382 public function getMetaTags() {
383 return $this->mMetatags
;
387 * Add a new \<link\> tag to the page header.
389 * Note: use setCanonicalUrl() for rel=canonical.
391 * @param array $linkarr Associative array of attributes.
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags
, $linkarr );
398 * Returns the current <link> tags
403 public function getLinkTags() {
404 return $this->mLinktags
;
408 * Add a new \<link\> with "rel" attribute set to "meta"
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl
= $url;
429 * Returns the URL to be used for the <link rel=canonical> if
433 * @return bool|string
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl
;
440 * Get the value of the "rel" attribute for metadata links
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
448 return 'alternate meta';
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
460 * @param string $script Raw HTML
462 function addScript( $script ) {
463 $this->mScripts
.= $script . "\n";
467 * Register and add a stylesheet from an extension directory.
469 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
470 * @param string $url Path to sheet. Provide either a full url (beginning
471 * with 'http', etc) or a relative path from the document root
472 * (beginning with '/'). Otherwise it behaves identically to
473 * addStyle() and draws from the /skins folder.
475 public function addExtensionStyle( $url ) {
476 wfDeprecated( __METHOD__
, '1.27' );
477 array_push( $this->mExtStyles
, $url );
481 * Get all styles added by extensions
483 * @deprecated since 1.27
486 function getExtStyle() {
487 wfDeprecated( __METHOD__
, '1.27' );
488 return $this->mExtStyles
;
492 * Add a JavaScript file out of skins/common, or a given relative path.
493 * Internal use only. Use OutputPage::addModules() if possible.
495 * @param string $file Filename in skins/common or complete on-server path
497 * @param string $version Style version of the file. Defaults to $wgStyleVersion
499 public function addScriptFile( $file, $version = null ) {
500 // See if $file parameter is an absolute URL or begins with a slash
501 if ( substr( $file, 0, 1 ) == '/' ||
preg_match( '#^[a-z]*://#i', $file ) ) {
504 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
506 if ( is_null( $version ) ) {
507 $version = $this->getConfig()->get( 'StyleVersion' );
509 $this->addScript( Html
::linkedScript( wfAppendQuery( $path, $version ) ) );
513 * Add a self-contained script tag with the given contents
514 * Internal use only. Use OutputPage::addModules() if possible.
516 * @param string $script JavaScript text, no "<script>" tags
518 public function addInlineScript( $script ) {
519 $this->mScripts
.= Html
::inlineScript( "\n$script\n" ) . "\n";
523 * Filter an array of modules to remove insufficiently trustworthy members, and modules
524 * which are no longer registered (eg a page is cached before an extension is disabled)
525 * @param array $modules
526 * @param string|null $position If not null, only return modules with this position
527 * @param string $type
530 protected function filterModules( array $modules, $position = null,
531 $type = ResourceLoaderModule
::TYPE_COMBINED
533 $resourceLoader = $this->getResourceLoader();
534 $filteredModules = [];
535 foreach ( $modules as $val ) {
536 $module = $resourceLoader->getModule( $val );
537 if ( $module instanceof ResourceLoaderModule
538 && $module->getOrigin() <= $this->getAllowedModules( $type )
539 && ( is_null( $position ) ||
$module->getPosition() == $position )
540 && ( !$this->mTarget ||
in_array( $this->mTarget
, $module->getTargets() ) )
542 $filteredModules[] = $val;
545 return $filteredModules;
549 * Get the list of modules to include on this page
551 * @param bool $filter Whether to filter out insufficiently trustworthy modules
552 * @param string|null $position If not null, only return modules with this position
553 * @param string $param
554 * @return array Array of module names
556 public function getModules( $filter = false, $position = null, $param = 'mModules' ) {
557 $modules = array_values( array_unique( $this->$param ) );
559 ?
$this->filterModules( $modules, $position )
564 * Add one or more modules recognized by ResourceLoader. Modules added
565 * through this function will be loaded by ResourceLoader when the
568 * @param string|array $modules Module name (string) or array of module names
570 public function addModules( $modules ) {
571 $this->mModules
= array_merge( $this->mModules
, (array)$modules );
575 * Get the list of module JS to include on this page
577 * @param bool $filter
578 * @param string|null $position
580 * @return array Array of module names
582 public function getModuleScripts( $filter = false, $position = null ) {
583 return $this->getModules( $filter, $position, 'mModuleScripts' );
587 * Add only JS of one or more modules recognized by ResourceLoader. Module
588 * scripts added through this function will be loaded by ResourceLoader when
591 * @param string|array $modules Module name (string) or array of module names
593 public function addModuleScripts( $modules ) {
594 $this->mModuleScripts
= array_merge( $this->mModuleScripts
, (array)$modules );
598 * Get the list of module CSS to include on this page
600 * @param bool $filter
601 * @param string|null $position
603 * @return array Array of module names
605 public function getModuleStyles( $filter = false, $position = null ) {
606 return $this->getModules( $filter, $position, 'mModuleStyles' );
610 * Add only CSS of one or more modules recognized by ResourceLoader.
612 * Module styles added through this function will be added using standard link CSS
613 * tags, rather than as a combined Javascript and CSS package. Thus, they will
614 * load when JavaScript is disabled (unless CSS also happens to be disabled).
616 * @param string|array $modules Module name (string) or array of module names
618 public function addModuleStyles( $modules ) {
619 $this->mModuleStyles
= array_merge( $this->mModuleStyles
, (array)$modules );
623 * Get the list of module messages to include on this page
625 * @deprecated since 1.26 Obsolete
626 * @param bool $filter
627 * @param string|null $position
628 * @return array Array of module names
630 public function getModuleMessages( $filter = false, $position = null ) {
631 wfDeprecated( __METHOD__
, '1.26' );
636 * Load messages of one or more ResourceLoader modules.
638 * @deprecated since 1.26 Use addModules() instead
639 * @param string|array $modules Module name (string) or array of module names
641 public function addModuleMessages( $modules ) {
642 wfDeprecated( __METHOD__
, '1.26' );
646 * @return null|string ResourceLoader target
648 public function getTarget() {
649 return $this->mTarget
;
653 * Sets ResourceLoader target for load.php links. If null, will be omitted
655 * @param string|null $target
657 public function setTarget( $target ) {
658 $this->mTarget
= $target;
662 * Get an array of head items
666 function getHeadItemsArray() {
667 return $this->mHeadItems
;
671 * Get all header items in a string
674 * @deprecated since 1.24 Use OutputPage::headElement or
675 * if absolutely necessary use OutputPage::getHeadItemsArray
677 function getHeadItems() {
678 wfDeprecated( __METHOD__
, '1.24' );
680 foreach ( $this->mHeadItems
as $item ) {
687 * Add or replace an header item to the output
689 * Whenever possible, use more specific options like ResourceLoader modules,
690 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
691 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
692 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
693 * This would be your very LAST fallback.
695 * @param string $name Item name
696 * @param string $value Raw HTML
698 public function addHeadItem( $name, $value ) {
699 $this->mHeadItems
[$name] = $value;
703 * Check if the header item $name is already set
705 * @param string $name Item name
708 public function hasHeadItem( $name ) {
709 return isset( $this->mHeadItems
[$name] );
713 * Set the value of the ETag HTTP header, only used if $wgUseETag is true
715 * @param string $tag Value of "ETag" header
717 function setETag( $tag ) {
722 * Set whether the output should only contain the body of the article,
723 * without any skin, sidebar, etc.
724 * Used e.g. when calling with "action=render".
726 * @param bool $only Whether to output only the body of the article
728 public function setArticleBodyOnly( $only ) {
729 $this->mArticleBodyOnly
= $only;
733 * Return whether the output will contain only the body of the article
737 public function getArticleBodyOnly() {
738 return $this->mArticleBodyOnly
;
742 * Set an additional output property
745 * @param string $name
746 * @param mixed $value
748 public function setProperty( $name, $value ) {
749 $this->mProperties
[$name] = $value;
753 * Get an additional output property
756 * @param string $name
757 * @return mixed Property value or null if not found
759 public function getProperty( $name ) {
760 if ( isset( $this->mProperties
[$name] ) ) {
761 return $this->mProperties
[$name];
768 * checkLastModified tells the client to use the client-cached page if
769 * possible. If successful, the OutputPage is disabled so that
770 * any future call to OutputPage->output() have no effect.
772 * Side effect: sets mLastModified for Last-Modified header
774 * @param string $timestamp
776 * @return bool True if cache-ok headers was sent.
778 public function checkLastModified( $timestamp ) {
779 if ( !$timestamp ||
$timestamp == '19700101000000' ) {
780 wfDebug( __METHOD__
. ": CACHE DISABLED, NO TIMESTAMP\n" );
783 $config = $this->getConfig();
784 if ( !$config->get( 'CachePages' ) ) {
785 wfDebug( __METHOD__
. ": CACHE DISABLED\n" );
789 $timestamp = wfTimestamp( TS_MW
, $timestamp );
791 'page' => $timestamp,
792 'user' => $this->getUser()->getTouched(),
793 'epoch' => $config->get( 'CacheEpoch' )
795 if ( $config->get( 'UseSquid' ) ) {
796 // bug 44570: the core page itself may not change, but resources might
797 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW
, time() - $config->get( 'SquidMaxage' ) );
799 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] );
801 $maxModified = max( $modifiedTimes );
802 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $maxModified );
804 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
805 if ( $clientHeader === false ) {
806 wfDebug( __METHOD__
. ": client did not send If-Modified-Since header", 'private' );
810 # IE sends sizes after the date like this:
811 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
812 # this breaks strtotime().
813 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
815 MediaWiki\
suppressWarnings(); // E_STRICT system time bitching
816 $clientHeaderTime = strtotime( $clientHeader );
817 MediaWiki\restoreWarnings
();
818 if ( !$clientHeaderTime ) {
820 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
823 $clientHeaderTime = wfTimestamp( TS_MW
, $clientHeaderTime );
827 foreach ( $modifiedTimes as $name => $value ) {
828 if ( $info !== '' ) {
831 $info .= "$name=" . wfTimestamp( TS_ISO_8601
, $value );
834 wfDebug( __METHOD__
. ": client sent If-Modified-Since: " .
835 wfTimestamp( TS_ISO_8601
, $clientHeaderTime ), 'private' );
836 wfDebug( __METHOD__
. ": effective Last-Modified: " .
837 wfTimestamp( TS_ISO_8601
, $maxModified ), 'private' );
838 if ( $clientHeaderTime < $maxModified ) {
839 wfDebug( __METHOD__
. ": STALE, $info", 'private' );
844 # Give a 304 Not Modified response code and disable body output
845 wfDebug( __METHOD__
. ": NOT MODIFIED, $info", 'private' );
846 ini_set( 'zlib.output_compression', 0 );
847 $this->getRequest()->response()->statusHeader( 304 );
848 $this->sendCacheControl();
851 // Don't output a compressed blob when using ob_gzhandler;
852 // it's technically against HTTP spec and seems to confuse
853 // Firefox when the response gets split over two packets.
854 wfClearOutputBuffers();
860 * Override the last modified timestamp
862 * @param string $timestamp New timestamp, in a format readable by
865 public function setLastModified( $timestamp ) {
866 $this->mLastModified
= wfTimestamp( TS_RFC2822
, $timestamp );
870 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
872 * @param string $policy The literal string to output as the contents of
873 * the meta tag. Will be parsed according to the spec and output in
877 public function setRobotPolicy( $policy ) {
878 $policy = Article
::formatRobotPolicy( $policy );
880 if ( isset( $policy['index'] ) ) {
881 $this->setIndexPolicy( $policy['index'] );
883 if ( isset( $policy['follow'] ) ) {
884 $this->setFollowPolicy( $policy['follow'] );
889 * Set the index policy for the page, but leave the follow policy un-
892 * @param string $policy Either 'index' or 'noindex'.
895 public function setIndexPolicy( $policy ) {
896 $policy = trim( $policy );
897 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
898 $this->mIndexPolicy
= $policy;
903 * Set the follow policy for the page, but leave the index policy un-
906 * @param string $policy Either 'follow' or 'nofollow'.
909 public function setFollowPolicy( $policy ) {
910 $policy = trim( $policy );
911 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
912 $this->mFollowPolicy
= $policy;
917 * Set the new value of the "action text", this will be added to the
918 * "HTML title", separated from it with " - ".
920 * @param string $text New value of the "action text"
922 public function setPageTitleActionText( $text ) {
923 $this->mPageTitleActionText
= $text;
927 * Get the value of the "action text"
931 public function getPageTitleActionText() {
932 return $this->mPageTitleActionText
;
936 * "HTML title" means the contents of "<title>".
937 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
939 * @param string|Message $name
941 public function setHTMLTitle( $name ) {
942 if ( $name instanceof Message
) {
943 $this->mHTMLtitle
= $name->setContext( $this->getContext() )->text();
945 $this->mHTMLtitle
= $name;
950 * Return the "HTML title", i.e. the content of the "<title>" tag.
954 public function getHTMLTitle() {
955 return $this->mHTMLtitle
;
959 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
963 public function setRedirectedFrom( $t ) {
964 $this->mRedirectedFrom
= $t;
968 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
969 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
970 * but not bad tags like \<script\>. This function automatically sets
971 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
972 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
973 * good tags like \<i\> will be dropped entirely.
975 * @param string|Message $name
977 public function setPageTitle( $name ) {
978 if ( $name instanceof Message
) {
979 $name = $name->setContext( $this->getContext() )->text();
982 # change "<script>foo&bar</script>" to "<script>foo&bar</script>"
983 # but leave "<i>foobar</i>" alone
984 $nameWithTags = Sanitizer
::normalizeCharReferences( Sanitizer
::removeHTMLtags( $name ) );
985 $this->mPagetitle
= $nameWithTags;
987 # change "<i>foo&bar</i>" to "foo&bar"
989 $this->msg( 'pagetitle' )->rawParams( Sanitizer
::stripAllTags( $nameWithTags ) )
990 ->inContentLanguage()
995 * Return the "page title", i.e. the content of the \<h1\> tag.
999 public function getPageTitle() {
1000 return $this->mPagetitle
;
1004 * Set the Title object to use
1008 public function setTitle( Title
$t ) {
1009 $this->getContext()->setTitle( $t );
1013 * Replace the subtitle with $str
1015 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1017 public function setSubtitle( $str ) {
1018 $this->clearSubtitle();
1019 $this->addSubtitle( $str );
1023 * Add $str to the subtitle
1025 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1027 public function addSubtitle( $str ) {
1028 if ( $str instanceof Message
) {
1029 $this->mSubtitle
[] = $str->setContext( $this->getContext() )->parse();
1031 $this->mSubtitle
[] = $str;
1036 * Build message object for a subtitle containing a backlink to a page
1038 * @param Title $title Title to link to
1039 * @param array $query Array of additional parameters to include in the link
1043 public static function buildBacklinkSubtitle( Title
$title, $query = [] ) {
1044 if ( $title->isRedirect() ) {
1045 $query['redirect'] = 'no';
1047 return wfMessage( 'backlinksubtitle' )
1048 ->rawParams( Linker
::link( $title, null, [], $query ) );
1052 * Add a subtitle containing a backlink to a page
1054 * @param Title $title Title to link to
1055 * @param array $query Array of additional parameters to include in the link
1057 public function addBacklinkSubtitle( Title
$title, $query = [] ) {
1058 $this->addSubtitle( self
::buildBacklinkSubtitle( $title, $query ) );
1062 * Clear the subtitles
1064 public function clearSubtitle() {
1065 $this->mSubtitle
= [];
1073 public function getSubtitle() {
1074 return implode( "<br />\n\t\t\t\t", $this->mSubtitle
);
1078 * Set the page as printable, i.e. it'll be displayed with all
1079 * print styles included
1081 public function setPrintable() {
1082 $this->mPrintable
= true;
1086 * Return whether the page is "printable"
1090 public function isPrintable() {
1091 return $this->mPrintable
;
1095 * Disable output completely, i.e. calling output() will have no effect
1097 public function disable() {
1098 $this->mDoNothing
= true;
1102 * Return whether the output will be completely disabled
1106 public function isDisabled() {
1107 return $this->mDoNothing
;
1111 * Show an "add new section" link?
1115 public function showNewSectionLink() {
1116 return $this->mNewSectionLink
;
1120 * Forcibly hide the new section link?
1124 public function forceHideNewSectionLink() {
1125 return $this->mHideNewSectionLink
;
1129 * Add or remove feed links in the page header
1130 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1131 * for the new version
1132 * @see addFeedLink()
1134 * @param bool $show True: add default feeds, false: remove all feeds
1136 public function setSyndicated( $show = true ) {
1138 $this->setFeedAppendQuery( false );
1140 $this->mFeedLinks
= [];
1145 * Add default feeds to the page header
1146 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1147 * for the new version
1148 * @see addFeedLink()
1150 * @param string $val Query to append to feed links or false to output
1153 public function setFeedAppendQuery( $val ) {
1154 $this->mFeedLinks
= [];
1156 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1157 $query = "feed=$type";
1158 if ( is_string( $val ) ) {
1159 $query .= '&' . $val;
1161 $this->mFeedLinks
[$type] = $this->getTitle()->getLocalURL( $query );
1166 * Add a feed link to the page header
1168 * @param string $format Feed type, should be a key of $wgFeedClasses
1169 * @param string $href URL
1171 public function addFeedLink( $format, $href ) {
1172 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1173 $this->mFeedLinks
[$format] = $href;
1178 * Should we output feed links for this page?
1181 public function isSyndicated() {
1182 return count( $this->mFeedLinks
) > 0;
1186 * Return URLs for each supported syndication format for this page.
1187 * @return array Associating format keys with URLs
1189 public function getSyndicationLinks() {
1190 return $this->mFeedLinks
;
1194 * Will currently always return null
1198 public function getFeedAppendQuery() {
1199 return $this->mFeedLinksAppendQuery
;
1203 * Set whether the displayed content is related to the source of the
1204 * corresponding article on the wiki
1205 * Setting true will cause the change "article related" toggle to true
1209 public function setArticleFlag( $v ) {
1210 $this->mIsarticle
= $v;
1212 $this->mIsArticleRelated
= $v;
1217 * Return whether the content displayed page is related to the source of
1218 * the corresponding article on the wiki
1222 public function isArticle() {
1223 return $this->mIsarticle
;
1227 * Set whether this page is related an article on the wiki
1228 * Setting false will cause the change of "article flag" toggle to false
1232 public function setArticleRelated( $v ) {
1233 $this->mIsArticleRelated
= $v;
1235 $this->mIsarticle
= false;
1240 * Return whether this page is related an article on the wiki
1244 public function isArticleRelated() {
1245 return $this->mIsArticleRelated
;
1249 * Add new language links
1251 * @param array $newLinkArray Associative array mapping language code to the page
1254 public function addLanguageLinks( array $newLinkArray ) {
1255 $this->mLanguageLinks +
= $newLinkArray;
1259 * Reset the language links and add new language links
1261 * @param array $newLinkArray Associative array mapping language code to the page
1264 public function setLanguageLinks( array $newLinkArray ) {
1265 $this->mLanguageLinks
= $newLinkArray;
1269 * Get the list of language links
1271 * @return array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
1273 public function getLanguageLinks() {
1274 return $this->mLanguageLinks
;
1278 * Add an array of categories, with names in the keys
1280 * @param array $categories Mapping category name => sort key
1282 public function addCategoryLinks( array $categories ) {
1285 if ( !is_array( $categories ) ||
count( $categories ) == 0 ) {
1289 # Add the links to a LinkBatch
1290 $arr = [ NS_CATEGORY
=> $categories ];
1291 $lb = new LinkBatch
;
1292 $lb->setArray( $arr );
1294 # Fetch existence plus the hiddencat property
1295 $dbr = wfGetDB( DB_SLAVE
);
1296 $fields = [ 'page_id', 'page_namespace', 'page_title', 'page_len',
1297 'page_is_redirect', 'page_latest', 'pp_value' ];
1299 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
1300 $fields[] = 'page_content_model';
1302 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
1303 $fields[] = 'page_lang';
1306 $res = $dbr->select( [ 'page', 'page_props' ],
1308 $lb->constructSet( 'page', $dbr ),
1311 [ 'page_props' => [ 'LEFT JOIN', [
1312 'pp_propname' => 'hiddencat',
1317 # Add the results to the link cache
1318 $lb->addResultToCache( LinkCache
::singleton(), $res );
1320 # Set all the values to 'normal'.
1321 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1323 # Mark hidden categories
1324 foreach ( $res as $row ) {
1325 if ( isset( $row->pp_value
) ) {
1326 $categories[$row->page_title
] = 'hidden';
1330 # Add the remaining categories to the skin
1332 'OutputPageMakeCategoryLinks',
1333 [ &$this, $categories, &$this->mCategoryLinks
] )
1335 foreach ( $categories as $category => $type ) {
1336 // array keys will cast numeric category names to ints, so cast back to string
1337 $category = (string)$category;
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
= [];
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( [ '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 = [], $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 ( $options !== null && !empty( $options->isBogus
) ) {
1569 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1570 // been changed somehow, and keep it if so.
1571 $anonPO = ParserOptions
::newFromAnon();
1572 $anonPO->setEditSection( false );
1573 if ( !$options->matches( $anonPO ) ) {
1574 wfLogWarning( __METHOD__
. ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1575 $options->isBogus
= false;
1579 if ( !$this->mParserOptions
) {
1580 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1581 // $wgUser isn't unstubbable yet, so don't try to get a
1582 // ParserOptions for it. And don't cache this ParserOptions
1584 $po = ParserOptions
::newFromAnon();
1585 $po->setEditSection( false );
1586 $po->isBogus
= true;
1587 if ( $options !== null ) {
1588 $this->mParserOptions
= empty( $options->isBogus
) ?
$options : null;
1593 $this->mParserOptions
= ParserOptions
::newFromContext( $this->getContext() );
1594 $this->mParserOptions
->setEditSection( false );
1597 if ( $options !== null && !empty( $options->isBogus
) ) {
1598 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1600 return wfSetVar( $this->mParserOptions
, null, true );
1602 return wfSetVar( $this->mParserOptions
, $options );
1607 * Set the revision ID which will be seen by the wiki text parser
1608 * for things such as embedded {{REVISIONID}} variable use.
1610 * @param int|null $revid An positive integer, or null
1611 * @return mixed Previous value
1613 public function setRevisionId( $revid ) {
1614 $val = is_null( $revid ) ?
null : intval( $revid );
1615 return wfSetVar( $this->mRevisionId
, $val );
1619 * Get the displayed revision ID
1623 public function getRevisionId() {
1624 return $this->mRevisionId
;
1628 * Set the timestamp of the revision which will be displayed. This is used
1629 * to avoid a extra DB call in Skin::lastModified().
1631 * @param string|null $timestamp
1632 * @return mixed Previous value
1634 public function setRevisionTimestamp( $timestamp ) {
1635 return wfSetVar( $this->mRevisionTimestamp
, $timestamp );
1639 * Get the timestamp of displayed revision.
1640 * This will be null if not filled by setRevisionTimestamp().
1642 * @return string|null
1644 public function getRevisionTimestamp() {
1645 return $this->mRevisionTimestamp
;
1649 * Set the displayed file version
1651 * @param File|bool $file
1652 * @return mixed Previous value
1654 public function setFileVersion( $file ) {
1656 if ( $file instanceof File
&& $file->exists() ) {
1657 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1659 return wfSetVar( $this->mFileVersion
, $val, true );
1663 * Get the displayed file version
1665 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1667 public function getFileVersion() {
1668 return $this->mFileVersion
;
1672 * Get the templates used on this page
1674 * @return array (namespace => dbKey => revId)
1677 public function getTemplateIds() {
1678 return $this->mTemplateIds
;
1682 * Get the files used on this page
1684 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1687 public function getFileSearchOptions() {
1688 return $this->mImageTimeKeys
;
1692 * Convert wikitext to HTML and add it to the buffer
1693 * Default assumes that the current page title will be used.
1695 * @param string $text
1696 * @param bool $linestart Is this the start of a line?
1697 * @param bool $interface Is this text in the user interface language?
1698 * @throws MWException
1700 public function addWikiText( $text, $linestart = true, $interface = true ) {
1701 $title = $this->getTitle(); // Work around E_STRICT
1703 throw new MWException( 'Title is null' );
1705 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1709 * Add wikitext with a custom Title object
1711 * @param string $text Wikitext
1712 * @param Title $title
1713 * @param bool $linestart Is this the start of a line?
1715 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1716 $this->addWikiTextTitle( $text, $title, $linestart );
1720 * Add wikitext with a custom Title object and tidy enabled.
1722 * @param string $text Wikitext
1723 * @param Title $title
1724 * @param bool $linestart Is this the start of a line?
1726 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1727 $this->addWikiTextTitle( $text, $title, $linestart, true );
1731 * Add wikitext with tidy enabled
1733 * @param string $text Wikitext
1734 * @param bool $linestart Is this the start of a line?
1736 public function addWikiTextTidy( $text, $linestart = true ) {
1737 $title = $this->getTitle();
1738 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1742 * Add wikitext with a custom Title object
1744 * @param string $text Wikitext
1745 * @param Title $title
1746 * @param bool $linestart Is this the start of a line?
1747 * @param bool $tidy Whether to use tidy
1748 * @param bool $interface Whether it is an interface message
1749 * (for example disables conversion)
1751 public function addWikiTextTitle( $text, Title
$title, $linestart,
1752 $tidy = false, $interface = false
1756 $popts = $this->parserOptions();
1757 $oldTidy = $popts->setTidy( $tidy );
1758 $popts->setInterfaceMessage( (bool)$interface );
1760 $parserOutput = $wgParser->getFreshParser()->parse(
1761 $text, $title, $popts,
1762 $linestart, true, $this->mRevisionId
1765 $popts->setTidy( $oldTidy );
1767 $this->addParserOutput( $parserOutput );
1772 * Add a ParserOutput object, but without Html.
1774 * @deprecated since 1.24, use addParserOutputMetadata() instead.
1775 * @param ParserOutput $parserOutput
1777 public function addParserOutputNoText( $parserOutput ) {
1778 wfDeprecated( __METHOD__
, '1.24' );
1779 $this->addParserOutputMetadata( $parserOutput );
1783 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1784 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1788 * @param ParserOutput $parserOutput
1790 public function addParserOutputMetadata( $parserOutput ) {
1791 $this->mLanguageLinks +
= $parserOutput->getLanguageLinks();
1792 $this->addCategoryLinks( $parserOutput->getCategories() );
1793 $this->setIndicators( $parserOutput->getIndicators() );
1794 $this->mNewSectionLink
= $parserOutput->getNewSection();
1795 $this->mHideNewSectionLink
= $parserOutput->getHideNewSection();
1797 if ( !$parserOutput->isCacheable() ) {
1798 $this->enableClientCache( false );
1800 $this->mNoGallery
= $parserOutput->getNoGallery();
1801 $this->mHeadItems
= array_merge( $this->mHeadItems
, $parserOutput->getHeadItems() );
1802 $this->addModules( $parserOutput->getModules() );
1803 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1804 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1805 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1806 $this->mPreventClickjacking
= $this->mPreventClickjacking
1807 ||
$parserOutput->preventClickjacking();
1809 // Template versioning...
1810 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1811 if ( isset( $this->mTemplateIds
[$ns] ) ) {
1812 $this->mTemplateIds
[$ns] = $dbks +
$this->mTemplateIds
[$ns];
1814 $this->mTemplateIds
[$ns] = $dbks;
1817 // File versioning...
1818 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1819 $this->mImageTimeKeys
[$dbk] = $data;
1822 // Hooks registered in the object
1823 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1824 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1825 list( $hookName, $data ) = $hookInfo;
1826 if ( isset( $parserOutputHooks[$hookName] ) ) {
1827 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1831 // enable OOUI if requested via ParserOutput
1832 if ( $parserOutput->getEnableOOUI() ) {
1833 $this->enableOOUI();
1836 // Link flags are ignored for now, but may in the future be
1837 // used to mark individual language links.
1839 Hooks
::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks
, &$linkFlags ] );
1840 Hooks
::run( 'OutputPageParserOutput', [ &$this, $parserOutput ] );
1844 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1845 * ParserOutput object, without any other metadata.
1848 * @param ParserOutput $parserOutput
1850 public function addParserOutputContent( $parserOutput ) {
1851 $this->addParserOutputText( $parserOutput );
1853 $this->addModules( $parserOutput->getModules() );
1854 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1855 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1857 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1861 * Add the HTML associated with a ParserOutput object, without any metadata.
1864 * @param ParserOutput $parserOutput
1866 public function addParserOutputText( $parserOutput ) {
1867 $text = $parserOutput->getText();
1868 Hooks
::run( 'OutputPageBeforeHTML', [ &$this, &$text ] );
1869 $this->addHTML( $text );
1873 * Add everything from a ParserOutput object.
1875 * @param ParserOutput $parserOutput
1877 function addParserOutput( $parserOutput ) {
1878 $this->addParserOutputMetadata( $parserOutput );
1879 $parserOutput->setTOCEnabled( $this->mEnableTOC
);
1881 // Touch section edit links only if not previously disabled
1882 if ( $parserOutput->getEditSectionTokens() ) {
1883 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks
);
1886 $this->addParserOutputText( $parserOutput );
1890 * Add the output of a QuickTemplate to the output buffer
1892 * @param QuickTemplate $template
1894 public function addTemplate( &$template ) {
1895 $this->addHTML( $template->getHTML() );
1899 * Parse wikitext and return the HTML.
1901 * @param string $text
1902 * @param bool $linestart Is this the start of a line?
1903 * @param bool $interface Use interface language ($wgLang instead of
1904 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1905 * This also disables LanguageConverter.
1906 * @param Language $language Target language object, will override $interface
1907 * @throws MWException
1908 * @return string HTML
1910 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1913 if ( is_null( $this->getTitle() ) ) {
1914 throw new MWException( 'Empty $mTitle in ' . __METHOD__
);
1917 $popts = $this->parserOptions();
1919 $popts->setInterfaceMessage( true );
1921 if ( $language !== null ) {
1922 $oldLang = $popts->setTargetLanguage( $language );
1925 $parserOutput = $wgParser->getFreshParser()->parse(
1926 $text, $this->getTitle(), $popts,
1927 $linestart, true, $this->mRevisionId
1931 $popts->setInterfaceMessage( false );
1933 if ( $language !== null ) {
1934 $popts->setTargetLanguage( $oldLang );
1937 return $parserOutput->getText();
1941 * Parse wikitext, strip paragraphs, and return the HTML.
1943 * @param string $text
1944 * @param bool $linestart Is this the start of a line?
1945 * @param bool $interface Use interface language ($wgLang instead of
1946 * $wgContLang) while parsing language sensitive magic
1947 * words like GRAMMAR and PLURAL
1948 * @return string HTML
1950 public function parseInline( $text, $linestart = true, $interface = false ) {
1951 $parsed = $this->parse( $text, $linestart, $interface );
1952 return Parser
::stripOuterParagraph( $parsed );
1957 * @deprecated since 1.27 Use setCdnMaxage() instead
1959 public function setSquidMaxage( $maxage ) {
1960 $this->setCdnMaxage( $maxage );
1964 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1966 * @param int $maxage Maximum cache time on the CDN, in seconds.
1968 public function setCdnMaxage( $maxage ) {
1969 $this->mCdnMaxage
= min( $maxage, $this->mCdnMaxageLimit
);
1973 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1975 * @param int $maxage Maximum cache time on the CDN, in seconds
1978 public function lowerCdnMaxage( $maxage ) {
1979 $this->mCdnMaxageLimit
= min( $maxage, $this->mCdnMaxageLimit
);
1980 $this->setCdnMaxage( $this->mCdnMaxage
);
1984 * Use enableClientCache(false) to force it to send nocache headers
1986 * @param bool $state
1990 public function enableClientCache( $state ) {
1991 return wfSetVar( $this->mEnableClientCache
, $state );
1995 * Get the list of cookies that will influence on the cache
1999 function getCacheVaryCookies() {
2001 if ( $cookies === null ) {
2002 $config = $this->getConfig();
2003 $cookies = array_merge(
2004 SessionManager
::singleton()->getVaryCookies(),
2008 $config->get( 'CacheVaryCookies' )
2010 Hooks
::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2016 * Check if the request has a cache-varying cookie header
2017 * If it does, it's very important that we don't allow public caching
2021 function haveCacheVaryCookies() {
2022 $request = $this->getRequest();
2023 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2024 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2025 wfDebug( __METHOD__
. ": found $cookieName\n" );
2029 wfDebug( __METHOD__
. ": no cache-varying cookies found\n" );
2034 * Add an HTTP header that will influence on the cache
2036 * @param string $header Header name
2037 * @param string[]|null $option Options for the Key header. See
2038 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2039 * for the list of valid options.
2041 public function addVaryHeader( $header, array $option = null ) {
2042 if ( !array_key_exists( $header, $this->mVaryHeader
) ) {
2043 $this->mVaryHeader
[$header] = [];
2045 if ( !is_array( $option ) ) {
2048 $this->mVaryHeader
[$header] = array_unique( array_merge( $this->mVaryHeader
[$header], $option ) );
2052 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2053 * such as Accept-Encoding or Cookie
2057 public function getVaryHeader() {
2058 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2059 $this->addVaryHeader( $header, $options );
2061 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader
) );
2065 * Get a complete Key header
2069 public function getKeyHeader() {
2070 $cvCookies = $this->getCacheVaryCookies();
2072 $cookiesOption = [];
2073 foreach ( $cvCookies as $cookieName ) {
2074 $cookiesOption[] = 'param=' . $cookieName;
2076 $this->addVaryHeader( 'Cookie', $cookiesOption );
2078 foreach ( SessionManager
::singleton()->getVaryHeaders() as $header => $options ) {
2079 $this->addVaryHeader( $header, $options );
2083 foreach ( $this->mVaryHeader
as $header => $option ) {
2084 $newheader = $header;
2085 if ( is_array( $option ) && count( $option ) > 0 ) {
2086 $newheader .= ';' . implode( ';', $option );
2088 $headers[] = $newheader;
2090 $key = 'Key: ' . implode( ',', $headers );
2096 * T23672: Add Accept-Language to Vary and Key headers
2097 * if there's no 'variant' parameter existed in GET.
2100 * /w/index.php?title=Main_page should always be served; but
2101 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2103 function addAcceptLanguage() {
2104 $title = $this->getTitle();
2105 if ( !$title instanceof Title
) {
2109 $lang = $title->getPageLanguage();
2110 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2111 $variants = $lang->getVariants();
2113 foreach ( $variants as $variant ) {
2114 if ( $variant === $lang->getCode() ) {
2117 $aloption[] = 'substr=' . $variant;
2119 // IE and some other browsers use BCP 47 standards in
2120 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2121 // We should handle these too.
2122 $variantBCP47 = wfBCP47( $variant );
2123 if ( $variantBCP47 !== $variant ) {
2124 $aloption[] = 'substr=' . $variantBCP47;
2128 $this->addVaryHeader( 'Accept-Language', $aloption );
2133 * Set a flag which will cause an X-Frame-Options header appropriate for
2134 * edit pages to be sent. The header value is controlled by
2135 * $wgEditPageFrameOptions.
2137 * This is the default for special pages. If you display a CSRF-protected
2138 * form on an ordinary view page, then you need to call this function.
2140 * @param bool $enable
2142 public function preventClickjacking( $enable = true ) {
2143 $this->mPreventClickjacking
= $enable;
2147 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2148 * This can be called from pages which do not contain any CSRF-protected
2151 public function allowClickjacking() {
2152 $this->mPreventClickjacking
= false;
2156 * Get the prevent-clickjacking flag
2161 public function getPreventClickjacking() {
2162 return $this->mPreventClickjacking
;
2166 * Get the X-Frame-Options header value (without the name part), or false
2167 * if there isn't one. This is used by Skin to determine whether to enable
2168 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2172 public function getFrameOptions() {
2173 $config = $this->getConfig();
2174 if ( $config->get( 'BreakFrames' ) ) {
2176 } elseif ( $this->mPreventClickjacking
&& $config->get( 'EditPageFrameOptions' ) ) {
2177 return $config->get( 'EditPageFrameOptions' );
2183 * Send cache control HTTP headers
2185 public function sendCacheControl() {
2186 $response = $this->getRequest()->response();
2187 $config = $this->getConfig();
2188 if ( $config->get( 'UseETag' ) && $this->mETag
) {
2189 $response->header( "ETag: $this->mETag" );
2192 $this->addVaryHeader( 'Cookie' );
2193 $this->addAcceptLanguage();
2195 # don't serve compressed data to clients who can't handle it
2196 # maintain different caches for logged-in users and non-logged in ones
2197 $response->header( $this->getVaryHeader() );
2199 if ( $config->get( 'UseKeyHeader' ) ) {
2200 $response->header( $this->getKeyHeader() );
2203 if ( $this->mEnableClientCache
) {
2205 $config->get( 'UseSquid' ) &&
2206 !$response->hasCookies() &&
2207 !SessionManager
::getGlobalSession()->isPersistent() &&
2208 !$this->isPrintable() &&
2209 $this->mCdnMaxage
!= 0 &&
2210 !$this->haveCacheVaryCookies()
2212 if ( $config->get( 'UseESI' ) ) {
2213 # We'll purge the proxy cache explicitly, but require end user agents
2214 # to revalidate against the proxy on each visit.
2215 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2216 wfDebug( __METHOD__
. ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2217 # start with a shorter timeout for initial testing
2218 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2219 $response->header( 'Surrogate-Control: max-age=' . $config->get( 'SquidMaxage' )
2220 . '+' . $this->mCdnMaxage
. ', content="ESI/1.0"' );
2221 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2223 # We'll purge the proxy cache for anons explicitly, but require end user agents
2224 # to revalidate against the proxy on each visit.
2225 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2226 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2227 wfDebug( __METHOD__
. ": local proxy caching; {$this->mLastModified} **", 'private' );
2228 # start with a shorter timeout for initial testing
2229 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2230 $response->header( 'Cache-Control: s-maxage=' . $this->mCdnMaxage
2231 . ', must-revalidate, max-age=0' );
2234 # We do want clients to cache if they can, but they *must* check for updates
2235 # on revisiting the page.
2236 wfDebug( __METHOD__
. ": private caching; {$this->mLastModified} **", 'private' );
2237 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2238 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2240 if ( $this->mLastModified
) {
2241 $response->header( "Last-Modified: {$this->mLastModified}" );
2244 wfDebug( __METHOD__
. ": no caching **", 'private' );
2246 # In general, the absence of a last modified header should be enough to prevent
2247 # the client from using its cache. We send a few other things just to make sure.
2248 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2249 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2250 $response->header( 'Pragma: no-cache' );
2255 * Finally, all the text has been munged and accumulated into
2256 * the object, let's actually output it:
2258 public function output() {
2259 if ( $this->mDoNothing
) {
2263 $response = $this->getRequest()->response();
2264 $config = $this->getConfig();
2266 if ( $this->mRedirect
!= '' ) {
2267 # Standards require redirect URLs to be absolute
2268 $this->mRedirect
= wfExpandUrl( $this->mRedirect
, PROTO_CURRENT
);
2270 $redirect = $this->mRedirect
;
2271 $code = $this->mRedirectCode
;
2273 if ( Hooks
::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2274 if ( $code == '301' ||
$code == '303' ) {
2275 if ( !$config->get( 'DebugRedirects' ) ) {
2276 $response->statusHeader( $code );
2278 $this->mLastModified
= wfTimestamp( TS_RFC2822
);
2280 if ( $config->get( 'VaryOnXFP' ) ) {
2281 $this->addVaryHeader( 'X-Forwarded-Proto' );
2283 $this->sendCacheControl();
2285 $response->header( "Content-Type: text/html; charset=utf-8" );
2286 if ( $config->get( 'DebugRedirects' ) ) {
2287 $url = htmlspecialchars( $redirect );
2288 print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2289 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2290 print "</body>\n</html>\n";
2292 $response->header( 'Location: ' . $redirect );
2297 } elseif ( $this->mStatusCode
) {
2298 $response->statusHeader( $this->mStatusCode
);
2301 # Buffer output; final headers may depend on later processing
2304 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2305 $response->header( 'Content-language: ' . $config->get( 'LanguageCode' ) );
2307 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2308 // jQuery etc. can work correctly.
2309 $response->header( 'X-UA-Compatible: IE=Edge' );
2311 // Prevent framing, if requested
2312 $frameOptions = $this->getFrameOptions();
2313 if ( $frameOptions ) {
2314 $response->header( "X-Frame-Options: $frameOptions" );
2317 if ( $this->mArticleBodyOnly
) {
2318 echo $this->mBodytext
;
2320 $sk = $this->getSkin();
2321 // add skin specific modules
2322 $modules = $sk->getDefaultModules();
2324 // Enforce various default modules for all skins
2326 // Keep this list as small as possible
2328 'mediawiki.page.startup',
2332 // Support for high-density display images if enabled
2333 if ( $config->get( 'ResponsiveImages' ) ) {
2334 $coreModules[] = 'mediawiki.hidpi';
2337 $this->addModules( $coreModules );
2338 foreach ( $modules as $group ) {
2339 $this->addModules( $group );
2341 MWDebug
::addModules( $this );
2343 // Hook that allows last minute changes to the output page, e.g.
2344 // adding of CSS or Javascript by extensions.
2345 Hooks
::run( 'BeforePageDisplay', [ &$this, &$sk ] );
2350 // This hook allows last minute changes to final overall output by modifying output buffer
2351 Hooks
::run( 'AfterFinalPageOutput', [ $this ] );
2353 $this->sendCacheControl();
2360 * Actually output something with print.
2362 * @param string $ins The string to output
2363 * @deprecated since 1.22 Use echo yourself.
2365 public function out( $ins ) {
2366 wfDeprecated( __METHOD__
, '1.22' );
2371 * Prepare this object to display an error page; disable caching and
2372 * indexing, clear the current text and redirect, set the page's title
2373 * and optionally an custom HTML title (content of the "<title>" tag).
2375 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2376 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2377 * optional, if not passed the "<title>" attribute will be
2378 * based on $pageTitle
2380 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2381 $this->setPageTitle( $pageTitle );
2382 if ( $htmlTitle !== false ) {
2383 $this->setHTMLTitle( $htmlTitle );
2385 $this->setRobotPolicy( 'noindex,nofollow' );
2386 $this->setArticleRelated( false );
2387 $this->enableClientCache( false );
2388 $this->mRedirect
= '';
2389 $this->clearSubtitle();
2394 * Output a standard error page
2396 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2397 * showErrorPage( 'titlemsg', 'pagetextmsg', array( 'param1', 'param2' ) );
2398 * showErrorPage( 'titlemsg', $messageObject );
2399 * showErrorPage( $titleMessageObject, $messageObject );
2401 * @param string|Message $title Message key (string) for page title, or a Message object
2402 * @param string|Message $msg Message key (string) for page text, or a Message object
2403 * @param array $params Message parameters; ignored if $msg is a Message object
2405 public function showErrorPage( $title, $msg, $params = [] ) {
2406 if ( !$title instanceof Message
) {
2407 $title = $this->msg( $title );
2410 $this->prepareErrorPage( $title );
2412 if ( $msg instanceof Message
) {
2413 if ( $params !== [] ) {
2414 trigger_error( 'Argument ignored: $params. The message parameters argument '
2415 . 'is discarded when the $msg argument is a Message object instead of '
2416 . 'a string.', E_USER_NOTICE
);
2418 $this->addHTML( $msg->parseAsBlock() );
2420 $this->addWikiMsgArray( $msg, $params );
2423 $this->returnToMain();
2427 * Output a standard permission error page
2429 * @param array $errors Error message keys
2430 * @param string $action Action that was denied or null if unknown
2432 public function showPermissionsErrorPage( array $errors, $action = null ) {
2433 // For some action (read, edit, create and upload), display a "login to do this action"
2434 // error if all of the following conditions are met:
2435 // 1. the user is not logged in
2436 // 2. the only error is insufficient permissions (i.e. no block or something else)
2437 // 3. the error can be avoided simply by logging in
2438 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2439 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2440 && ( $errors[0][0] == 'badaccess-groups' ||
$errors[0][0] == 'badaccess-group0' )
2441 && ( User
::groupHasPermission( 'user', $action )
2442 || User
::groupHasPermission( 'autoconfirmed', $action ) )
2444 $displayReturnto = null;
2446 # Due to bug 32276, if a user does not have read permissions,
2447 # $this->getTitle() will just give Special:Badtitle, which is
2448 # not especially useful as a returnto parameter. Use the title
2449 # from the request instead, if there was one.
2450 $request = $this->getRequest();
2451 $returnto = Title
::newFromText( $request->getVal( 'title', '' ) );
2452 if ( $action == 'edit' ) {
2453 $msg = 'whitelistedittext';
2454 $displayReturnto = $returnto;
2455 } elseif ( $action == 'createpage' ||
$action == 'createtalk' ) {
2456 $msg = 'nocreatetext';
2457 } elseif ( $action == 'upload' ) {
2458 $msg = 'uploadnologintext';
2460 $msg = 'loginreqpagetext';
2461 $displayReturnto = Title
::newMainPage();
2467 $query['returnto'] = $returnto->getPrefixedText();
2469 if ( !$request->wasPosted() ) {
2470 $returntoquery = $request->getValues();
2471 unset( $returntoquery['title'] );
2472 unset( $returntoquery['returnto'] );
2473 unset( $returntoquery['returntoquery'] );
2474 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2477 $loginLink = Linker
::linkKnown(
2478 SpecialPage
::getTitleFor( 'Userlogin' ),
2479 $this->msg( 'loginreqlink' )->escaped(),
2484 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2485 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2487 # Don't return to a page the user can't read otherwise
2488 # we'll end up in a pointless loop
2489 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2490 $this->returnToMain( null, $displayReturnto );
2493 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2494 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2499 * Display an error page indicating that a given version of MediaWiki is
2500 * required to use it
2502 * @param mixed $version The version of MediaWiki needed to use the page
2504 public function versionRequired( $version ) {
2505 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2507 $this->addWikiMsg( 'versionrequiredtext', $version );
2508 $this->returnToMain();
2512 * Format a list of error messages
2514 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2515 * @param string $action Action that was denied or null if unknown
2516 * @return string The wikitext error-messages, formatted into a list.
2518 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2519 if ( $action == null ) {
2520 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2522 $action_desc = $this->msg( "action-$action" )->plain();
2524 'permissionserrorstext-withaction',
2527 )->plain() . "\n\n";
2530 if ( count( $errors ) > 1 ) {
2531 $text .= '<ul class="permissions-errors">' . "\n";
2533 foreach ( $errors as $error ) {
2535 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2540 $text .= "<div class=\"permissions-errors\">\n" .
2541 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2549 * Display a page stating that the Wiki is in read-only mode.
2550 * Should only be called after wfReadOnly() has returned true.
2552 * Historically, this function was used to show the source of the page that the user
2553 * was trying to edit and _also_ permissions error messages. The relevant code was
2554 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2556 * @deprecated since 1.25; throw the exception directly
2557 * @throws ReadOnlyError
2559 public function readOnlyPage() {
2560 if ( func_num_args() > 0 ) {
2561 throw new MWException( __METHOD__
. ' no longer accepts arguments since 1.25.' );
2564 throw new ReadOnlyError
;
2568 * Turn off regular page output and return an error response
2569 * for when rate limiting has triggered.
2571 * @deprecated since 1.25; throw the exception directly
2573 public function rateLimited() {
2574 wfDeprecated( __METHOD__
, '1.25' );
2575 throw new ThrottledError
;
2579 * Show a warning about slave lag
2581 * If the lag is higher than $wgSlaveLagCritical seconds,
2582 * then the warning is a bit more obvious. If the lag is
2583 * lower than $wgSlaveLagWarning, then no warning is shown.
2585 * @param int $lag Slave lag
2587 public function showLagWarning( $lag ) {
2588 $config = $this->getConfig();
2589 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2590 $message = $lag < $config->get( 'SlaveLagCritical' )
2593 $wrap = Html
::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2594 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2598 public function showFatalError( $message ) {
2599 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2601 $this->addHTML( $message );
2604 public function showUnexpectedValueError( $name, $val ) {
2605 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2608 public function showFileCopyError( $old, $new ) {
2609 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2612 public function showFileRenameError( $old, $new ) {
2613 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2616 public function showFileDeleteError( $name ) {
2617 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2620 public function showFileNotFoundError( $name ) {
2621 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2625 * Add a "return to" link pointing to a specified title
2627 * @param Title $title Title to link
2628 * @param array $query Query string parameters
2629 * @param string $text Text of the link (input is not escaped)
2630 * @param array $options Options array to pass to Linker
2632 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2633 $link = $this->msg( 'returnto' )->rawParams(
2634 Linker
::link( $title, $text, [], $query, $options ) )->escaped();
2635 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2639 * Add a "return to" link pointing to a specified title,
2640 * or the title indicated in the request, or else the main page
2642 * @param mixed $unused
2643 * @param Title|string $returnto Title or String to return to
2644 * @param string $returntoquery Query string for the return to link
2646 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2647 if ( $returnto == null ) {
2648 $returnto = $this->getRequest()->getText( 'returnto' );
2651 if ( $returntoquery == null ) {
2652 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2655 if ( $returnto === '' ) {
2656 $returnto = Title
::newMainPage();
2659 if ( is_object( $returnto ) ) {
2660 $titleObj = $returnto;
2662 $titleObj = Title
::newFromText( $returnto );
2664 if ( !is_object( $titleObj ) ) {
2665 $titleObj = Title
::newMainPage();
2668 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2672 * @param Skin $sk The given Skin
2673 * @param bool $includeStyle Unused
2674 * @return string The doctype, opening "<html>", and head element.
2676 public function headElement( Skin
$sk, $includeStyle = true ) {
2679 $userdir = $this->getLanguage()->getDir();
2680 $sitedir = $wgContLang->getDir();
2682 $ret = Html
::htmlHeader( $sk->getHtmlElementAttributes() );
2684 if ( $this->getHTMLTitle() == '' ) {
2685 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2688 $openHead = Html
::openElement( 'head' );
2690 # Don't bother with the newline if $head == ''
2691 $ret .= "$openHead\n";
2694 if ( !Html
::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2695 // Add <meta charset="UTF-8">
2696 // This should be before <title> since it defines the charset used by
2697 // text including the text inside <title>.
2698 // The spec recommends defining XHTML5's charset using the XML declaration
2700 // Our XML declaration is output by Html::htmlHeader.
2701 // http://www.whatwg.org/html/semantics.html#attr-meta-http-equiv-content-type
2702 // http://www.whatwg.org/html/semantics.html#charset
2703 $ret .= Html
::element( 'meta', [ 'charset' => 'UTF-8' ] ) . "\n";
2706 $ret .= Html
::element( 'title', null, $this->getHTMLTitle() ) . "\n";
2707 $ret .= $this->getInlineHeadScripts() . "\n";
2708 $ret .= $this->buildCssLinks() . "\n";
2709 $ret .= $this->getExternalHeadScripts() . "\n";
2711 foreach ( $this->getHeadLinksArray() as $item ) {
2712 $ret .= $item . "\n";
2715 foreach ( $this->mHeadItems
as $item ) {
2716 $ret .= $item . "\n";
2719 $closeHead = Html
::closeElement( 'head' );
2721 $ret .= "$closeHead\n";
2725 $bodyClasses[] = 'mediawiki';
2727 # Classes for LTR/RTL directionality support
2728 $bodyClasses[] = $userdir;
2729 $bodyClasses[] = "sitedir-$sitedir";
2731 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2732 # A <body> class is probably not the best way to do this . . .
2733 $bodyClasses[] = 'capitalize-all-nouns';
2736 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2737 $bodyClasses[] = 'skin-' . Sanitizer
::escapeClass( $sk->getSkinName() );
2739 'action-' . Sanitizer
::escapeClass( Action
::getActionName( $this->getContext() ) );
2742 // While the implode() is not strictly needed, it's used for backwards compatibility
2743 // (this used to be built as a string and hooks likely still expect that).
2744 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2746 // Allow skins and extensions to add body attributes they need
2747 $sk->addToBodyAttributes( $this, $bodyAttrs );
2748 Hooks
::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2750 $ret .= Html
::openElement( 'body', $bodyAttrs ) . "\n";
2756 * Get a ResourceLoader object associated with this OutputPage
2758 * @return ResourceLoader
2760 public function getResourceLoader() {
2761 if ( is_null( $this->mResourceLoader
) ) {
2762 $this->mResourceLoader
= new ResourceLoader(
2764 LoggerFactory
::getInstance( 'resourceloader' )
2767 return $this->mResourceLoader
;
2771 * Construct neccecary html and loader preset states to load modules on a page.
2773 * Use getHtmlFromLoaderLinks() to convert this array to HTML.
2775 * @param array|string $modules One or more module names
2776 * @param string $only ResourceLoaderModule TYPE_ class constant
2777 * @param array $extraQuery [optional] Array with extra query parameters for the request
2778 * @return array A list of HTML strings and array of client loader preset states
2780 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
2781 $modules = (array)$modules;
2784 // List of html strings
2786 // Associative array of module names and their states
2790 if ( !count( $modules ) ) {
2794 if ( count( $modules ) > 1 ) {
2795 // Remove duplicate module requests
2796 $modules = array_unique( $modules );
2797 // Sort module names so requests are more uniform
2800 if ( ResourceLoader
::inDebugMode() ) {
2801 // Recursively call us for every item
2802 foreach ( $modules as $name ) {
2803 $link = $this->makeResourceLoaderLink( $name, $only, $extraQuery );
2804 $links['html'] = array_merge( $links['html'], $link['html'] );
2805 $links['states'] +
= $link['states'];
2811 if ( !is_null( $this->mTarget
) ) {
2812 $extraQuery['target'] = $this->mTarget
;
2815 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
2816 $sortedModules = [];
2817 $resourceLoader = $this->getResourceLoader();
2818 foreach ( $modules as $name ) {
2819 $module = $resourceLoader->getModule( $name );
2820 # Check that we're allowed to include this module on this page
2822 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_SCRIPTS
)
2823 && $only == ResourceLoaderModule
::TYPE_SCRIPTS
)
2824 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_STYLES
)
2825 && $only == ResourceLoaderModule
::TYPE_STYLES
)
2826 ||
( $module->getOrigin() > $this->getAllowedModules( ResourceLoaderModule
::TYPE_COMBINED
)
2827 && $only == ResourceLoaderModule
::TYPE_COMBINED
)
2828 ||
( $this->mTarget
&& !in_array( $this->mTarget
, $module->getTargets() ) )
2833 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
2836 foreach ( $sortedModules as $source => $groups ) {
2837 foreach ( $groups as $group => $grpModules ) {
2838 // Special handling for user-specific groups
2840 if ( ( $group === 'user' ||
$group === 'private' ) && $this->getUser()->isLoggedIn() ) {
2841 $user = $this->getUser()->getName();
2844 // Create a fake request based on the one we are about to make so modules return
2845 // correct timestamp and emptiness data
2846 $query = ResourceLoader
::makeLoaderQuery(
2847 [], // modules; not determined yet
2848 $this->getLanguage()->getCode(),
2849 $this->getSkin()->getSkinName(),
2851 null, // version; not determined yet
2852 ResourceLoader
::inDebugMode(),
2853 $only === ResourceLoaderModule
::TYPE_COMBINED ?
null : $only,
2854 $this->isPrintable(),
2855 $this->getRequest()->getBool( 'handheld' ),
2858 $context = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2860 // Extract modules that know they're empty and see if we have one or more
2863 foreach ( $grpModules as $key => $module ) {
2864 // Inline empty modules: since they're empty, just mark them as 'ready' (bug 46857)
2865 // If we're only getting the styles, we don't need to do anything for empty modules.
2866 if ( $module->isKnownEmpty( $context ) ) {
2867 unset( $grpModules[$key] );
2868 if ( $only !== ResourceLoaderModule
::TYPE_STYLES
) {
2869 $links['states'][$key] = 'ready';
2873 $isRaw |
= $module->isRaw();
2876 // If there are no non-empty modules, skip this group
2877 if ( count( $grpModules ) === 0 ) {
2881 // Inline private modules. These can't be loaded through load.php for security
2882 // reasons, see bug 34907. Note that these modules should be loaded from
2883 // getExternalHeadScripts() before the first loader call. Otherwise other modules can't
2884 // properly use them as dependencies (bug 30914)
2885 if ( $group === 'private' ) {
2886 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
2887 $links['html'][] = Html
::inlineStyle(
2888 $resourceLoader->makeModuleResponse( $context, $grpModules )
2891 $links['html'][] = ResourceLoader
::makeInlineScript(
2892 $resourceLoader->makeModuleResponse( $context, $grpModules )
2898 // Special handling for the user group; because users might change their stuff
2899 // on-wiki like user pages, or user preferences; we need to find the highest
2900 // timestamp of these user-changeable modules so we can ensure cache misses on change
2901 // This should NOT be done for the site group (bug 27564) because anons get that too
2902 // and we shouldn't be putting timestamps in CDN-cached HTML
2904 if ( $group === 'user' ) {
2905 $query['version'] = $resourceLoader->getCombinedVersion( $context, array_keys( $grpModules ) );
2908 $query['modules'] = ResourceLoader
::makePackedModulesString( array_keys( $grpModules ) );
2909 $moduleContext = new ResourceLoaderContext( $resourceLoader, new FauxRequest( $query ) );
2910 $url = $resourceLoader->createLoaderURL( $source, $moduleContext, $extraQuery );
2912 // Automatically select style/script elements
2913 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
2914 $link = Html
::linkedStyle( $url );
2916 if ( $context->getRaw() ||
$isRaw ) {
2917 // Startup module can't load itself, needs to use <script> instead of mw.loader.load
2918 $link = Html
::element( 'script', [
2919 // In SpecialJavaScriptTest, QUnit must load synchronous
2920 'async' => !isset( $extraQuery['sync'] ),
2924 $link = ResourceLoader
::makeInlineScript(
2925 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] )
2929 // For modules requested directly in the html via <script> or mw.loader.load
2930 // tell mw.loader they are being loading to prevent duplicate requests.
2931 foreach ( $grpModules as $key => $module ) {
2932 // Don't output state=loading for the startup module.
2933 if ( $key !== 'startup' ) {
2934 $links['states'][$key] = 'loading';
2939 if ( $group == 'noscript' ) {
2940 $links['html'][] = Html
::rawElement( 'noscript', [], $link );
2942 $links['html'][] = $link;
2951 * Build html output from an array of links from makeResourceLoaderLink.
2952 * @param array $links
2953 * @return string HTML
2955 protected static function getHtmlFromLoaderLinks( array $links ) {
2958 foreach ( $links as $link ) {
2959 if ( !is_array( $link ) ) {
2962 $html = array_merge( $html, $link['html'] );
2963 $states +
= $link['states'];
2966 // Filter out empty values
2967 $html = array_filter( $html, 'strlen' );
2969 if ( count( $states ) ) {
2970 array_unshift( $html, ResourceLoader
::makeInlineScript(
2971 ResourceLoader
::makeLoaderStateScript( $states )
2975 return WrappedString
::join( "\n", $html );
2979 * JS stuff to put in the "<head>". This is the startup module, config
2980 * vars and modules marked with position 'top'
2982 * @return string HTML fragment
2984 function getHeadScripts() {
2985 return $this->getInlineHeadScripts() . "\n" . $this->getExternalHeadScripts();
2989 * <script src="..."> tags for "<head>". This is the startup module
2990 * and other modules marked with position 'top'.
2992 * @return string HTML fragment
2994 function getExternalHeadScripts() {
2997 // Startup - this provides the client with the module
2998 // manifest and loads jquery and mediawiki base modules
2999 $links[] = $this->makeResourceLoaderLink( 'startup', ResourceLoaderModule
::TYPE_SCRIPTS
);
3001 return self
::getHtmlFromLoaderLinks( $links );
3005 * <script>...</script> tags to put in "<head>".
3007 * @return string HTML fragment
3009 function getInlineHeadScripts() {
3012 // Client profile classes for <html>. Allows for easy hiding/showing of UI components.
3013 // Must be done synchronously on every page to avoid flashes of wrong content.
3014 // Note: This class distinguishes MediaWiki-supported JavaScript from the rest.
3015 // The "rest" includes browsers that support JavaScript but not supported by our runtime.
3016 // For the performance benefit of the majority, this is added unconditionally here and is
3017 // then fixed up by the startup module for unsupported browsers.
3018 $links[] = Html
::inlineScript(
3019 'document.documentElement.className = document.documentElement.className'
3020 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
3023 // Load config before anything else
3024 $links[] = ResourceLoader
::makeInlineScript(
3025 ResourceLoader
::makeConfigSetScript( $this->getJSVars() )
3028 // Load embeddable private modules before any loader links
3029 // This needs to be TYPE_COMBINED so these modules are properly wrapped
3030 // in mw.loader.implement() calls and deferred until mw.user is available
3031 $embedScripts = [ 'user.options' ];
3032 $links[] = $this->makeResourceLoaderLink(
3034 ResourceLoaderModule
::TYPE_COMBINED
3036 // Separate user.tokens as otherwise caching will be allowed (T84960)
3037 $links[] = $this->makeResourceLoaderLink(
3039 ResourceLoaderModule
::TYPE_COMBINED
3042 // Modules requests - let the client calculate dependencies and batch requests as it likes
3043 // Only load modules that have marked themselves for loading at the top
3044 $modules = $this->getModules( true, 'top' );
3046 $links[] = ResourceLoader
::makeInlineScript(
3047 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3051 // "Scripts only" modules marked for top inclusion
3052 $links[] = $this->makeResourceLoaderLink(
3053 $this->getModuleScripts( true, 'top' ),
3054 ResourceLoaderModule
::TYPE_SCRIPTS
3057 return self
::getHtmlFromLoaderLinks( $links );
3061 * JS stuff to put at the 'bottom', which goes at the bottom of the `<body>`.
3062 * These are modules marked with position 'bottom', legacy scripts ($this->mScripts),
3063 * site JS, and user JS.
3065 * @param bool $unused Previously used to let this method change its output based
3066 * on whether it was called by getExternalHeadScripts() or getBottomScripts().
3069 function getScriptsForBottomQueue( $unused = null ) {
3070 // Scripts "only" requests marked for bottom inclusion
3071 // If we're in the <head>, use load() calls rather than <script src="..."> tags
3074 $links[] = $this->makeResourceLoaderLink( $this->getModuleScripts( true, 'bottom' ),
3075 ResourceLoaderModule
::TYPE_SCRIPTS
3078 // Modules requests - let the client calculate dependencies and batch requests as it likes
3079 // Only load modules that have marked themselves for loading at the bottom
3080 $modules = $this->getModules( true, 'bottom' );
3082 $links[] = ResourceLoader
::makeInlineScript(
3083 Xml
::encodeJsCall( 'mw.loader.load', [ $modules ] )
3088 $links[] = $this->mScripts
;
3090 // Add user JS if enabled
3091 // This must use TYPE_COMBINED instead of only=scripts so that its request is handled by
3092 // mw.loader.implement() which ensures that execution is scheduled after the "site" module.
3093 if ( $this->getConfig()->get( 'AllowUserJs' )
3094 && $this->getUser()->isLoggedIn()
3095 && $this->getTitle()
3096 && $this->getTitle()->isJsSubpage()
3097 && $this->userCanPreview()
3099 // We're on a preview of a JS subpage. Exclude this page from the user module (T28283)
3100 // and include the draft contents as a raw script instead.
3101 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
,
3102 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3104 // Load the previewed JS
3105 $links[] = ResourceLoader
::makeInlineScript(
3106 Xml
::encodeJsCall( 'mw.loader.using', [
3110 . Xml
::encodeJsCall( '$.globalEval', [
3111 $this->getRequest()->getText( 'wpTextbox1' )
3118 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3119 // asynchronously and may arrive *after* the inline script here. So the previewed code
3120 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3121 // Similarly, when previewing ./common.js and the user module does arrive first,
3122 // it will arrive without common.js and the inline script runs after.
3123 // Thus running common after the excluded subpage.
3125 // Include the user module normally, i.e., raw to avoid it being wrapped in a closure.
3126 $links[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_COMBINED
);
3129 // Group JS is only enabled if site JS is enabled.
3130 $links[] = $this->makeResourceLoaderLink(
3132 ResourceLoaderModule
::TYPE_COMBINED
3135 return self
::getHtmlFromLoaderLinks( $links );
3139 * JS stuff to put at the bottom of the "<body>"
3142 function getBottomScripts() {
3143 return $this->getScriptsForBottomQueue();
3147 * Get the javascript config vars to include on this page
3149 * @return array Array of javascript config vars
3152 public function getJsConfigVars() {
3153 return $this->mJsConfigVars
;
3157 * Add one or more variables to be set in mw.config in JavaScript
3159 * @param string|array $keys Key or array of key/value pairs
3160 * @param mixed $value [optional] Value of the configuration variable
3162 public function addJsConfigVars( $keys, $value = null ) {
3163 if ( is_array( $keys ) ) {
3164 foreach ( $keys as $key => $value ) {
3165 $this->mJsConfigVars
[$key] = $value;
3170 $this->mJsConfigVars
[$keys] = $value;
3174 * Get an array containing the variables to be set in mw.config in JavaScript.
3176 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3177 * - in other words, page-independent/site-wide variables (without state).
3178 * You will only be adding bloat to the html page and causing page caches to
3179 * have to be purged on configuration changes.
3182 public function getJSVars() {
3187 $canonicalSpecialPageName = false; # bug 21115
3189 $title = $this->getTitle();
3190 $ns = $title->getNamespace();
3191 $canonicalNamespace = MWNamespace
::exists( $ns )
3192 ? MWNamespace
::getCanonicalName( $ns )
3193 : $title->getNsText();
3195 $sk = $this->getSkin();
3196 // Get the relevant title so that AJAX features can use the correct page name
3197 // when making API requests from certain special pages (bug 34972).
3198 $relevantTitle = $sk->getRelevantTitle();
3199 $relevantUser = $sk->getRelevantUser();
3201 if ( $ns == NS_SPECIAL
) {
3202 list( $canonicalSpecialPageName, /*...*/ ) =
3203 SpecialPageFactory
::resolveAlias( $title->getDBkey() );
3204 } elseif ( $this->canUseWikiPage() ) {
3205 $wikiPage = $this->getWikiPage();
3206 $curRevisionId = $wikiPage->getLatest();
3207 $articleId = $wikiPage->getId();
3210 $lang = $title->getPageLanguage();
3212 // Pre-process information
3213 $separatorTransTable = $lang->separatorTransformTable();
3214 $separatorTransTable = $separatorTransTable ?
$separatorTransTable : [];
3215 $compactSeparatorTransTable = [
3216 implode( "\t", array_keys( $separatorTransTable ) ),
3217 implode( "\t", $separatorTransTable ),
3219 $digitTransTable = $lang->digitTransformTable();
3220 $digitTransTable = $digitTransTable ?
$digitTransTable : [];
3221 $compactDigitTransTable = [
3222 implode( "\t", array_keys( $digitTransTable ) ),
3223 implode( "\t", $digitTransTable ),
3226 $user = $this->getUser();
3229 'wgCanonicalNamespace' => $canonicalNamespace,
3230 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3231 'wgNamespaceNumber' => $title->getNamespace(),
3232 'wgPageName' => $title->getPrefixedDBkey(),
3233 'wgTitle' => $title->getText(),
3234 'wgCurRevisionId' => $curRevisionId,
3235 'wgRevisionId' => (int)$this->getRevisionId(),
3236 'wgArticleId' => $articleId,
3237 'wgIsArticle' => $this->isArticle(),
3238 'wgIsRedirect' => $title->isRedirect(),
3239 'wgAction' => Action
::getActionName( $this->getContext() ),
3240 'wgUserName' => $user->isAnon() ?
null : $user->getName(),
3241 'wgUserGroups' => $user->getEffectiveGroups(),
3242 'wgCategories' => $this->getCategories(),
3243 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3244 'wgPageContentLanguage' => $lang->getCode(),
3245 'wgPageContentModel' => $title->getContentModel(),
3246 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3247 'wgDigitTransformTable' => $compactDigitTransTable,
3248 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3249 'wgMonthNames' => $lang->getMonthNamesArray(),
3250 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3251 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3252 'wgRelevantArticleId' => $relevantTitle->getArticleId(),
3255 if ( $user->isLoggedIn() ) {
3256 $vars['wgUserId'] = $user->getId();
3257 $vars['wgUserEditCount'] = $user->getEditCount();
3258 $userReg = wfTimestampOrNull( TS_UNIX
, $user->getRegistration() );
3259 $vars['wgUserRegistration'] = $userReg !== null ?
( $userReg * 1000 ) : null;
3260 // Get the revision ID of the oldest new message on the user's talk
3261 // page. This can be used for constructing new message alerts on
3263 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3266 if ( $wgContLang->hasVariants() ) {
3267 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3269 // Same test as SkinTemplate
3270 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3271 && ( $title->exists() ||
$title->quickUserCan( 'create', $user ) );
3273 foreach ( $title->getRestrictionTypes() as $type ) {
3274 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3277 if ( $title->isMainPage() ) {
3278 $vars['wgIsMainPage'] = true;
3281 if ( $this->mRedirectedFrom
) {
3282 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom
->getPrefixedDBkey();
3285 if ( $relevantUser ) {
3286 $vars['wgRelevantUserName'] = $relevantUser->getName();
3289 // Allow extensions to add their custom variables to the mw.config map.
3290 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3291 // page-dependant but site-wide (without state).
3292 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3293 Hooks
::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3295 // Merge in variables from addJsConfigVars last
3296 return array_merge( $vars, $this->getJsConfigVars() );
3300 * To make it harder for someone to slip a user a fake
3301 * user-JavaScript or user-CSS preview, a random token
3302 * is associated with the login session. If it's not
3303 * passed back with the preview request, we won't render
3308 public function userCanPreview() {
3309 $request = $this->getRequest();
3311 $request->getVal( 'action' ) !== 'submit' ||
3312 !$request->getCheck( 'wpPreview' ) ||
3313 !$request->wasPosted()
3318 $user = $this->getUser();
3319 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3323 $title = $this->getTitle();
3324 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3327 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3328 // Don't execute another user's CSS or JS on preview (T85855)
3332 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3333 if ( count( $errors ) !== 0 ) {
3341 * @return array Array in format "link name or number => 'link html'".
3343 public function getHeadLinksArray() {
3347 $config = $this->getConfig();
3349 $canonicalUrl = $this->mCanonicalUrl
;
3351 $tags['meta-generator'] = Html
::element( 'meta', [
3352 'name' => 'generator',
3353 'content' => "MediaWiki $wgVersion",
3356 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3357 $tags['meta-referrer'] = Html
::element( 'meta', [
3358 'name' => 'referrer',
3359 'content' => $config->get( 'ReferrerPolicy' )
3363 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3364 if ( $p !== 'index,follow' ) {
3365 // http://www.robotstxt.org/wc/meta-user.html
3366 // Only show if it's different from the default robots policy
3367 $tags['meta-robots'] = Html
::element( 'meta', [
3373 foreach ( $this->mMetatags
as $tag ) {
3374 if ( 0 == strcasecmp( 'http:', substr( $tag[0], 0, 5 ) ) ) {
3376 $tag[0] = substr( $tag[0], 5 );
3380 $tagName = "meta-{$tag[0]}";
3381 if ( isset( $tags[$tagName] ) ) {
3382 $tagName .= $tag[1];
3384 $tags[$tagName] = Html
::element( 'meta',
3387 'content' => $tag[1]
3392 foreach ( $this->mLinktags
as $tag ) {
3393 $tags[] = Html
::element( 'link', $tag );
3396 # Universal edit button
3397 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3398 $user = $this->getUser();
3399 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3400 && ( $this->getTitle()->exists() ||
3401 $this->getTitle()->quickUserCan( 'create', $user ) )
3403 // Original UniversalEditButton
3404 $msg = $this->msg( 'edit' )->text();
3405 $tags['universal-edit-button'] = Html
::element( 'link', [
3406 'rel' => 'alternate',
3407 'type' => 'application/x-wiki',
3409 'href' => $this->getTitle()->getEditURL(),
3411 // Alternate edit link
3412 $tags['alternative-edit'] = Html
::element( 'link', [
3415 'href' => $this->getTitle()->getEditURL(),
3420 # Generally the order of the favicon and apple-touch-icon links
3421 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3422 # uses whichever one appears later in the HTML source. Make sure
3423 # apple-touch-icon is specified first to avoid this.
3424 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3425 $tags['apple-touch-icon'] = Html
::element( 'link', [
3426 'rel' => 'apple-touch-icon',
3427 'href' => $config->get( 'AppleTouchIcon' )
3431 if ( $config->get( 'Favicon' ) !== false ) {
3432 $tags['favicon'] = Html
::element( 'link', [
3433 'rel' => 'shortcut icon',
3434 'href' => $config->get( 'Favicon' )
3438 # OpenSearch description link
3439 $tags['opensearch'] = Html
::element( 'link', [
3441 'type' => 'application/opensearchdescription+xml',
3442 'href' => wfScript( 'opensearch_desc' ),
3443 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3446 if ( $config->get( 'EnableAPI' ) ) {
3447 # Real Simple Discovery link, provides auto-discovery information
3448 # for the MediaWiki API (and potentially additional custom API
3449 # support such as WordPress or Twitter-compatible APIs for a
3450 # blogging extension, etc)
3451 $tags['rsd'] = Html
::element( 'link', [
3453 'type' => 'application/rsd+xml',
3454 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3455 // Whether RSD accepts relative or protocol-relative URLs is completely
3456 // undocumented, though.
3457 'href' => wfExpandUrl( wfAppendQuery(
3459 [ 'action' => 'rsd' ] ),
3466 if ( !$config->get( 'DisableLangConversion' ) ) {
3467 $lang = $this->getTitle()->getPageLanguage();
3468 if ( $lang->hasVariants() ) {
3469 $variants = $lang->getVariants();
3470 foreach ( $variants as $variant ) {
3471 $tags["variant-$variant"] = Html
::element( 'link', [
3472 'rel' => 'alternate',
3473 'hreflang' => wfBCP47( $variant ),
3474 'href' => $this->getTitle()->getLocalURL(
3475 [ 'variant' => $variant ] )
3479 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3480 $tags["variant-x-default"] = Html
::element( 'link', [
3481 'rel' => 'alternate',
3482 'hreflang' => 'x-default',
3483 'href' => $this->getTitle()->getLocalURL() ] );
3488 if ( $this->copyrightUrl
!== null ) {
3489 $copyright = $this->copyrightUrl
;
3492 if ( $config->get( 'RightsPage' ) ) {
3493 $copy = Title
::newFromText( $config->get( 'RightsPage' ) );
3496 $copyright = $copy->getLocalURL();
3500 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3501 $copyright = $config->get( 'RightsUrl' );
3506 $tags['copyright'] = Html
::element( 'link', [
3507 'rel' => 'copyright',
3508 'href' => $copyright ]
3513 if ( $config->get( 'Feed' ) ) {
3516 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3517 # Use the page name for the title. In principle, this could
3518 # lead to issues with having the same name for different feeds
3519 # corresponding to the same page, but we can't avoid that at
3522 $feedLinks[] = $this->feedLink(
3525 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3527 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3532 # Recent changes feed should appear on every page (except recentchanges,
3533 # that would be redundant). Put it after the per-page feed to avoid
3534 # changing existing behavior. It's still available, probably via a
3535 # menu in your browser. Some sites might have a different feed they'd
3536 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3537 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3538 # If so, use it instead.
3539 $sitename = $config->get( 'Sitename' );
3540 if ( $config->get( 'OverrideSiteFeed' ) ) {
3541 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3542 // Note, this->feedLink escapes the url.
3543 $feedLinks[] = $this->feedLink(
3546 $this->msg( "site-{$type}-feed", $sitename )->text()
3549 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3550 $rctitle = SpecialPage
::getTitleFor( 'Recentchanges' );
3551 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3552 $feedLinks[] = $this->feedLink(
3554 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3555 # For grep: 'site-rss-feed', 'site-atom-feed'
3556 $this->msg( "site-{$format}-feed", $sitename )->text()
3561 # Allow extensions to change the list pf feeds. This hook is primarily for changing,
3562 # manipulating or removing existing feed tags. If you want to add new feeds, you should
3563 # use OutputPage::addFeedLink() instead.
3564 Hooks
::run( 'AfterBuildFeedLinks', [ &$feedLinks ] );
3566 $tags +
= $feedLinks;
3570 if ( $config->get( 'EnableCanonicalServerLink' ) ) {
3571 if ( $canonicalUrl !== false ) {
3572 $canonicalUrl = wfExpandUrl( $canonicalUrl, PROTO_CANONICAL
);
3574 if ( $this->isArticleRelated() ) {
3575 // This affects all requests where "setArticleRelated" is true. This is
3576 // typically all requests that show content (query title, curid, oldid, diff),
3577 // and all wikipage actions (edit, delete, purge, info, history etc.).
3578 // It does not apply to File pages and Special pages.
3579 // 'history' and 'info' actions address page metadata rather than the page
3580 // content itself, so they may not be canonicalized to the view page url.
3581 // TODO: this ought to be better encapsulated in the Action class.
3582 $action = Action
::getActionName( $this->getContext() );
3583 if ( in_array( $action, [ 'history', 'info' ] ) ) {
3584 $query = "action={$action}";
3588 $canonicalUrl = $this->getTitle()->getCanonicalURL( $query );
3590 $reqUrl = $this->getRequest()->getRequestURL();
3591 $canonicalUrl = wfExpandUrl( $reqUrl, PROTO_CANONICAL
);
3595 if ( $canonicalUrl !== false ) {
3596 $tags[] = Html
::element( 'link', [
3597 'rel' => 'canonical',
3598 'href' => $canonicalUrl
3606 * @return string HTML tag links to be put in the header.
3607 * @deprecated since 1.24 Use OutputPage::headElement or if you have to,
3608 * OutputPage::getHeadLinksArray directly.
3610 public function getHeadLinks() {
3611 wfDeprecated( __METHOD__
, '1.24' );
3612 return implode( "\n", $this->getHeadLinksArray() );
3616 * Generate a "<link rel/>" for a feed.
3618 * @param string $type Feed type
3619 * @param string $url URL to the feed
3620 * @param string $text Value of the "title" attribute
3621 * @return string HTML fragment
3623 private function feedLink( $type, $url, $text ) {
3624 return Html
::element( 'link', [
3625 'rel' => 'alternate',
3626 'type' => "application/$type+xml",
3633 * Add a local or specified stylesheet, with the given media options.
3634 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3636 * @param string $style URL to the file
3637 * @param string $media To specify a media type, 'screen', 'printable', 'handheld' or any.
3638 * @param string $condition For IE conditional comments, specifying an IE version
3639 * @param string $dir Set to 'rtl' or 'ltr' for direction-specific sheets
3641 public function addStyle( $style, $media = '', $condition = '', $dir = '' ) {
3644 $options['media'] = $media;
3647 $options['condition'] = $condition;
3650 $options['dir'] = $dir;
3652 $this->styles
[$style] = $options;
3656 * Adds inline CSS styles
3657 * Internal use only. Use OutputPage::addModuleStyles() if possible.
3659 * @param mixed $style_css Inline CSS
3660 * @param string $flip Set to 'flip' to flip the CSS if needed
3662 public function addInlineStyle( $style_css, $flip = 'noflip' ) {
3663 if ( $flip === 'flip' && $this->getLanguage()->isRTL() ) {
3664 # If wanted, and the interface is right-to-left, flip the CSS
3665 $style_css = CSSJanus
::transform( $style_css, true, false );
3667 $this->mInlineStyles
.= Html
::inlineStyle( $style_css ) . "\n";
3671 * Build a set of "<link>" elements for the stylesheets specified in the $this->styles array.
3672 * These will be applied to various media & IE conditionals.
3676 public function buildCssLinks() {
3679 $this->getSkin()->setupSkinUserCss( $this );
3681 // Add ResourceLoader styles
3682 // Split the styles into these groups
3691 $otherTags = []; // Tags to append after the normal <link> tags
3692 $resourceLoader = $this->getResourceLoader();
3694 $moduleStyles = $this->getModuleStyles();
3696 // Per-site custom styles
3697 $moduleStyles[] = 'site';
3698 $moduleStyles[] = 'noscript';
3699 $moduleStyles[] = 'user.groups';
3701 // Per-user custom styles
3702 if ( $this->getConfig()->get( 'AllowUserCss' ) && $this->getTitle()->isCssSubpage()
3703 && $this->userCanPreview()
3705 // We're on a preview of a CSS subpage
3706 // Exclude this page from the user module in case it's in there (bug 26283)
3707 $link = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule
::TYPE_STYLES
,
3708 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3710 $otherTags = array_merge( $otherTags, $link['html'] );
3712 // Load the previewed CSS
3713 // If needed, Janus it first. This is user-supplied CSS, so it's
3714 // assumed to be right for the content language directionality.
3715 $previewedCSS = $this->getRequest()->getText( 'wpTextbox1' );
3716 if ( $this->getLanguage()->getDir() !== $wgContLang->getDir() ) {
3717 $previewedCSS = CSSJanus
::transform( $previewedCSS, true, false );
3719 $otherTags[] = Html
::inlineStyle( $previewedCSS ) . "\n";
3721 // Load the user styles normally
3722 $moduleStyles[] = 'user';
3725 // Per-user preference styles
3726 $moduleStyles[] = 'user.cssprefs';
3728 foreach ( $moduleStyles as $name ) {
3729 $module = $resourceLoader->getModule( $name );
3733 if ( $name === 'site' ) {
3734 // HACK: The site module shouldn't be fragmented with a cache group and
3735 // http request. But in order to ensure its styles are separated and after the
3736 // ResourceLoaderDynamicStyles marker, pretend it is in a group called 'site'.
3737 // The scripts remain ungrouped and rides the bottom queue.
3738 $styles['site'][] = $name;
3741 $group = $module->getGroup();
3742 // Modules in groups other than the ones needing special treatment
3743 // (see $styles assignment)
3744 // will be placed in the "other" style category.
3745 $styles[isset( $styles[$group] ) ?
$group : 'other'][] = $name;
3748 // We want site, private and user styles to override dynamically added
3749 // styles from modules, but we want dynamically added styles to override
3750 // statically added styles from other modules. So the order has to be
3751 // other, dynamic, site, private, user. Add statically added styles for
3753 $links[] = $this->makeResourceLoaderLink(
3755 ResourceLoaderModule
::TYPE_STYLES
3757 // Add normal styles added through addStyle()/addInlineStyle() here
3758 $links[] = implode( "\n", $this->buildCssLinksArray() ) . $this->mInlineStyles
;
3759 // Add marker tag to mark the place where the client-side
3760 // loader should inject dynamic styles
3761 // We use a <meta> tag with a made-up name for this because that's valid HTML
3762 $links[] = Html
::element(
3764 [ 'name' => 'ResourceLoaderDynamicStyles', 'content' => '' ]
3767 // Add site-specific and user-specific styles
3768 // 'private' at present only contains user.options, so put that before 'user'
3769 // Any future private modules will likely have a similar user-specific character
3770 foreach ( [ 'site', 'noscript', 'private', 'user' ] as $group ) {
3771 $links[] = $this->makeResourceLoaderLink( $styles[$group],
3772 ResourceLoaderModule
::TYPE_STYLES
3776 // Add stuff in $otherTags (previewed user CSS if applicable)
3777 return self
::getHtmlFromLoaderLinks( $links ) . implode( '', $otherTags );
3783 public function buildCssLinksArray() {
3786 // Add any extension CSS
3787 foreach ( $this->mExtStyles
as $url ) {
3788 $this->addStyle( $url );
3790 $this->mExtStyles
= [];
3792 foreach ( $this->styles
as $file => $options ) {
3793 $link = $this->styleLink( $file, $options );
3795 $links[$file] = $link;
3802 * Generate \<link\> tags for stylesheets
3804 * @param string $style URL to the file
3805 * @param array $options Option, can contain 'condition', 'dir', 'media' keys
3806 * @return string HTML fragment
3808 protected function styleLink( $style, array $options ) {
3809 if ( isset( $options['dir'] ) ) {
3810 if ( $this->getLanguage()->getDir() != $options['dir'] ) {
3815 if ( isset( $options['media'] ) ) {
3816 $media = self
::transformCssMedia( $options['media'] );
3817 if ( is_null( $media ) ) {
3824 if ( substr( $style, 0, 1 ) == '/' ||
3825 substr( $style, 0, 5 ) == 'http:' ||
3826 substr( $style, 0, 6 ) == 'https:' ) {
3829 $config = $this->getConfig();
3830 $url = $config->get( 'StylePath' ) . '/' . $style . '?' .
3831 $config->get( 'StyleVersion' );
3834 $link = Html
::linkedStyle( $url, $media );
3836 if ( isset( $options['condition'] ) ) {
3837 $condition = htmlspecialchars( $options['condition'] );
3838 $link = "<!--[if $condition]>$link<![endif]-->";
3844 * Transform path to web-accessible static resource.
3846 * This is used to add a validation hash as query string.
3847 * This aids various behaviors:
3849 * - Put long Cache-Control max-age headers on responses for improved
3850 * cache performance.
3851 * - Get the correct version of a file as expected by the current page.
3852 * - Instantly get the updated version of a file after deployment.
3854 * Avoid using this for urls included in HTML as otherwise clients may get different
3855 * versions of a resource when navigating the site depending on when the page was cached.
3856 * If changes to the url propagate, this is not a problem (e.g. if the url is in
3857 * an external stylesheet).
3860 * @param Config $config
3861 * @param string $path Path-absolute URL to file (from document root, must start with "/")
3862 * @return string URL
3864 public static function transformResourcePath( Config
$config, $path ) {
3866 $remotePathPrefix = $config->get( 'ResourceBasePath' );
3867 if ( $remotePathPrefix === '' ) {
3868 // The configured base path is required to be empty string for
3869 // wikis in the domain root
3872 $remotePath = $remotePathPrefix;
3874 if ( strpos( $path, $remotePath ) !== 0 ) {
3875 // Path is outside wgResourceBasePath, ignore.
3878 $path = RelPath\
getRelativePath( $path, $remotePath );
3879 return self
::transformFilePath( $remotePathPrefix, $IP, $path );
3883 * Utility method for transformResourceFilePath().
3885 * Caller is responsible for ensuring the file exists. Emits a PHP warning otherwise.
3888 * @param string $remotePath URL path prefix that points to $localPath
3889 * @param string $localPath File directory exposed at $remotePath
3890 * @param string $file Path to target file relative to $localPath
3891 * @return string URL
3893 public static function transformFilePath( $remotePathPrefix, $localPath, $file ) {
3894 $hash = md5_file( "$localPath/$file" );
3895 if ( $hash === false ) {
3896 wfLogWarning( __METHOD__
. ": Failed to hash $localPath/$file" );
3899 return "$remotePathPrefix/$file?" . substr( $hash, 0, 5 );
3903 * Transform "media" attribute based on request parameters
3905 * @param string $media Current value of the "media" attribute
3906 * @return string Modified value of the "media" attribute, or null to skip
3909 public static function transformCssMedia( $media ) {
3912 // http://www.w3.org/TR/css3-mediaqueries/#syntax
3913 $screenMediaQueryRegex = '/^(?:only\s+)?screen\b/i';
3915 // Switch in on-screen display for media testing
3917 'printable' => 'print',
3918 'handheld' => 'handheld',
3920 foreach ( $switches as $switch => $targetMedia ) {
3921 if ( $wgRequest->getBool( $switch ) ) {
3922 if ( $media == $targetMedia ) {
3924 } elseif ( preg_match( $screenMediaQueryRegex, $media ) === 1 ) {
3925 /* This regex will not attempt to understand a comma-separated media_query_list
3927 * Example supported values for $media:
3928 * 'screen', 'only screen', 'screen and (min-width: 982px)' ),
3929 * Example NOT supported value for $media:
3930 * '3d-glasses, screen, print and resolution > 90dpi'
3932 * If it's a print request, we never want any kind of screen stylesheets
3933 * If it's a handheld request (currently the only other choice with a switch),
3934 * we don't want simple 'screen' but we might want screen queries that
3935 * have a max-width or something, so we'll pass all others on and let the
3936 * client do the query.
3938 if ( $targetMedia == 'print' ||
$media == 'screen' ) {
3949 * Add a wikitext-formatted message to the output.
3950 * This is equivalent to:
3952 * $wgOut->addWikiText( wfMessage( ... )->plain() )
3954 public function addWikiMsg( /*...*/ ) {
3955 $args = func_get_args();
3956 $name = array_shift( $args );
3957 $this->addWikiMsgArray( $name, $args );
3961 * Add a wikitext-formatted message to the output.
3962 * Like addWikiMsg() except the parameters are taken as an array
3963 * instead of a variable argument list.
3965 * @param string $name
3966 * @param array $args
3968 public function addWikiMsgArray( $name, $args ) {
3969 $this->addHTML( $this->msg( $name, $args )->parseAsBlock() );
3973 * This function takes a number of message/argument specifications, wraps them in
3974 * some overall structure, and then parses the result and adds it to the output.
3976 * In the $wrap, $1 is replaced with the first message, $2 with the second,
3977 * and so on. The subsequent arguments may be either
3978 * 1) strings, in which case they are message names, or
3979 * 2) arrays, in which case, within each array, the first element is the message
3980 * name, and subsequent elements are the parameters to that message.
3982 * Don't use this for messages that are not in the user's interface language.
3986 * $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>", 'some-error' );
3990 * $wgOut->addWikiText( "<div class='error'>\n"
3991 * . wfMessage( 'some-error' )->plain() . "\n</div>" );
3993 * The newline after the opening div is needed in some wikitext. See bug 19226.
3995 * @param string $wrap
3997 public function wrapWikiMsg( $wrap /*, ...*/ ) {
3998 $msgSpecs = func_get_args();
3999 array_shift( $msgSpecs );
4000 $msgSpecs = array_values( $msgSpecs );
4002 foreach ( $msgSpecs as $n => $spec ) {
4003 if ( is_array( $spec ) ) {
4005 $name = array_shift( $args );
4006 if ( isset( $args['options'] ) ) {
4007 unset( $args['options'] );
4009 'Adding "options" to ' . __METHOD__
. ' is no longer supported',
4017 $s = str_replace( '$' . ( $n +
1 ), $this->msg( $name, $args )->plain(), $s );
4019 $this->addWikiText( $s );
4023 * Enables/disables TOC, doesn't override __NOTOC__
4027 public function enableTOC( $flag = true ) {
4028 $this->mEnableTOC
= $flag;
4035 public function isTOCEnabled() {
4036 return $this->mEnableTOC
;
4040 * Enables/disables section edit links, doesn't override __NOEDITSECTION__
4044 public function enableSectionEditLinks( $flag = true ) {
4045 $this->mEnableSectionEditLinks
= $flag;
4052 public function sectionEditLinksEnabled() {
4053 return $this->mEnableSectionEditLinks
;
4057 * Helper function to setup the PHP implementation of OOUI to use in this request.
4060 * @param String $skinName The Skin name to determine the correct OOUI theme
4061 * @param String $dir Language direction
4063 public static function setupOOUI( $skinName = '', $dir = 'ltr' ) {
4064 $themes = ExtensionRegistry
::getInstance()->getAttribute( 'SkinOOUIThemes' );
4065 // Make keys (skin names) lowercase for case-insensitive matching.
4066 $themes = array_change_key_case( $themes, CASE_LOWER
);
4067 $theme = isset( $themes[$skinName] ) ?
$themes[$skinName] : 'MediaWiki';
4068 // For example, 'OOUI\MediaWikiTheme'.
4069 $themeClass = "OOUI\\{$theme}Theme";
4070 OOUI\Theme
::setSingleton( new $themeClass() );
4071 OOUI\Element
::setDefaultDir( $dir );
4075 * Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with
4076 * MediaWiki and this OutputPage instance.
4080 public function enableOOUI() {
4082 strtolower( $this->getSkin()->getSkinName() ),
4083 $this->getLanguage()->getDir()
4085 $this->addModuleStyles( [
4086 'oojs-ui-core.styles',
4087 'oojs-ui.styles.icons',
4088 'oojs-ui.styles.indicators',
4089 'oojs-ui.styles.textures',
4090 'mediawiki.widgets.styles',
4092 // Used by 'skipFunction' of the four 'oojs-ui.styles.*' modules. Please don't treat this as a
4093 // public API or you'll be severely disappointed when T87871 is fixed and it disappears.
4094 $this->addMeta( 'X-OOUI-PHP', '1' );