Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / skins / Skin.php
blob96812ea23fd942be0b5cdf6c0d4636d5debde996
1 <?php
2 /**
3 * Base class for all skins.
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
20 * @file
23 /**
24 * @defgroup Skins Skins
27 /**
28 * The main skin class which provides methods and properties for all other skins.
30 * See docs/skin.txt for more information.
32 * @ingroup Skins
34 abstract class Skin extends ContextSource {
35 protected $skinname = null;
36 protected $mRelevantTitle = null;
37 protected $mRelevantUser = null;
39 /**
40 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
41 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
43 public $stylename = null;
45 /**
46 * Fetch the set of available skins.
47 * @return array Associative array of strings
49 static function getSkinNames() {
50 return SkinFactory::getDefaultInstance()->getSkinNames();
53 /**
54 * Fetch the skinname messages for available skins.
55 * @return string[]
57 static function getSkinNameMessages() {
58 $messages = [];
59 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
60 $messages[] = "skinname-$skinKey";
62 return $messages;
65 /**
66 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
67 * Useful for Special:Preferences and other places where you
68 * only want to show skins users _can_ use.
69 * @return string[]
70 * @since 1.23
72 public static function getAllowedSkins() {
73 global $wgSkipSkins;
75 $allowedSkins = self::getSkinNames();
77 foreach ( $wgSkipSkins as $skip ) {
78 unset( $allowedSkins[$skip] );
81 return $allowedSkins;
84 /**
85 * Normalize a skin preference value to a form that can be loaded.
87 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
88 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
90 * @param string $key 'monobook', 'vector', etc.
91 * @return string
93 static function normalizeKey( $key ) {
94 global $wgDefaultSkin, $wgFallbackSkin;
96 $skinNames = Skin::getSkinNames();
98 // Make keys lowercase for case-insensitive matching.
99 $skinNames = array_change_key_case( $skinNames, CASE_LOWER );
100 $key = strtolower( $key );
101 $defaultSkin = strtolower( $wgDefaultSkin );
102 $fallbackSkin = strtolower( $wgFallbackSkin );
104 if ( $key == '' || $key == 'default' ) {
105 // Don't return the default immediately;
106 // in a misconfiguration we need to fall back.
107 $key = $defaultSkin;
110 if ( isset( $skinNames[$key] ) ) {
111 return $key;
114 // Older versions of the software used a numeric setting
115 // in the user preferences.
116 $fallback = [
117 0 => $defaultSkin,
118 2 => 'cologneblue'
121 if ( isset( $fallback[$key] ) ) {
122 $key = $fallback[$key];
125 if ( isset( $skinNames[$key] ) ) {
126 return $key;
127 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
128 return $defaultSkin;
129 } else {
130 return $fallbackSkin;
135 * @return string Skin name
137 public function getSkinName() {
138 return $this->skinname;
142 * @param OutputPage $out
144 public function initPage( OutputPage $out ) {
145 $this->preloadExistence();
149 * Defines the ResourceLoader modules that should be added to the skin
150 * It is recommended that skins wishing to override call parent::getDefaultModules()
151 * and substitute out any modules they wish to change by using a key to look them up
152 * @return array Array of modules with helper keys for easy overriding
154 public function getDefaultModules() {
155 global $wgUseAjax, $wgEnableAPI, $wgEnableWriteAPI;
157 $out = $this->getOutput();
158 $user = $out->getUser();
159 $modules = [
160 // modules that enhance the page content in some way
161 'content' => [
162 'mediawiki.page.ready',
164 // modules that exist for legacy reasons
165 'legacy' => ResourceLoaderStartUpModule::getLegacyModules(),
166 // modules relating to search functionality
167 'search' => [],
168 // modules relating to functionality relating to watching an article
169 'watch' => [],
170 // modules which relate to the current users preferences
171 'user' => [],
174 // Add various resources if required
175 if ( $wgUseAjax && $wgEnableAPI ) {
176 if ( $wgEnableWriteAPI && $user->isLoggedIn()
177 && $user->isAllowedAll( 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
178 && $this->getRelevantTitle()->canExist()
180 $modules['watch'][] = 'mediawiki.page.watch.ajax';
183 $modules['search'][] = 'mediawiki.searchSuggest';
186 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
187 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
190 // Crazy edit-on-double-click stuff
191 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
192 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
194 return $modules;
198 * Preload the existence of three commonly-requested pages in a single query
200 protected function preloadExistence() {
201 $titles = [];
203 // User/talk link
204 $user = $this->getUser();
205 if ( $user->isLoggedIn() ) {
206 $titles[] = $user->getUserPage();
207 $titles[] = $user->getTalkPage();
210 // Check, if the page can hold some kind of content, otherwise do nothing
211 $title = $this->getRelevantTitle();
212 if ( $title->canExist() ) {
213 if ( $title->isTalkPage() ) {
214 $titles[] = $title->getSubjectPage();
215 } else {
216 $titles[] = $title->getTalkPage();
220 // Footer links (used by SkinTemplate::prepareQuickTemplate)
221 foreach ( [
222 $this->footerLinkTitle( 'privacy', 'privacypage' ),
223 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
224 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
225 ] as $title ) {
226 if ( $title ) {
227 $titles[] = $title;
231 Hooks::run( 'SkinPreloadExistence', [ &$titles, $this ] );
233 if ( $titles ) {
234 $lb = new LinkBatch( $titles );
235 $lb->setCaller( __METHOD__ );
236 $lb->execute();
241 * Get the current revision ID
243 * @return int
245 public function getRevisionId() {
246 return $this->getOutput()->getRevisionId();
250 * Whether the revision displayed is the latest revision of the page
252 * @return bool
254 public function isRevisionCurrent() {
255 $revID = $this->getRevisionId();
256 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
260 * Set the "relevant" title
261 * @see self::getRelevantTitle()
262 * @param Title $t
264 public function setRelevantTitle( $t ) {
265 $this->mRelevantTitle = $t;
269 * Return the "relevant" title.
270 * A "relevant" title is not necessarily the actual title of the page.
271 * Special pages like Special:MovePage use set the page they are acting on
272 * as their "relevant" title, this allows the skin system to display things
273 * such as content tabs which belong to to that page instead of displaying
274 * a basic special page tab which has almost no meaning.
276 * @return Title
278 public function getRelevantTitle() {
279 if ( isset( $this->mRelevantTitle ) ) {
280 return $this->mRelevantTitle;
282 return $this->getTitle();
286 * Set the "relevant" user
287 * @see self::getRelevantUser()
288 * @param User $u
290 public function setRelevantUser( $u ) {
291 $this->mRelevantUser = $u;
295 * Return the "relevant" user.
296 * A "relevant" user is similar to a relevant title. Special pages like
297 * Special:Contributions mark the user which they are relevant to so that
298 * things like the toolbox can display the information they usually are only
299 * able to display on a user's userpage and talkpage.
300 * @return User
302 public function getRelevantUser() {
303 if ( isset( $this->mRelevantUser ) ) {
304 return $this->mRelevantUser;
306 $title = $this->getRelevantTitle();
307 if ( $title->hasSubjectNamespace( NS_USER ) ) {
308 $rootUser = $title->getRootText();
309 if ( User::isIP( $rootUser ) ) {
310 $this->mRelevantUser = User::newFromName( $rootUser, false );
311 } else {
312 $user = User::newFromName( $rootUser, false );
314 if ( $user ) {
315 $user->load( User::READ_NORMAL );
317 if ( $user->isLoggedIn() ) {
318 $this->mRelevantUser = $user;
322 return $this->mRelevantUser;
324 return null;
328 * Outputs the HTML generated by other functions.
329 * @param OutputPage $out
331 abstract function outputPage( OutputPage $out = null );
334 * @param array $data
335 * @return string
337 static function makeVariablesScript( $data ) {
338 if ( $data ) {
339 return ResourceLoader::makeInlineScript(
340 ResourceLoader::makeConfigSetScript( $data )
342 } else {
343 return '';
348 * Get the query to generate a dynamic stylesheet
350 * @return array
352 public static function getDynamicStylesheetQuery() {
353 global $wgSquidMaxage;
355 return [
356 'action' => 'raw',
357 'maxage' => $wgSquidMaxage,
358 'usemsgcache' => 'yes',
359 'ctype' => 'text/css',
360 'smaxage' => $wgSquidMaxage,
365 * Add skin specific stylesheets
366 * Calling this method with an $out of anything but the same OutputPage
367 * inside ->getOutput() is deprecated. The $out arg is kept
368 * for compatibility purposes with skins.
369 * @param OutputPage $out
370 * @todo delete
372 abstract function setupSkinUserCss( OutputPage $out );
375 * TODO: document
376 * @param Title $title
377 * @return string
379 function getPageClasses( $title ) {
380 $numeric = 'ns-' . $title->getNamespace();
382 if ( $title->isSpecialPage() ) {
383 $type = 'ns-special';
384 // bug 23315: provide a class based on the canonical special page name without subpages
385 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
386 if ( $canonicalName ) {
387 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
388 } else {
389 $type .= ' mw-invalidspecialpage';
391 } elseif ( $title->isTalkPage() ) {
392 $type = 'ns-talk';
393 } else {
394 $type = 'ns-subject';
397 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
398 $root = Sanitizer::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
400 return "$numeric $type $name $root";
404 * Return values for <html> element
405 * @return array Array of associative name-to-value elements for <html> element
407 public function getHtmlElementAttributes() {
408 $lang = $this->getLanguage();
409 return [
410 'lang' => $lang->getHtmlCode(),
411 'dir' => $lang->getDir(),
412 'class' => 'client-nojs',
417 * This will be called by OutputPage::headElement when it is creating the
418 * "<body>" tag, skins can override it if they have a need to add in any
419 * body attributes or classes of their own.
420 * @param OutputPage $out
421 * @param array $bodyAttrs
423 function addToBodyAttributes( $out, &$bodyAttrs ) {
424 // does nothing by default
428 * URL to the logo
429 * @return string
431 function getLogo() {
432 global $wgLogo;
433 return $wgLogo;
437 * @return string HTML
439 function getCategoryLinks() {
440 global $wgUseCategoryBrowser;
442 $out = $this->getOutput();
443 $allCats = $out->getCategoryLinks();
445 if ( !count( $allCats ) ) {
446 return '';
449 $embed = "<li>";
450 $pop = "</li>";
452 $s = '';
453 $colon = $this->msg( 'colon-separator' )->escaped();
455 if ( !empty( $allCats['normal'] ) ) {
456 $t = $embed . implode( "{$pop}{$embed}", $allCats['normal'] ) . $pop;
458 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) )->escaped();
459 $linkPage = wfMessage( 'pagecategorieslink' )->inContentLanguage()->text();
460 $title = Title::newFromText( $linkPage );
461 $link = $title ? Linker::link( $title, $msg ) : $msg;
462 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
463 $link . $colon . '<ul>' . $t . '</ul>' . '</div>';
466 # Hidden categories
467 if ( isset( $allCats['hidden'] ) ) {
468 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
469 $class = ' mw-hidden-cats-user-shown';
470 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
471 $class = ' mw-hidden-cats-ns-shown';
472 } else {
473 $class = ' mw-hidden-cats-hidden';
476 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
477 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
478 $colon . '<ul>' . $embed . implode( "{$pop}{$embed}", $allCats['hidden'] ) . $pop . '</ul>' .
479 '</div>';
482 # optional 'dmoz-like' category browser. Will be shown under the list
483 # of categories an article belong to
484 if ( $wgUseCategoryBrowser ) {
485 $s .= '<br /><hr />';
487 # get a big array of the parents tree
488 $parenttree = $this->getTitle()->getParentCategoryTree();
489 # Skin object passed by reference cause it can not be
490 # accessed under the method subfunction drawCategoryBrowser
491 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
492 # Clean out bogus first entry and sort them
493 unset( $tempout[0] );
494 asort( $tempout );
495 # Output one per line
496 $s .= implode( "<br />\n", $tempout );
499 return $s;
503 * Render the array as a series of links.
504 * @param array $tree Categories tree returned by Title::getParentCategoryTree
505 * @return string Separated by &gt;, terminate with "\n"
507 function drawCategoryBrowser( $tree ) {
508 $return = '';
510 foreach ( $tree as $element => $parent ) {
511 if ( empty( $parent ) ) {
512 # element start a new list
513 $return .= "\n";
514 } else {
515 # grab the others elements
516 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
519 # add our current element to the list
520 $eltitle = Title::newFromText( $element );
521 $return .= Linker::link( $eltitle, htmlspecialchars( $eltitle->getText() ) );
524 return $return;
528 * @return string HTML
530 function getCategories() {
531 $out = $this->getOutput();
532 $catlinks = $this->getCategoryLinks();
534 // Check what we're showing
535 $allCats = $out->getCategoryLinks();
536 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
537 $this->getTitle()->getNamespace() == NS_CATEGORY;
539 $classes = [ 'catlinks' ];
540 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
541 $classes[] = 'catlinks-allhidden';
544 return Html::rawElement(
545 'div',
546 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
547 $catlinks
552 * This runs a hook to allow extensions placing their stuff after content
553 * and article metadata (e.g. categories).
554 * Note: This function has nothing to do with afterContent().
556 * This hook is placed here in order to allow using the same hook for all
557 * skins, both the SkinTemplate based ones and the older ones, which directly
558 * use this class to get their data.
560 * The output of this function gets processed in SkinTemplate::outputPage() for
561 * the SkinTemplate based skins, all other skins should directly echo it.
563 * @return string Empty by default, if not changed by any hook function.
565 protected function afterContentHook() {
566 $data = '';
568 if ( Hooks::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
569 // adding just some spaces shouldn't toggle the output
570 // of the whole <div/>, so we use trim() here
571 if ( trim( $data ) != '' ) {
572 // Doing this here instead of in the skins to
573 // ensure that the div has the same ID in all
574 // skins
575 $data = "<div id='mw-data-after-content'>\n" .
576 "\t$data\n" .
577 "</div>\n";
579 } else {
580 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
583 return $data;
587 * Generate debug data HTML for displaying at the bottom of the main content
588 * area.
589 * @return string HTML containing debug data, if enabled (otherwise empty).
591 protected function generateDebugHTML() {
592 return MWDebug::getHTMLDebugLog();
596 * This gets called shortly before the "</body>" tag.
598 * @return string HTML-wrapped JS code to be put before "</body>"
600 function bottomScripts() {
601 // TODO and the suckage continues. This function is really just a wrapper around
602 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
603 // up at some point
604 $bottomScriptText = $this->getOutput()->getBottomScripts();
605 Hooks::run( 'SkinAfterBottomScripts', [ $this, &$bottomScriptText ] );
607 return $bottomScriptText;
611 * Text with the permalink to the source page,
612 * usually shown on the footer of a printed page
614 * @return string HTML text with an URL
616 function printSource() {
617 $oldid = $this->getRevisionId();
618 if ( $oldid ) {
619 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
620 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
621 } else {
622 // oldid not available for non existing pages
623 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
626 return $this->msg( 'retrievedfrom' )
627 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
628 ->parse();
632 * @return string HTML
634 function getUndeleteLink() {
635 $action = $this->getRequest()->getVal( 'action', 'view' );
637 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
638 ( !$this->getTitle()->exists() || $action == 'history' ) ) {
639 $n = $this->getTitle()->isDeleted();
641 if ( $n ) {
642 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
643 $msg = 'thisisdeleted';
644 } else {
645 $msg = 'viewdeleted';
648 return $this->msg( $msg )->rawParams(
649 Linker::linkKnown(
650 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
651 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
652 )->escaped();
656 return '';
660 * @param OutputPage $out Defaults to $this->getOutput() if left as null
661 * @return string
663 function subPageSubtitle( $out = null ) {
664 if ( $out === null ) {
665 $out = $this->getOutput();
667 $title = $out->getTitle();
668 $subpages = '';
670 if ( !Hooks::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
671 return $subpages;
674 if ( $out->isArticle() && MWNamespace::hasSubpages( $title->getNamespace() ) ) {
675 $ptext = $title->getPrefixedText();
676 if ( strpos( $ptext, '/' ) !== false ) {
677 $links = explode( '/', $ptext );
678 array_pop( $links );
679 $c = 0;
680 $growinglink = '';
681 $display = '';
682 $lang = $this->getLanguage();
684 foreach ( $links as $link ) {
685 $growinglink .= $link;
686 $display .= $link;
687 $linkObj = Title::newFromText( $growinglink );
689 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
690 $getlink = Linker::linkKnown(
691 $linkObj,
692 htmlspecialchars( $display )
695 $c++;
697 if ( $c > 1 ) {
698 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
699 } else {
700 $subpages .= '&lt; ';
703 $subpages .= $getlink;
704 $display = '';
705 } else {
706 $display .= '/';
708 $growinglink .= '/';
713 return $subpages;
717 * @deprecated since 1.27, feature removed
718 * @return bool Always false
720 function showIPinHeader() {
721 wfDeprecated( __METHOD__, '1.27' );
722 return false;
726 * @return string
728 function getSearchLink() {
729 $searchPage = SpecialPage::getTitleFor( 'Search' );
730 return $searchPage->getLocalURL();
734 * @return string
736 function escapeSearchLink() {
737 return htmlspecialchars( $this->getSearchLink() );
741 * @param string $type
742 * @return string
744 function getCopyright( $type = 'detect' ) {
745 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
747 if ( $type == 'detect' ) {
748 if ( !$this->isRevisionCurrent()
749 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
751 $type = 'history';
752 } else {
753 $type = 'normal';
757 if ( $type == 'history' ) {
758 $msg = 'history_copyright';
759 } else {
760 $msg = 'copyright';
763 if ( $wgRightsPage ) {
764 $title = Title::newFromText( $wgRightsPage );
765 $link = Linker::linkKnown( $title, $wgRightsText );
766 } elseif ( $wgRightsUrl ) {
767 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
768 } elseif ( $wgRightsText ) {
769 $link = $wgRightsText;
770 } else {
771 # Give up now
772 return '';
775 // Allow for site and per-namespace customization of copyright notice.
776 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
777 $forContent = true;
779 Hooks::run(
780 'SkinCopyrightFooter',
781 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
784 return $this->msg( $msg )->rawParams( $link )->text();
788 * @return null|string
790 function getCopyrightIcon() {
791 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
793 $out = '';
795 if ( $wgFooterIcons['copyright']['copyright'] ) {
796 $out = $wgFooterIcons['copyright']['copyright'];
797 } elseif ( $wgRightsIcon ) {
798 $icon = htmlspecialchars( $wgRightsIcon );
800 if ( $wgRightsUrl ) {
801 $url = htmlspecialchars( $wgRightsUrl );
802 $out .= '<a href="' . $url . '">';
805 $text = htmlspecialchars( $wgRightsText );
806 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
808 if ( $wgRightsUrl ) {
809 $out .= '</a>';
813 return $out;
817 * Gets the powered by MediaWiki icon.
818 * @return string
820 function getPoweredBy() {
821 global $wgResourceBasePath;
823 $url1 = htmlspecialchars(
824 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
826 $url1_5 = htmlspecialchars(
827 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
829 $url2 = htmlspecialchars(
830 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
832 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
833 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
834 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
835 Hooks::run( 'SkinGetPoweredBy', [ &$text, $this ] );
836 return $text;
840 * Get the timestamp of the latest revision, formatted in user language
842 * @return string
844 protected function lastModified() {
845 $timestamp = $this->getOutput()->getRevisionTimestamp();
847 # No cached timestamp, load it from the database
848 if ( $timestamp === null ) {
849 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
852 if ( $timestamp ) {
853 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
854 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
855 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
856 } else {
857 $s = '';
860 if ( wfGetLB()->getLaggedReplicaMode() ) {
861 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
864 return $s;
868 * @param string $align
869 * @return string
871 function logoText( $align = '' ) {
872 if ( $align != '' ) {
873 $a = " style='float: {$align};'";
874 } else {
875 $a = '';
878 $mp = $this->msg( 'mainpage' )->escaped();
879 $mptitle = Title::newMainPage();
880 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
882 $logourl = $this->getLogo();
883 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
885 return $s;
889 * Renders a $wgFooterIcons icon according to the method's arguments
890 * @param array $icon The icon to build the html for, see $wgFooterIcons
891 * for the format of this array.
892 * @param bool|string $withImage Whether to use the icon's image or output
893 * a text-only footericon.
894 * @return string HTML
896 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
897 if ( is_string( $icon ) ) {
898 $html = $icon;
899 } else { // Assuming array
900 $url = isset( $icon["url"] ) ? $icon["url"] : null;
901 unset( $icon["url"] );
902 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
903 // do this the lazy way, just pass icon data as an attribute array
904 $html = Html::element( 'img', $icon );
905 } else {
906 $html = htmlspecialchars( $icon["alt"] );
908 if ( $url ) {
909 $html = Html::rawElement( 'a', [ "href" => $url ], $html );
912 return $html;
916 * Gets the link to the wiki's main page.
917 * @return string
919 function mainPageLink() {
920 $s = Linker::linkKnown(
921 Title::newMainPage(),
922 $this->msg( 'mainpage' )->escaped()
925 return $s;
929 * Returns an HTML link for use in the footer
930 * @param string $desc The i18n message key for the link text
931 * @param string $page The i18n message key for the page to link to
932 * @return string HTML anchor
934 public function footerLink( $desc, $page ) {
935 $title = $this->footerLinkTitle( $desc, $page );
936 if ( !$title ) {
937 return '';
940 return Linker::linkKnown(
941 $title,
942 $this->msg( $desc )->escaped()
947 * @param string $desc
948 * @param string $page
949 * @return Title|null
951 private function footerLinkTitle( $desc, $page ) {
952 // If the link description has been set to "-" in the default language,
953 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
954 // then it is disabled, for all languages.
955 return null;
957 // Otherwise, we display the link for the user, described in their
958 // language (which may or may not be the same as the default language),
959 // but we make the link target be the one site-wide page.
960 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
962 return $title ?: null;
966 * Gets the link to the wiki's privacy policy page.
967 * @return string HTML
969 function privacyLink() {
970 return $this->footerLink( 'privacy', 'privacypage' );
974 * Gets the link to the wiki's about page.
975 * @return string HTML
977 function aboutLink() {
978 return $this->footerLink( 'aboutsite', 'aboutpage' );
982 * Gets the link to the wiki's general disclaimers page.
983 * @return string HTML
985 function disclaimerLink() {
986 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
990 * Return URL options for the 'edit page' link.
991 * This may include an 'oldid' specifier, if the current page view is such.
993 * @return array
994 * @private
996 function editUrlOptions() {
997 $options = [ 'action' => 'edit' ];
999 if ( !$this->isRevisionCurrent() ) {
1000 $options['oldid'] = intval( $this->getRevisionId() );
1003 return $options;
1007 * @param User|int $id
1008 * @return bool
1010 function showEmailUser( $id ) {
1011 if ( $id instanceof User ) {
1012 $targetUser = $id;
1013 } else {
1014 $targetUser = User::newFromId( $id );
1017 # The sending user must have a confirmed email address and the target
1018 # user must have a confirmed email address and allow emails from users.
1019 return $this->getUser()->canSendEmail() &&
1020 $targetUser->canReceiveEmail();
1024 * Return a fully resolved style path url to images or styles stored in the current skins's folder.
1025 * This method returns a url resolved using the configured skin style path
1026 * and includes the style version inside of the url.
1028 * Requires $stylename to be set, otherwise throws MWException.
1030 * @param string $name The name or path of a skin resource file
1031 * @return string The fully resolved style path url including styleversion
1032 * @throws MWException
1034 function getSkinStylePath( $name ) {
1035 global $wgStylePath, $wgStyleVersion;
1037 if ( $this->stylename === null ) {
1038 $class = get_class( $this );
1039 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1042 return "$wgStylePath/{$this->stylename}/$name?$wgStyleVersion";
1045 /* these are used extensively in SkinTemplate, but also some other places */
1048 * @param string $urlaction
1049 * @return string
1051 static function makeMainPageUrl( $urlaction = '' ) {
1052 $title = Title::newMainPage();
1053 self::checkTitle( $title, '' );
1055 return $title->getLocalURL( $urlaction );
1059 * Make a URL for a Special Page using the given query and protocol.
1061 * If $proto is set to null, make a local URL. Otherwise, make a full
1062 * URL with the protocol specified.
1064 * @param string $name Name of the Special page
1065 * @param string $urlaction Query to append
1066 * @param string|null $proto Protocol to use or null for a local URL
1067 * @return string
1069 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1070 $title = SpecialPage::getSafeTitleFor( $name );
1071 if ( is_null( $proto ) ) {
1072 return $title->getLocalURL( $urlaction );
1073 } else {
1074 return $title->getFullURL( $urlaction, false, $proto );
1079 * @param string $name
1080 * @param string $subpage
1081 * @param string $urlaction
1082 * @return string
1084 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1085 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1086 return $title->getLocalURL( $urlaction );
1090 * @param string $name
1091 * @param string $urlaction
1092 * @return string
1094 static function makeI18nUrl( $name, $urlaction = '' ) {
1095 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1096 self::checkTitle( $title, $name );
1097 return $title->getLocalURL( $urlaction );
1101 * @param string $name
1102 * @param string $urlaction
1103 * @return string
1105 static function makeUrl( $name, $urlaction = '' ) {
1106 $title = Title::newFromText( $name );
1107 self::checkTitle( $title, $name );
1109 return $title->getLocalURL( $urlaction );
1113 * If url string starts with http, consider as external URL, else
1114 * internal
1115 * @param string $name
1116 * @return string URL
1118 static function makeInternalOrExternalUrl( $name ) {
1119 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1120 return $name;
1121 } else {
1122 return self::makeUrl( $name );
1127 * this can be passed the NS number as defined in Language.php
1128 * @param string $name
1129 * @param string $urlaction
1130 * @param int $namespace
1131 * @return string
1133 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1134 $title = Title::makeTitleSafe( $namespace, $name );
1135 self::checkTitle( $title, $name );
1137 return $title->getLocalURL( $urlaction );
1141 * these return an array with the 'href' and boolean 'exists'
1142 * @param string $name
1143 * @param string $urlaction
1144 * @return array
1146 static function makeUrlDetails( $name, $urlaction = '' ) {
1147 $title = Title::newFromText( $name );
1148 self::checkTitle( $title, $name );
1150 return [
1151 'href' => $title->getLocalURL( $urlaction ),
1152 'exists' => $title->isKnown(),
1157 * Make URL details where the article exists (or at least it's convenient to think so)
1158 * @param string $name Article name
1159 * @param string $urlaction
1160 * @return array
1162 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1163 $title = Title::newFromText( $name );
1164 self::checkTitle( $title, $name );
1166 return [
1167 'href' => $title->getLocalURL( $urlaction ),
1168 'exists' => true
1173 * make sure we have some title to operate on
1175 * @param Title $title
1176 * @param string $name
1178 static function checkTitle( &$title, $name ) {
1179 if ( !is_object( $title ) ) {
1180 $title = Title::newFromText( $name );
1181 if ( !is_object( $title ) ) {
1182 $title = Title::newFromText( '--error: link target missing--' );
1188 * Build an array that represents the sidebar(s), the navigation bar among them.
1190 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1192 * The format of the returned array is [ heading => content, ... ], where:
1193 * - heading is the heading of a navigation portlet. It is either:
1194 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1195 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1196 * - plain text, which should be HTML-escaped by the skin
1197 * - content is the contents of the portlet. It is either:
1198 * - HTML text (<ul><li>...</li>...</ul>)
1199 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1200 * - (for a magic string as a key, any value)
1202 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1203 * and can technically insert anything in here; skin creators are expected to handle
1204 * values described above.
1206 * @return array
1208 function buildSidebar() {
1209 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1211 $that = $this;
1212 $callback = function () use ( $that ) {
1213 $bar = [];
1214 $that->addToSidebar( $bar, 'sidebar' );
1215 Hooks::run( 'SkinBuildSidebar', [ $that, &$bar ] );
1217 return $bar;
1220 if ( $wgEnableSidebarCache ) {
1221 $cache = ObjectCache::getMainWANInstance();
1222 $sidebar = $cache->getWithSetCallback(
1223 $cache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1224 MessageCache::singleton()->isDisabled()
1225 ? $cache::TTL_UNCACHEABLE // bug T133069
1226 : $wgSidebarCacheExpiry,
1227 $callback,
1228 [ 'lockTSE' => 30 ]
1230 } else {
1231 $sidebar = $callback();
1234 // Apply post-processing to the cached value
1235 Hooks::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1237 return $sidebar;
1241 * Add content from a sidebar system message
1242 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1244 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1246 * @param array $bar
1247 * @param string $message
1249 public function addToSidebar( &$bar, $message ) {
1250 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1254 * Add content from plain text
1255 * @since 1.17
1256 * @param array $bar
1257 * @param string $text
1258 * @return array
1260 function addToSidebarPlain( &$bar, $text ) {
1261 $lines = explode( "\n", $text );
1263 $heading = '';
1264 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1265 ? Title::newMainPage() : $this->getTitle();
1267 foreach ( $lines as $line ) {
1268 if ( strpos( $line, '*' ) !== 0 ) {
1269 continue;
1271 $line = rtrim( $line, "\r" ); // for Windows compat
1273 if ( strpos( $line, '**' ) !== 0 ) {
1274 $heading = trim( $line, '* ' );
1275 if ( !array_key_exists( $heading, $bar ) ) {
1276 $bar[$heading] = [];
1278 } else {
1279 $line = trim( $line, '* ' );
1281 if ( strpos( $line, '|' ) !== false ) { // sanity check
1282 $line = MessageCache::singleton()->transform( $line, false, null, $messageTitle );
1283 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1284 if ( count( $line ) !== 2 ) {
1285 // Second sanity check, could be hit by people doing
1286 // funky stuff with parserfuncs... (bug 33321)
1287 continue;
1290 $extraAttribs = [];
1292 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1293 if ( $msgLink->exists() ) {
1294 $link = $msgLink->text();
1295 if ( $link == '-' ) {
1296 continue;
1298 } else {
1299 $link = $line[0];
1301 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1302 if ( $msgText->exists() ) {
1303 $text = $msgText->text();
1304 } else {
1305 $text = $line[1];
1308 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1309 $href = $link;
1311 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1312 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1313 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1314 $extraAttribs['rel'] = 'nofollow';
1317 global $wgExternalLinkTarget;
1318 if ( $wgExternalLinkTarget ) {
1319 $extraAttribs['target'] = $wgExternalLinkTarget;
1321 } else {
1322 $title = Title::newFromText( $link );
1324 if ( $title ) {
1325 $title = $title->fixSpecialName();
1326 $href = $title->getLinkURL();
1327 } else {
1328 $href = 'INVALID-TITLE';
1332 $bar[$heading][] = array_merge( [
1333 'text' => $text,
1334 'href' => $href,
1335 'id' => 'n-' . Sanitizer::escapeId( strtr( $line[1], ' ', '-' ), 'noninitial' ),
1336 'active' => false
1337 ], $extraAttribs );
1338 } else {
1339 continue;
1344 return $bar;
1348 * Gets new talk page messages for the current user and returns an
1349 * appropriate alert message (or an empty string if there are no messages)
1350 * @return string
1352 function getNewtalks() {
1354 $newMessagesAlert = '';
1355 $user = $this->getUser();
1356 $newtalks = $user->getNewMessageLinks();
1357 $out = $this->getOutput();
1359 // Allow extensions to disable or modify the new messages alert
1360 if ( !Hooks::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1361 return '';
1363 if ( $newMessagesAlert ) {
1364 return $newMessagesAlert;
1367 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1368 $uTalkTitle = $user->getTalkPage();
1369 $lastSeenRev = isset( $newtalks[0]['rev'] ) ? $newtalks[0]['rev'] : null;
1370 $nofAuthors = 0;
1371 if ( $lastSeenRev !== null ) {
1372 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1373 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1374 if ( $latestRev !== null ) {
1375 // Singular if only 1 unseen revision, plural if several unseen revisions.
1376 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1377 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1378 $lastSeenRev, $latestRev, 10, 'include_new' );
1380 } else {
1381 // Singular if no revision -> diff link will show latest change only in any case
1382 $plural = false;
1384 $plural = $plural ? 999 : 1;
1385 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1386 // the number of revisions or authors is not necessarily the same as the number of
1387 // "messages".
1388 $newMessagesLink = Linker::linkKnown(
1389 $uTalkTitle,
1390 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1392 [ 'redirect' => 'no' ]
1395 $newMessagesDiffLink = Linker::linkKnown(
1396 $uTalkTitle,
1397 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1399 $lastSeenRev !== null
1400 ? [ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1401 : [ 'diff' => 'cur' ]
1404 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1405 $newMessagesAlert = $this->msg(
1406 'youhavenewmessagesfromusers',
1407 $newMessagesLink,
1408 $newMessagesDiffLink
1409 )->numParams( $nofAuthors, $plural );
1410 } else {
1411 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1412 $newMessagesAlert = $this->msg(
1413 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1414 $newMessagesLink,
1415 $newMessagesDiffLink
1416 )->numParams( $plural );
1418 $newMessagesAlert = $newMessagesAlert->text();
1419 # Disable CDN cache
1420 $out->setCdnMaxage( 0 );
1421 } elseif ( count( $newtalks ) ) {
1422 $sep = $this->msg( 'newtalkseparator' )->escaped();
1423 $msgs = [];
1425 foreach ( $newtalks as $newtalk ) {
1426 $msgs[] = Xml::element(
1427 'a',
1428 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1431 $parts = implode( $sep, $msgs );
1432 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1433 $out->setCdnMaxage( 0 );
1436 return $newMessagesAlert;
1440 * Get a cached notice
1442 * @param string $name Message name, or 'default' for $wgSiteNotice
1443 * @return string|bool HTML fragment, or false to indicate that the caller
1444 * should fall back to the next notice in its sequence
1446 private function getCachedNotice( $name ) {
1447 global $wgRenderHashAppend, $parserMemc, $wgContLang;
1449 $needParse = false;
1451 if ( $name === 'default' ) {
1452 // special case
1453 global $wgSiteNotice;
1454 $notice = $wgSiteNotice;
1455 if ( empty( $notice ) ) {
1456 return false;
1458 } else {
1459 $msg = $this->msg( $name )->inContentLanguage();
1460 if ( $msg->isBlank() ) {
1461 return '';
1462 } elseif ( $msg->isDisabled() ) {
1463 return false;
1465 $notice = $msg->plain();
1468 // Use the extra hash appender to let eg SSL variants separately cache.
1469 $key = wfMemcKey( $name . $wgRenderHashAppend );
1470 $cachedNotice = $parserMemc->get( $key );
1471 if ( is_array( $cachedNotice ) ) {
1472 if ( md5( $notice ) == $cachedNotice['hash'] ) {
1473 $notice = $cachedNotice['html'];
1474 } else {
1475 $needParse = true;
1477 } else {
1478 $needParse = true;
1481 if ( $needParse ) {
1482 $parsed = $this->getOutput()->parse( $notice );
1483 $parserMemc->set( $key, [ 'html' => $parsed, 'hash' => md5( $notice ) ], 600 );
1484 $notice = $parsed;
1487 $notice = Html::rawElement( 'div', [ 'id' => 'localNotice',
1488 'lang' => $wgContLang->getHtmlCode(), 'dir' => $wgContLang->getDir() ], $notice );
1489 return $notice;
1493 * Get the site notice
1495 * @return string HTML fragment
1497 function getSiteNotice() {
1498 $siteNotice = '';
1500 if ( Hooks::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1501 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1502 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1503 } else {
1504 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1505 if ( $anonNotice === false ) {
1506 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1507 } else {
1508 $siteNotice = $anonNotice;
1511 if ( $siteNotice === false ) {
1512 $siteNotice = $this->getCachedNotice( 'default' );
1516 Hooks::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1517 return $siteNotice;
1521 * Create a section edit link. This supersedes editSectionLink() and
1522 * editSectionLinkForOther().
1524 * @param Title $nt The title being linked to (may not be the same as
1525 * the current page, if the section is included from a template)
1526 * @param string $section The designation of the section being pointed to,
1527 * to be included in the link, like "&section=$section"
1528 * @param string $tooltip The tooltip to use for the link: will be escaped
1529 * and wrapped in the 'editsectionhint' message
1530 * @param string $lang Language code
1531 * @return string HTML to use for edit link
1533 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1534 // HTML generated here should probably have userlangattributes
1535 // added to it for LTR text on RTL pages
1537 $lang = wfGetLangObj( $lang );
1539 $attribs = [];
1540 if ( !is_null( $tooltip ) ) {
1541 # Bug 25462: undo double-escaping.
1542 $tooltip = Sanitizer::decodeCharReferences( $tooltip );
1543 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1544 ->inLanguage( $lang )->text();
1547 $links = [
1548 'editsection' => [
1549 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1550 'targetTitle' => $nt,
1551 'attribs' => $attribs,
1552 'query' => [ 'action' => 'edit', 'section' => $section ],
1553 'options' => [ 'noclasses', 'known' ]
1557 Hooks::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1559 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1561 $linksHtml = [];
1562 foreach ( $links as $k => $linkDetails ) {
1563 $linksHtml[] = Linker::link(
1564 $linkDetails['targetTitle'],
1565 $linkDetails['text'],
1566 $linkDetails['attribs'],
1567 $linkDetails['query'],
1568 $linkDetails['options']
1572 $result .= implode(
1573 '<span class="mw-editsection-divider">'
1574 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->text()
1575 . '</span>',
1576 $linksHtml
1579 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1580 // Deprecated, use SkinEditSectionLinks hook instead
1581 Hooks::run(
1582 'DoEditSectionLink',
1583 [ $this, $nt, $section, $tooltip, &$result, $lang ],
1584 '1.25'
1586 return $result;