skins: Skin::getSkinNameMessages() method is now deprecated
[lhc/web/wiklou.git] / includes / skins / Skin.php
1 <?php
2 /**
3 * Base class for all skins.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\WrappedString;
25 use Wikimedia\WrappedStringList;
26
27 /**
28 * @defgroup Skins Skins
29 */
30
31 /**
32 * The main skin class which provides methods and properties for all other skins.
33 *
34 * See docs/skin.txt for more information.
35 *
36 * @ingroup Skins
37 */
38 abstract class Skin extends ContextSource {
39 /**
40 * @var string|null
41 */
42 protected $skinname = null;
43
44 protected $mRelevantTitle = null;
45 protected $mRelevantUser = null;
46
47 /**
48 * @var string Stylesheets set to use. Subdirectory in skins/ where various stylesheets are
49 * located. Only needs to be set if you intend to use the getSkinStylePath() method.
50 */
51 public $stylename = null;
52
53 /**
54 * Fetch the set of available skins.
55 * @return array Associative array of strings
56 */
57 static function getSkinNames() {
58 $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
59 return $skinFactory->getSkinNames();
60 }
61
62 /**
63 * Fetch the skinname messages for available skins.
64 * @deprecated since 1.34, no longer used.
65 * @return string[]
66 */
67 static function getSkinNameMessages() {
68 wfDeprecated( __METHOD__, '1.34' );
69 $messages = [];
70 foreach ( self::getSkinNames() as $skinKey => $skinName ) {
71 $messages[] = "skinname-$skinKey";
72 }
73 return $messages;
74 }
75
76 /**
77 * Fetch the list of user-selectable skins in regards to $wgSkipSkins.
78 * Useful for Special:Preferences and other places where you
79 * only want to show skins users _can_ use.
80 * @return string[]
81 * @since 1.23
82 */
83 public static function getAllowedSkins() {
84 global $wgSkipSkins;
85
86 $allowedSkins = self::getSkinNames();
87
88 foreach ( $wgSkipSkins as $skip ) {
89 unset( $allowedSkins[$skip] );
90 }
91
92 return $allowedSkins;
93 }
94
95 /**
96 * Normalize a skin preference value to a form that can be loaded.
97 *
98 * If a skin can't be found, it will fall back to the configured default ($wgDefaultSkin), or the
99 * hardcoded default ($wgFallbackSkin) if the default skin is unavailable too.
100 *
101 * @param string $key 'monobook', 'vector', etc.
102 * @return string
103 */
104 static function normalizeKey( $key ) {
105 global $wgDefaultSkin, $wgFallbackSkin;
106
107 $skinNames = self::getSkinNames();
108
109 // Make keys lowercase for case-insensitive matching.
110 $skinNames = array_change_key_case( $skinNames, CASE_LOWER );
111 $key = strtolower( $key );
112 $defaultSkin = strtolower( $wgDefaultSkin );
113 $fallbackSkin = strtolower( $wgFallbackSkin );
114
115 if ( $key == '' || $key == 'default' ) {
116 // Don't return the default immediately;
117 // in a misconfiguration we need to fall back.
118 $key = $defaultSkin;
119 }
120
121 if ( isset( $skinNames[$key] ) ) {
122 return $key;
123 }
124
125 // Older versions of the software used a numeric setting
126 // in the user preferences.
127 $fallback = [
128 0 => $defaultSkin,
129 2 => 'cologneblue'
130 ];
131
132 if ( isset( $fallback[$key] ) ) {
133 $key = $fallback[$key];
134 }
135
136 if ( isset( $skinNames[$key] ) ) {
137 return $key;
138 } elseif ( isset( $skinNames[$defaultSkin] ) ) {
139 return $defaultSkin;
140 } else {
141 return $fallbackSkin;
142 }
143 }
144
145 /**
146 * @since 1.31
147 * @param string|null $skinname
148 */
149 public function __construct( $skinname = null ) {
150 if ( is_string( $skinname ) ) {
151 $this->skinname = $skinname;
152 }
153 }
154
155 /**
156 * @return string|null Skin name
157 */
158 public function getSkinName() {
159 return $this->skinname;
160 }
161
162 /**
163 * @param OutputPage $out
164 */
165 public function initPage( OutputPage $out ) {
166 $this->preloadExistence();
167 }
168
169 /**
170 * Defines the ResourceLoader modules that should be added to the skin
171 * It is recommended that skins wishing to override call parent::getDefaultModules()
172 * and substitute out any modules they wish to change by using a key to look them up
173 *
174 * Any modules defined with the 'styles' key will be added as render blocking CSS via
175 * Output::addModuleStyles. Similarly, each key should refer to a list of modules
176 *
177 * @return array Array of modules with helper keys for easy overriding
178 */
179 public function getDefaultModules() {
180 $out = $this->getOutput();
181 $user = $this->getUser();
182
183 // Modules declared in the $modules literal are loaded
184 // for ALL users, on ALL pages, in ALL skins.
185 // Keep this list as small as possible!
186 $modules = [
187 'styles' => [
188 // The 'styles' key sets render-blocking style modules
189 // Unlike other keys in $modules, this is an associative array
190 // where each key is its own group pointing to a list of modules
191 'core' => [
192 'mediawiki.legacy.shared',
193 'mediawiki.legacy.commonPrint',
194 ],
195 'content' => [],
196 'syndicate' => [],
197 ],
198 'core' => [
199 'site',
200 'mediawiki.page.startup',
201 ],
202 // modules that enhance the content in some way
203 'content' => [
204 'mediawiki.page.ready',
205 ],
206 // modules relating to search functionality
207 'search' => [
208 'mediawiki.searchSuggest',
209 ],
210 // modules relating to functionality relating to watching an article
211 'watch' => [],
212 // modules which relate to the current users preferences
213 'user' => [],
214 // modules relating to RSS/Atom Feeds
215 'syndicate' => [],
216 ];
217
218 // Preload jquery.tablesorter for mediawiki.page.ready
219 if ( strpos( $out->getHTML(), 'sortable' ) !== false ) {
220 $modules['content'][] = 'jquery.tablesorter';
221 $modules['styles']['content'][] = 'jquery.tablesorter.styles';
222 }
223
224 // Preload jquery.makeCollapsible for mediawiki.page.ready
225 if ( strpos( $out->getHTML(), 'mw-collapsible' ) !== false ) {
226 $modules['content'][] = 'jquery.makeCollapsible';
227 $modules['styles']['content'][] = 'jquery.makeCollapsible.styles';
228 }
229
230 // Deprecated since 1.26: Unconditional loading of mediawiki.ui.button
231 // on every page is deprecated. Express a dependency instead.
232 if ( strpos( $out->getHTML(), 'mw-ui-button' ) !== false ) {
233 $modules['styles']['content'][] = 'mediawiki.ui.button';
234 }
235
236 if ( $out->isTOCEnabled() ) {
237 $modules['content'][] = 'mediawiki.toc';
238 $modules['styles']['content'][] = 'mediawiki.toc.styles';
239 }
240
241 // Add various resources if required
242 if ( $user->isLoggedIn()
243 && MediaWikiServices::getInstance()
244 ->getPermissionManager()
245 ->userHasAllRights( $user, 'writeapi', 'viewmywatchlist', 'editmywatchlist' )
246 && $this->getRelevantTitle()->canExist()
247 ) {
248 $modules['watch'][] = 'mediawiki.page.watch.ajax';
249 }
250
251 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
252 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
253 }
254
255 // Crazy edit-on-double-click stuff
256 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
257 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
258 }
259
260 if ( $out->isSyndicated() ) {
261 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
262 }
263
264 return $modules;
265 }
266
267 /**
268 * Preload the existence of three commonly-requested pages in a single query
269 */
270 protected function preloadExistence() {
271 $titles = [];
272
273 // User/talk link
274 $user = $this->getUser();
275 if ( $user->isLoggedIn() ) {
276 $titles[] = $user->getUserPage();
277 $titles[] = $user->getTalkPage();
278 }
279
280 // Check, if the page can hold some kind of content, otherwise do nothing
281 $title = $this->getRelevantTitle();
282 if ( $title->canExist() && $title->canHaveTalkPage() ) {
283 if ( $title->isTalkPage() ) {
284 $titles[] = $title->getSubjectPage();
285 } else {
286 $titles[] = $title->getTalkPage();
287 }
288 }
289
290 // Footer links (used by SkinTemplate::prepareQuickTemplate)
291 foreach ( [
292 $this->footerLinkTitle( 'privacy', 'privacypage' ),
293 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
294 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
295 ] as $title ) {
296 if ( $title ) {
297 $titles[] = $title;
298 }
299 }
300
301 Hooks::run( 'SkinPreloadExistence', [ &$titles, $this ] );
302
303 if ( $titles ) {
304 $lb = new LinkBatch( $titles );
305 $lb->setCaller( __METHOD__ );
306 $lb->execute();
307 }
308 }
309
310 /**
311 * Get the current revision ID
312 *
313 * @deprecated since 1.34, use OutputPage::getRevisionId instead
314 * @return int
315 */
316 public function getRevisionId() {
317 return $this->getOutput()->getRevisionId();
318 }
319
320 /**
321 * Whether the revision displayed is the latest revision of the page
322 *
323 * @deprecated since 1.34, use OutputPage::isRevisionCurrent instead
324 * @return bool
325 */
326 public function isRevisionCurrent() {
327 return $this->getOutput()->isRevisionCurrent();
328 }
329
330 /**
331 * Set the "relevant" title
332 * @see self::getRelevantTitle()
333 * @param Title $t
334 */
335 public function setRelevantTitle( $t ) {
336 $this->mRelevantTitle = $t;
337 }
338
339 /**
340 * Return the "relevant" title.
341 * A "relevant" title is not necessarily the actual title of the page.
342 * Special pages like Special:MovePage use set the page they are acting on
343 * as their "relevant" title, this allows the skin system to display things
344 * such as content tabs which belong to to that page instead of displaying
345 * a basic special page tab which has almost no meaning.
346 *
347 * @return Title
348 */
349 public function getRelevantTitle() {
350 return $this->mRelevantTitle ?? $this->getTitle();
351 }
352
353 /**
354 * Set the "relevant" user
355 * @see self::getRelevantUser()
356 * @param User $u
357 */
358 public function setRelevantUser( $u ) {
359 $this->mRelevantUser = $u;
360 }
361
362 /**
363 * Return the "relevant" user.
364 * A "relevant" user is similar to a relevant title. Special pages like
365 * Special:Contributions mark the user which they are relevant to so that
366 * things like the toolbox can display the information they usually are only
367 * able to display on a user's userpage and talkpage.
368 * @return User
369 */
370 public function getRelevantUser() {
371 if ( isset( $this->mRelevantUser ) ) {
372 return $this->mRelevantUser;
373 }
374 $title = $this->getRelevantTitle();
375 if ( $title->hasSubjectNamespace( NS_USER ) ) {
376 $rootUser = $title->getRootText();
377 if ( User::isIP( $rootUser ) ) {
378 $this->mRelevantUser = User::newFromName( $rootUser, false );
379 } else {
380 $user = User::newFromName( $rootUser, false );
381
382 if ( $user ) {
383 $user->load( User::READ_NORMAL );
384
385 if ( $user->isLoggedIn() ) {
386 $this->mRelevantUser = $user;
387 }
388 }
389 }
390 return $this->mRelevantUser;
391 }
392 return null;
393 }
394
395 /**
396 * Outputs the HTML generated by other functions.
397 */
398 abstract function outputPage();
399
400 /**
401 * @param array $data
402 * @param string|null $nonce OutputPage::getCSPNonce()
403 * @return string|WrappedString HTML
404 */
405 public static function makeVariablesScript( $data, $nonce = null ) {
406 if ( $data ) {
407 return ResourceLoader::makeInlineScript(
408 ResourceLoader::makeConfigSetScript( $data ),
409 $nonce
410 );
411 }
412 return '';
413 }
414
415 /**
416 * Get the query to generate a dynamic stylesheet
417 *
418 * @deprecated since 1.32 Use action=raw&ctype=text/css directly.
419 * @return array
420 */
421 public static function getDynamicStylesheetQuery() {
422 return [
423 'action' => 'raw',
424 'ctype' => 'text/css',
425 ];
426 }
427
428 /**
429 * Hook point for adding style modules to OutputPage.
430 *
431 * @deprecated since 1.32 Use getDefaultModules() instead.
432 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
433 */
434 public function setupSkinUserCss( OutputPage $out ) {
435 // Stub.
436 }
437
438 /**
439 * TODO: document
440 * @param Title $title
441 * @return string
442 */
443 function getPageClasses( $title ) {
444 $numeric = 'ns-' . $title->getNamespace();
445 $user = $this->getUser();
446
447 if ( $title->isSpecialPage() ) {
448 $type = 'ns-special';
449 // T25315: provide a class based on the canonical special page name without subpages
450 list( $canonicalName ) = MediaWikiServices::getInstance()->getSpecialPageFactory()->
451 resolveAlias( $title->getDBkey() );
452 if ( $canonicalName ) {
453 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
454 } else {
455 $type .= ' mw-invalidspecialpage';
456 }
457 } else {
458 if ( $title->isTalkPage() ) {
459 $type = 'ns-talk';
460 } else {
461 $type = 'ns-subject';
462 }
463 // T208315: add HTML class when the user can edit the page
464 if ( $title->quickUserCan( 'edit', $user ) ) {
465 $type .= ' mw-editable';
466 }
467 }
468
469 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
470 $root = Sanitizer::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
471
472 return "$numeric $type $name $root";
473 }
474
475 /**
476 * Return values for <html> element
477 * @return array Array of associative name-to-value elements for <html> element
478 */
479 public function getHtmlElementAttributes() {
480 $lang = $this->getLanguage();
481 return [
482 'lang' => $lang->getHtmlCode(),
483 'dir' => $lang->getDir(),
484 'class' => 'client-nojs',
485 ];
486 }
487
488 /**
489 * This will be called by OutputPage::headElement when it is creating the
490 * "<body>" tag, skins can override it if they have a need to add in any
491 * body attributes or classes of their own.
492 * @param OutputPage $out
493 * @param array &$bodyAttrs
494 */
495 function addToBodyAttributes( $out, &$bodyAttrs ) {
496 // does nothing by default
497 }
498
499 /**
500 * URL to the logo
501 * @return string
502 */
503 function getLogo() {
504 return $this->getConfig()->get( 'Logo' );
505 }
506
507 /**
508 * Whether the logo should be preloaded with an HTTP link header or not
509 *
510 * @deprecated since 1.32 Redundant. It now happens automatically based on whether
511 * the skin loads a stylesheet based on ResourceLoaderSkinModule, which all
512 * skins that use wgLogo in CSS do, and other's would not.
513 * @since 1.29
514 * @return bool
515 */
516 public function shouldPreloadLogo() {
517 return false;
518 }
519
520 /**
521 * @return string HTML
522 */
523 function getCategoryLinks() {
524 $out = $this->getOutput();
525 $allCats = $out->getCategoryLinks();
526 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
527
528 if ( $allCats === [] ) {
529 return '';
530 }
531
532 $embed = "<li>";
533 $pop = "</li>";
534
535 $s = '';
536 $colon = $this->msg( 'colon-separator' )->escaped();
537
538 if ( !empty( $allCats['normal'] ) ) {
539 $t = $embed . implode( $pop . $embed, $allCats['normal'] ) . $pop;
540
541 $msg = $this->msg( 'pagecategories' )->numParams( count( $allCats['normal'] ) );
542 $linkPage = $this->msg( 'pagecategorieslink' )->inContentLanguage()->text();
543 $title = Title::newFromText( $linkPage );
544 $link = $title ? $linkRenderer->makeLink( $title, $msg->text() ) : $msg->escaped();
545 $s .= '<div id="mw-normal-catlinks" class="mw-normal-catlinks">' .
546 $link . $colon . '<ul>' . $t . '</ul></div>';
547 }
548
549 # Hidden categories
550 if ( isset( $allCats['hidden'] ) ) {
551 if ( $this->getUser()->getBoolOption( 'showhiddencats' ) ) {
552 $class = ' mw-hidden-cats-user-shown';
553 } elseif ( $this->getTitle()->getNamespace() == NS_CATEGORY ) {
554 $class = ' mw-hidden-cats-ns-shown';
555 } else {
556 $class = ' mw-hidden-cats-hidden';
557 }
558
559 $s .= "<div id=\"mw-hidden-catlinks\" class=\"mw-hidden-catlinks$class\">" .
560 $this->msg( 'hidden-categories' )->numParams( count( $allCats['hidden'] ) )->escaped() .
561 $colon . '<ul>' . $embed . implode( $pop . $embed, $allCats['hidden'] ) . $pop . '</ul>' .
562 '</div>';
563 }
564
565 # optional 'dmoz-like' category browser. Will be shown under the list
566 # of categories an article belong to
567 if ( $this->getConfig()->get( 'UseCategoryBrowser' ) ) {
568 $s .= '<br /><hr />';
569
570 # get a big array of the parents tree
571 $parenttree = $this->getTitle()->getParentCategoryTree();
572 # Skin object passed by reference cause it can not be
573 # accessed under the method subfunction drawCategoryBrowser
574 $tempout = explode( "\n", $this->drawCategoryBrowser( $parenttree ) );
575 # Clean out bogus first entry and sort them
576 unset( $tempout[0] );
577 asort( $tempout );
578 # Output one per line
579 $s .= implode( "<br />\n", $tempout );
580 }
581
582 return $s;
583 }
584
585 /**
586 * Render the array as a series of links.
587 * @param array $tree Categories tree returned by Title::getParentCategoryTree
588 * @return string Separated by &gt;, terminate with "\n"
589 */
590 function drawCategoryBrowser( $tree ) {
591 $return = '';
592 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
593
594 foreach ( $tree as $element => $parent ) {
595 if ( empty( $parent ) ) {
596 # element start a new list
597 $return .= "\n";
598 } else {
599 # grab the others elements
600 $return .= $this->drawCategoryBrowser( $parent ) . ' &gt; ';
601 }
602
603 # add our current element to the list
604 $eltitle = Title::newFromText( $element );
605 $return .= $linkRenderer->makeLink( $eltitle, $eltitle->getText() );
606 }
607
608 return $return;
609 }
610
611 /**
612 * @return string HTML
613 */
614 function getCategories() {
615 $out = $this->getOutput();
616 $catlinks = $this->getCategoryLinks();
617
618 // Check what we're showing
619 $allCats = $out->getCategoryLinks();
620 $showHidden = $this->getUser()->getBoolOption( 'showhiddencats' ) ||
621 $this->getTitle()->getNamespace() == NS_CATEGORY;
622
623 $classes = [ 'catlinks' ];
624 if ( empty( $allCats['normal'] ) && !( !empty( $allCats['hidden'] ) && $showHidden ) ) {
625 $classes[] = 'catlinks-allhidden';
626 }
627
628 return Html::rawElement(
629 'div',
630 [ 'id' => 'catlinks', 'class' => $classes, 'data-mw' => 'interface' ],
631 $catlinks
632 );
633 }
634
635 /**
636 * This runs a hook to allow extensions placing their stuff after content
637 * and article metadata (e.g. categories).
638 * Note: This function has nothing to do with afterContent().
639 *
640 * This hook is placed here in order to allow using the same hook for all
641 * skins, both the SkinTemplate based ones and the older ones, which directly
642 * use this class to get their data.
643 *
644 * The output of this function gets processed in SkinTemplate::outputPage() for
645 * the SkinTemplate based skins, all other skins should directly echo it.
646 *
647 * @return string Empty by default, if not changed by any hook function.
648 */
649 protected function afterContentHook() {
650 $data = '';
651
652 if ( Hooks::run( 'SkinAfterContent', [ &$data, $this ] ) ) {
653 // adding just some spaces shouldn't toggle the output
654 // of the whole <div/>, so we use trim() here
655 if ( trim( $data ) != '' ) {
656 // Doing this here instead of in the skins to
657 // ensure that the div has the same ID in all
658 // skins
659 $data = "<div id='mw-data-after-content'>\n" .
660 "\t$data\n" .
661 "</div>\n";
662 }
663 } else {
664 wfDebug( "Hook SkinAfterContent changed output processing.\n" );
665 }
666
667 return $data;
668 }
669
670 /**
671 * Generate debug data HTML for displaying at the bottom of the main content
672 * area.
673 * @return string HTML containing debug data, if enabled (otherwise empty).
674 */
675 protected function generateDebugHTML() {
676 return MWDebug::getHTMLDebugLog();
677 }
678
679 /**
680 * This gets called shortly before the "</body>" tag.
681 *
682 * @return string|WrappedStringList HTML containing scripts to put before `</body>`
683 */
684 function bottomScripts() {
685 // TODO and the suckage continues. This function is really just a wrapper around
686 // OutputPage::getBottomScripts() which takes a Skin param. This should be cleaned
687 // up at some point
688 $chunks = [ $this->getOutput()->getBottomScripts() ];
689
690 // Keep the hook appendage separate to preserve WrappedString objects.
691 // This enables BaseTemplate::getTrail() to merge them where possible.
692 $extraHtml = '';
693 Hooks::run( 'SkinAfterBottomScripts', [ $this, &$extraHtml ] );
694 if ( $extraHtml !== '' ) {
695 $chunks[] = $extraHtml;
696 }
697 return WrappedString::join( "\n", $chunks );
698 }
699
700 /**
701 * Text with the permalink to the source page,
702 * usually shown on the footer of a printed page
703 *
704 * @return string HTML text with an URL
705 */
706 function printSource() {
707 $oldid = $this->getOutput()->getRevisionId();
708 if ( $oldid ) {
709 $canonicalUrl = $this->getTitle()->getCanonicalURL( 'oldid=' . $oldid );
710 $url = htmlspecialchars( wfExpandIRI( $canonicalUrl ) );
711 } else {
712 // oldid not available for non existing pages
713 $url = htmlspecialchars( wfExpandIRI( $this->getTitle()->getCanonicalURL() ) );
714 }
715
716 return $this->msg( 'retrievedfrom' )
717 ->rawParams( '<a dir="ltr" href="' . $url . '">' . $url . '</a>' )
718 ->parse();
719 }
720
721 /**
722 * @return string HTML
723 */
724 function getUndeleteLink() {
725 $action = $this->getRequest()->getVal( 'action', 'view' );
726 $title = $this->getTitle();
727 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
728
729 if ( ( !$title->exists() || $action == 'history' ) &&
730 $title->quickUserCan( 'deletedhistory', $this->getUser() )
731 ) {
732 $n = $title->isDeleted();
733
734 if ( $n ) {
735 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
736 $msg = 'thisisdeleted';
737 } else {
738 $msg = 'viewdeleted';
739 }
740
741 $subtitle = $this->msg( $msg )->rawParams(
742 $linkRenderer->makeKnownLink(
743 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
744 $this->msg( 'restorelink' )->numParams( $n )->text() )
745 )->escaped();
746
747 // Allow extensions to add more links
748 $links = [];
749 Hooks::run( 'UndeletePageToolLinks', [ $this->getContext(), $linkRenderer, &$links ] );
750
751 if ( $links ) {
752 $subtitle .= ''
753 . $this->msg( 'word-separator' )->escaped()
754 . $this->msg( 'parentheses' )
755 ->rawParams( $this->getLanguage()->pipeList( $links ) )
756 ->escaped();
757 }
758 return Html::rawElement( 'div', [ 'class' => 'mw-undelete-subtitle' ], $subtitle );
759 }
760 }
761
762 return '';
763 }
764
765 /**
766 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
767 * @return string
768 */
769 function subPageSubtitle( $out = null ) {
770 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
771 if ( $out === null ) {
772 $out = $this->getOutput();
773 }
774 $title = $out->getTitle();
775 $subpages = '';
776
777 if ( !Hooks::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
778 return $subpages;
779 }
780
781 if (
782 $out->isArticle() && MediaWikiServices::getInstance()->getNamespaceInfo()->
783 hasSubpages( $title->getNamespace() )
784 ) {
785 $ptext = $title->getPrefixedText();
786 if ( strpos( $ptext, '/' ) !== false ) {
787 $links = explode( '/', $ptext );
788 array_pop( $links );
789 $c = 0;
790 $growinglink = '';
791 $display = '';
792 $lang = $this->getLanguage();
793
794 foreach ( $links as $link ) {
795 $growinglink .= $link;
796 $display .= $link;
797 $linkObj = Title::newFromText( $growinglink );
798
799 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
800 $getlink = $linkRenderer->makeKnownLink(
801 $linkObj, $display
802 );
803
804 $c++;
805
806 if ( $c > 1 ) {
807 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
808 } else {
809 $subpages .= '&lt; ';
810 }
811
812 $subpages .= $getlink;
813 $display = '';
814 } else {
815 $display .= '/';
816 }
817 $growinglink .= '/';
818 }
819 }
820 }
821
822 return $subpages;
823 }
824
825 /**
826 * @return string
827 */
828 function getSearchLink() {
829 $searchPage = SpecialPage::getTitleFor( 'Search' );
830 return $searchPage->getLocalURL();
831 }
832
833 /**
834 * @deprecated since 1.34, use getSearchLink() instead.
835 * @return string
836 */
837 function escapeSearchLink() {
838 wfDeprecated( __METHOD__, '1.34' );
839 return htmlspecialchars( $this->getSearchLink() );
840 }
841
842 /**
843 * @param string $type
844 * @return string
845 */
846 function getCopyright( $type = 'detect' ) {
847 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
848 if ( $type == 'detect' ) {
849 if ( !$this->getOutput()->isRevisionCurrent()
850 && !$this->msg( 'history_copyright' )->inContentLanguage()->isDisabled()
851 ) {
852 $type = 'history';
853 } else {
854 $type = 'normal';
855 }
856 }
857
858 if ( $type == 'history' ) {
859 $msg = 'history_copyright';
860 } else {
861 $msg = 'copyright';
862 }
863
864 $config = $this->getConfig();
865
866 if ( $config->get( 'RightsPage' ) ) {
867 $title = Title::newFromText( $config->get( 'RightsPage' ) );
868 $link = $linkRenderer->makeKnownLink(
869 $title, new HtmlArmor( $config->get( 'RightsText' ) )
870 );
871 } elseif ( $config->get( 'RightsUrl' ) ) {
872 $link = Linker::makeExternalLink( $config->get( 'RightsUrl' ), $config->get( 'RightsText' ) );
873 } elseif ( $config->get( 'RightsText' ) ) {
874 $link = $config->get( 'RightsText' );
875 } else {
876 # Give up now
877 return '';
878 }
879
880 // Allow for site and per-namespace customization of copyright notice.
881 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
882 $forContent = true;
883
884 Hooks::run(
885 'SkinCopyrightFooter',
886 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
887 );
888
889 return $this->msg( $msg )->rawParams( $link )->text();
890 }
891
892 /**
893 * @return null|string
894 */
895 function getCopyrightIcon() {
896 $out = '';
897 $config = $this->getConfig();
898
899 $footerIcons = $config->get( 'FooterIcons' );
900 if ( $footerIcons['copyright']['copyright'] ) {
901 $out = $footerIcons['copyright']['copyright'];
902 } elseif ( $config->get( 'RightsIcon' ) ) {
903 $icon = htmlspecialchars( $config->get( 'RightsIcon' ) );
904 $url = $config->get( 'RightsUrl' );
905
906 if ( $url ) {
907 $out .= '<a href="' . htmlspecialchars( $url ) . '">';
908 }
909
910 $text = htmlspecialchars( $config->get( 'RightsText' ) );
911 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
912
913 if ( $url ) {
914 $out .= '</a>';
915 }
916 }
917
918 return $out;
919 }
920
921 /**
922 * Gets the powered by MediaWiki icon.
923 * @return string
924 */
925 function getPoweredBy() {
926 $resourceBasePath = $this->getConfig()->get( 'ResourceBasePath' );
927 $url1 = htmlspecialchars(
928 "$resourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
929 );
930 $url1_5 = htmlspecialchars(
931 "$resourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
932 );
933 $url2 = htmlspecialchars(
934 "$resourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
935 );
936 $text = '<a href="https://www.mediawiki.org/"><img src="' . $url1
937 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
938 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
939 Hooks::run( 'SkinGetPoweredBy', [ &$text, $this ] );
940 return $text;
941 }
942
943 /**
944 * Get the timestamp of the latest revision, formatted in user language
945 *
946 * @return string
947 */
948 protected function lastModified() {
949 $timestamp = $this->getOutput()->getRevisionTimestamp();
950
951 # No cached timestamp, load it from the database
952 if ( $timestamp === null ) {
953 $timestamp = Revision::getTimestampFromId( $this->getTitle(),
954 $this->getOutput()->getRevisionId() );
955 }
956
957 if ( $timestamp ) {
958 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
959 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
960 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
961 } else {
962 $s = '';
963 }
964
965 if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
966 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
967 }
968
969 return $s;
970 }
971
972 /**
973 * @param string $align
974 * @return string
975 */
976 function logoText( $align = '' ) {
977 if ( $align != '' ) {
978 $a = " style='float: {$align};'";
979 } else {
980 $a = '';
981 }
982
983 $mp = $this->msg( 'mainpage' )->escaped();
984 $mptitle = Title::newMainPage();
985 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
986
987 $logourl = $this->getLogo();
988 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
989
990 return $s;
991 }
992
993 /**
994 * Renders a $wgFooterIcons icon according to the method's arguments
995 * @param array $icon The icon to build the html for, see $wgFooterIcons
996 * for the format of this array.
997 * @param bool|string $withImage Whether to use the icon's image or output
998 * a text-only footericon.
999 * @return string HTML
1000 */
1001 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
1002 if ( is_string( $icon ) ) {
1003 $html = $icon;
1004 } else { // Assuming array
1005 $url = $icon["url"] ?? null;
1006 unset( $icon["url"] );
1007 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
1008 // do this the lazy way, just pass icon data as an attribute array
1009 $html = Html::element( 'img', $icon );
1010 } else {
1011 $html = htmlspecialchars( $icon["alt"] );
1012 }
1013 if ( $url ) {
1014 $html = Html::rawElement( 'a',
1015 [ "href" => $url, "target" => $this->getConfig()->get( 'ExternalLinkTarget' ) ],
1016 $html );
1017 }
1018 }
1019 return $html;
1020 }
1021
1022 /**
1023 * Gets the link to the wiki's main page.
1024 * @return string
1025 */
1026 function mainPageLink() {
1027 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1028 $s = $linkRenderer->makeKnownLink(
1029 Title::newMainPage(),
1030 $this->msg( 'mainpage' )->text()
1031 );
1032
1033 return $s;
1034 }
1035
1036 /**
1037 * Returns an HTML link for use in the footer
1038 * @param string $desc The i18n message key for the link text
1039 * @param string $page The i18n message key for the page to link to
1040 * @return string HTML anchor
1041 */
1042 public function footerLink( $desc, $page ) {
1043 $title = $this->footerLinkTitle( $desc, $page );
1044 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1045 if ( !$title ) {
1046 return '';
1047 }
1048
1049 return $linkRenderer->makeKnownLink(
1050 $title,
1051 $this->msg( $desc )->text()
1052 );
1053 }
1054
1055 /**
1056 * @param string $desc
1057 * @param string $page
1058 * @return Title|null
1059 */
1060 private function footerLinkTitle( $desc, $page ) {
1061 // If the link description has been set to "-" in the default language,
1062 if ( $this->msg( $desc )->inContentLanguage()->isDisabled() ) {
1063 // then it is disabled, for all languages.
1064 return null;
1065 }
1066 // Otherwise, we display the link for the user, described in their
1067 // language (which may or may not be the same as the default language),
1068 // but we make the link target be the one site-wide page.
1069 $title = Title::newFromText( $this->msg( $page )->inContentLanguage()->text() );
1070
1071 return $title ?: null;
1072 }
1073
1074 /**
1075 * Gets the link to the wiki's privacy policy page.
1076 * @return string HTML
1077 */
1078 function privacyLink() {
1079 return $this->footerLink( 'privacy', 'privacypage' );
1080 }
1081
1082 /**
1083 * Gets the link to the wiki's about page.
1084 * @return string HTML
1085 */
1086 function aboutLink() {
1087 return $this->footerLink( 'aboutsite', 'aboutpage' );
1088 }
1089
1090 /**
1091 * Gets the link to the wiki's general disclaimers page.
1092 * @return string HTML
1093 */
1094 function disclaimerLink() {
1095 return $this->footerLink( 'disclaimers', 'disclaimerpage' );
1096 }
1097
1098 /**
1099 * Return URL options for the 'edit page' link.
1100 * This may include an 'oldid' specifier, if the current page view is such.
1101 *
1102 * @return array
1103 * @private
1104 */
1105 function editUrlOptions() {
1106 $options = [ 'action' => 'edit' ];
1107
1108 if ( !$this->getOutput()->isRevisionCurrent() ) {
1109 $options['oldid'] = intval( $this->getOutput()->getRevisionId() );
1110 }
1111
1112 return $options;
1113 }
1114
1115 /**
1116 * @param User|int $id
1117 * @return bool
1118 */
1119 function showEmailUser( $id ) {
1120 if ( $id instanceof User ) {
1121 $targetUser = $id;
1122 } else {
1123 $targetUser = User::newFromId( $id );
1124 }
1125
1126 # The sending user must have a confirmed email address and the receiving
1127 # user must accept emails from the sender.
1128 return $this->getUser()->canSendEmail()
1129 && SpecialEmailUser::validateTarget( $targetUser, $this->getUser() ) === '';
1130 }
1131
1132 /**
1133 * Return a fully resolved style path URL to images or styles stored in the
1134 * current skin's folder. This method returns a URL resolved using the
1135 * configured skin style path.
1136 *
1137 * Requires $stylename to be set, otherwise throws MWException.
1138 *
1139 * @param string $name The name or path of a skin resource file
1140 * @return string The fully resolved style path URL
1141 * @throws MWException
1142 */
1143 function getSkinStylePath( $name ) {
1144 if ( $this->stylename === null ) {
1145 $class = static::class;
1146 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1147 }
1148
1149 return $this->getConfig()->get( 'StylePath' ) . "/{$this->stylename}/$name";
1150 }
1151
1152 /* these are used extensively in SkinTemplate, but also some other places */
1153
1154 /**
1155 * @param string|string[] $urlaction
1156 * @return string
1157 */
1158 static function makeMainPageUrl( $urlaction = '' ) {
1159 $title = Title::newMainPage();
1160 self::checkTitle( $title, '' );
1161
1162 return $title->getLinkURL( $urlaction );
1163 }
1164
1165 /**
1166 * Make a URL for a Special Page using the given query and protocol.
1167 *
1168 * If $proto is set to null, make a local URL. Otherwise, make a full
1169 * URL with the protocol specified.
1170 *
1171 * @param string $name Name of the Special page
1172 * @param string|string[] $urlaction Query to append
1173 * @param string|null $proto Protocol to use or null for a local URL
1174 * @return string
1175 */
1176 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1177 $title = SpecialPage::getSafeTitleFor( $name );
1178 if ( is_null( $proto ) ) {
1179 return $title->getLocalURL( $urlaction );
1180 } else {
1181 return $title->getFullURL( $urlaction, false, $proto );
1182 }
1183 }
1184
1185 /**
1186 * @param string $name
1187 * @param string $subpage
1188 * @param string|string[] $urlaction
1189 * @return string
1190 */
1191 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1192 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1193 return $title->getLocalURL( $urlaction );
1194 }
1195
1196 /**
1197 * @param string $name
1198 * @param string|string[] $urlaction
1199 * @return string
1200 */
1201 static function makeI18nUrl( $name, $urlaction = '' ) {
1202 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1203 self::checkTitle( $title, $name );
1204 return $title->getLocalURL( $urlaction );
1205 }
1206
1207 /**
1208 * @param string $name
1209 * @param string|string[] $urlaction
1210 * @return string
1211 */
1212 static function makeUrl( $name, $urlaction = '' ) {
1213 $title = Title::newFromText( $name );
1214 self::checkTitle( $title, $name );
1215
1216 return $title->getLocalURL( $urlaction );
1217 }
1218
1219 /**
1220 * If url string starts with http, consider as external URL, else
1221 * internal
1222 * @param string $name
1223 * @return string URL
1224 */
1225 static function makeInternalOrExternalUrl( $name ) {
1226 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1227 return $name;
1228 } else {
1229 return self::makeUrl( $name );
1230 }
1231 }
1232
1233 /**
1234 * this can be passed the NS number as defined in Language.php
1235 * @param string $name
1236 * @param string|string[] $urlaction
1237 * @param int $namespace
1238 * @return string
1239 */
1240 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1241 $title = Title::makeTitleSafe( $namespace, $name );
1242 self::checkTitle( $title, $name );
1243
1244 return $title->getLocalURL( $urlaction );
1245 }
1246
1247 /**
1248 * these return an array with the 'href' and boolean 'exists'
1249 * @param string $name
1250 * @param string|string[] $urlaction
1251 * @return array
1252 */
1253 static function makeUrlDetails( $name, $urlaction = '' ) {
1254 $title = Title::newFromText( $name );
1255 self::checkTitle( $title, $name );
1256
1257 return [
1258 'href' => $title->getLocalURL( $urlaction ),
1259 'exists' => $title->isKnown(),
1260 ];
1261 }
1262
1263 /**
1264 * Make URL details where the article exists (or at least it's convenient to think so)
1265 * @param string $name Article name
1266 * @param string|string[] $urlaction
1267 * @return array
1268 */
1269 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1270 $title = Title::newFromText( $name );
1271 self::checkTitle( $title, $name );
1272
1273 return [
1274 'href' => $title->getLocalURL( $urlaction ),
1275 'exists' => true
1276 ];
1277 }
1278
1279 /**
1280 * make sure we have some title to operate on
1281 *
1282 * @param Title &$title
1283 * @param string $name
1284 */
1285 static function checkTitle( &$title, $name ) {
1286 if ( !is_object( $title ) ) {
1287 $title = Title::newFromText( $name );
1288 if ( !is_object( $title ) ) {
1289 $title = Title::newFromText( '--error: link target missing--' );
1290 }
1291 }
1292 }
1293
1294 /**
1295 * Build an array that represents the sidebar(s), the navigation bar among them.
1296 *
1297 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1298 *
1299 * The format of the returned array is [ heading => content, ... ], where:
1300 * - heading is the heading of a navigation portlet. It is either:
1301 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1302 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1303 * - plain text, which should be HTML-escaped by the skin
1304 * - content is the contents of the portlet. It is either:
1305 * - HTML text (<ul><li>...</li>...</ul>)
1306 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1307 * - (for a magic string as a key, any value)
1308 *
1309 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1310 * and can technically insert anything in here; skin creators are expected to handle
1311 * values described above.
1312 *
1313 * @return array
1314 */
1315 public function buildSidebar() {
1316 $services = MediaWikiServices::getInstance();
1317 $callback = function ( $old = null, &$ttl = null ) {
1318 $bar = [];
1319 $this->addToSidebar( $bar, 'sidebar' );
1320 Hooks::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1321 $msgCache = MediaWikiServices::getInstance()->getMessageCache();
1322 if ( $msgCache->isDisabled() ) {
1323 $ttl = WANObjectCache::TTL_UNCACHEABLE; // bug T133069
1324 }
1325
1326 return $bar;
1327 };
1328
1329 $msgCache = $services->getMessageCache();
1330 $wanCache = $services->getMainWANObjectCache();
1331 $config = $this->getConfig();
1332
1333 $sidebar = $config->get( 'EnableSidebarCache' )
1334 ? $wanCache->getWithSetCallback(
1335 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1336 $config->get( 'SidebarCacheExpiry' ),
1337 $callback,
1338 [
1339 'checkKeys' => [
1340 // Unless there is both no exact $code override nor an i18n definition
1341 // in the software, the only MediaWiki page to check is for $code.
1342 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1343 ],
1344 'lockTSE' => 30
1345 ]
1346 )
1347 : $callback();
1348
1349 // Apply post-processing to the cached value
1350 Hooks::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1351
1352 return $sidebar;
1353 }
1354
1355 /**
1356 * Add content from a sidebar system message
1357 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1358 *
1359 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1360 *
1361 * @param array &$bar
1362 * @param string $message
1363 */
1364 public function addToSidebar( &$bar, $message ) {
1365 $this->addToSidebarPlain( $bar, $this->msg( $message )->inContentLanguage()->plain() );
1366 }
1367
1368 /**
1369 * Add content from plain text
1370 * @since 1.17
1371 * @param array &$bar
1372 * @param string $text
1373 * @return array
1374 */
1375 function addToSidebarPlain( &$bar, $text ) {
1376 $lines = explode( "\n", $text );
1377
1378 $heading = '';
1379 $config = $this->getConfig();
1380 $messageTitle = $config->get( 'EnableSidebarCache' )
1381 ? Title::newMainPage() : $this->getTitle();
1382
1383 foreach ( $lines as $line ) {
1384 if ( strpos( $line, '*' ) !== 0 ) {
1385 continue;
1386 }
1387 $line = rtrim( $line, "\r" ); // for Windows compat
1388
1389 if ( strpos( $line, '**' ) !== 0 ) {
1390 $heading = trim( $line, '* ' );
1391 if ( !array_key_exists( $heading, $bar ) ) {
1392 $bar[$heading] = [];
1393 }
1394 } else {
1395 $line = trim( $line, '* ' );
1396
1397 if ( strpos( $line, '|' ) !== false ) { // sanity check
1398 $line = MessageCache::singleton()->transform( $line, false, null, $messageTitle );
1399 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1400 if ( count( $line ) !== 2 ) {
1401 // Second sanity check, could be hit by people doing
1402 // funky stuff with parserfuncs... (T35321)
1403 continue;
1404 }
1405
1406 $extraAttribs = [];
1407
1408 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1409 if ( $msgLink->exists() ) {
1410 $link = $msgLink->text();
1411 if ( $link == '-' ) {
1412 continue;
1413 }
1414 } else {
1415 $link = $line[0];
1416 }
1417 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1418 if ( $msgText->exists() ) {
1419 $text = $msgText->text();
1420 } else {
1421 $text = $line[1];
1422 }
1423
1424 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1425 $href = $link;
1426
1427 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1428 if ( $config->get( 'NoFollowLinks' ) &&
1429 !wfMatchesDomainList( $href, $config->get( 'NoFollowDomainExceptions' ) )
1430 ) {
1431 $extraAttribs['rel'] = 'nofollow';
1432 }
1433
1434 if ( $config->get( 'ExternalLinkTarget' ) ) {
1435 $extraAttribs['target'] = $config->get( 'ExternalLinkTarget' );
1436 }
1437 } else {
1438 $title = Title::newFromText( $link );
1439
1440 if ( $title ) {
1441 $title = $title->fixSpecialName();
1442 $href = $title->getLinkURL();
1443 } else {
1444 $href = 'INVALID-TITLE';
1445 }
1446 }
1447
1448 $bar[$heading][] = array_merge( [
1449 'text' => $text,
1450 'href' => $href,
1451 'id' => Sanitizer::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1452 'active' => false,
1453 ], $extraAttribs );
1454 } else {
1455 continue;
1456 }
1457 }
1458 }
1459
1460 return $bar;
1461 }
1462
1463 /**
1464 * Gets new talk page messages for the current user and returns an
1465 * appropriate alert message (or an empty string if there are no messages)
1466 * @return string
1467 */
1468 function getNewtalks() {
1469 $newMessagesAlert = '';
1470 $user = $this->getUser();
1471 $newtalks = $user->getNewMessageLinks();
1472 $out = $this->getOutput();
1473 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1474
1475 // Allow extensions to disable or modify the new messages alert
1476 if ( !Hooks::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1477 return '';
1478 }
1479 if ( $newMessagesAlert ) {
1480 return $newMessagesAlert;
1481 }
1482
1483 if ( count( $newtalks ) == 1 && WikiMap::isCurrentWikiId( $newtalks[0]['wiki'] ) ) {
1484 $uTalkTitle = $user->getTalkPage();
1485 $lastSeenRev = $newtalks[0]['rev'] ?? null;
1486 $nofAuthors = 0;
1487 if ( $lastSeenRev !== null ) {
1488 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1489 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1490 if ( $latestRev !== null ) {
1491 // Singular if only 1 unseen revision, plural if several unseen revisions.
1492 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1493 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1494 $lastSeenRev, $latestRev, 10, 'include_new' );
1495 }
1496 } else {
1497 // Singular if no revision -> diff link will show latest change only in any case
1498 $plural = false;
1499 }
1500 $plural = $plural ? 999 : 1;
1501 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1502 // the number of revisions or authors is not necessarily the same as the number of
1503 // "messages".
1504 $newMessagesLink = $linkRenderer->makeKnownLink(
1505 $uTalkTitle,
1506 $this->msg( 'newmessageslinkplural' )->params( $plural )->text(),
1507 [],
1508 $uTalkTitle->isRedirect() ? [ 'redirect' => 'no' ] : []
1509 );
1510
1511 $newMessagesDiffLink = $linkRenderer->makeKnownLink(
1512 $uTalkTitle,
1513 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->text(),
1514 [],
1515 $lastSeenRev !== null
1516 ? [ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1517 : [ 'diff' => 'cur' ]
1518 );
1519
1520 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1521 $newMessagesAlert = $this->msg(
1522 'youhavenewmessagesfromusers',
1523 $newMessagesLink,
1524 $newMessagesDiffLink
1525 )->numParams( $nofAuthors, $plural );
1526 } else {
1527 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1528 $newMessagesAlert = $this->msg(
1529 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1530 $newMessagesLink,
1531 $newMessagesDiffLink
1532 )->numParams( $plural );
1533 }
1534 $newMessagesAlert = $newMessagesAlert->text();
1535 # Disable CDN cache
1536 $out->setCdnMaxage( 0 );
1537 } elseif ( count( $newtalks ) ) {
1538 $sep = $this->msg( 'newtalkseparator' )->escaped();
1539 $msgs = [];
1540
1541 foreach ( $newtalks as $newtalk ) {
1542 $msgs[] = Xml::element(
1543 'a',
1544 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1545 );
1546 }
1547 $parts = implode( $sep, $msgs );
1548 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1549 $out->setCdnMaxage( 0 );
1550 }
1551
1552 return $newMessagesAlert;
1553 }
1554
1555 /**
1556 * Get a cached notice
1557 *
1558 * @param string $name Message name, or 'default' for $wgSiteNotice
1559 * @return string|bool HTML fragment, or false to indicate that the caller
1560 * should fall back to the next notice in its sequence
1561 */
1562 private function getCachedNotice( $name ) {
1563 $config = $this->getConfig();
1564
1565 if ( $name === 'default' ) {
1566 // special case
1567 $notice = $config->get( 'SiteNotice' );
1568 if ( empty( $notice ) ) {
1569 return false;
1570 }
1571 } else {
1572 $msg = $this->msg( $name )->inContentLanguage();
1573 if ( $msg->isBlank() ) {
1574 return '';
1575 } elseif ( $msg->isDisabled() ) {
1576 return false;
1577 }
1578 $notice = $msg->plain();
1579 }
1580
1581 $services = MediaWikiServices::getInstance();
1582 $cache = $services->getMainWANObjectCache();
1583 $parsed = $cache->getWithSetCallback(
1584 // Use the extra hash appender to let eg SSL variants separately cache
1585 // Key is verified with md5 hash of unparsed wikitext
1586 $cache->makeKey( $name, $config->get( 'RenderHashAppend' ), md5( $notice ) ),
1587 // TTL in seconds
1588 600,
1589 function () use ( $notice ) {
1590 return $this->getOutput()->parseAsInterface( $notice );
1591 }
1592 );
1593
1594 $contLang = $services->getContentLanguage();
1595 return Html::rawElement(
1596 'div',
1597 [
1598 'id' => 'localNotice',
1599 'lang' => $contLang->getHtmlCode(),
1600 'dir' => $contLang->getDir()
1601 ],
1602 $parsed
1603 );
1604 }
1605
1606 /**
1607 * Get the site notice
1608 *
1609 * @return string HTML fragment
1610 */
1611 function getSiteNotice() {
1612 $siteNotice = '';
1613
1614 if ( Hooks::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1615 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1616 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1617 } else {
1618 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1619 if ( $anonNotice === false ) {
1620 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1621 } else {
1622 $siteNotice = $anonNotice;
1623 }
1624 }
1625 if ( $siteNotice === false ) {
1626 $siteNotice = $this->getCachedNotice( 'default' );
1627 }
1628 }
1629
1630 Hooks::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1631 return $siteNotice;
1632 }
1633
1634 /**
1635 * Create a section edit link.
1636 *
1637 * @suppress SecurityCheck-XSS $links has keys of different taint types
1638 * @param Title $nt The title being linked to (may not be the same as
1639 * the current page, if the section is included from a template)
1640 * @param string $section The designation of the section being pointed to,
1641 * to be included in the link, like "&section=$section"
1642 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1643 * and wrapped in the 'editsectionhint' message
1644 * @param Language $lang Language object
1645 * @return string HTML to use for edit link
1646 */
1647 public function doEditSectionLink( Title $nt, $section, $tooltip, Language $lang ) {
1648 // HTML generated here should probably have userlangattributes
1649 // added to it for LTR text on RTL pages
1650
1651 $attribs = [];
1652 if ( !is_null( $tooltip ) ) {
1653 $attribs['title'] = $this->msg( 'editsectionhint' )->rawParams( $tooltip )
1654 ->inLanguage( $lang )->text();
1655 }
1656
1657 $links = [
1658 'editsection' => [
1659 'text' => $this->msg( 'editsection' )->inLanguage( $lang )->text(),
1660 'targetTitle' => $nt,
1661 'attribs' => $attribs,
1662 'query' => [ 'action' => 'edit', 'section' => $section ]
1663 ]
1664 ];
1665
1666 Hooks::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1667
1668 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1669
1670 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1671 $linksHtml = [];
1672 foreach ( $links as $k => $linkDetails ) {
1673 $linksHtml[] = $linkRenderer->makeKnownLink(
1674 $linkDetails['targetTitle'],
1675 $linkDetails['text'],
1676 $linkDetails['attribs'],
1677 $linkDetails['query']
1678 );
1679 }
1680
1681 $result .= implode(
1682 '<span class="mw-editsection-divider">'
1683 . $this->msg( 'pipe-separator' )->inLanguage( $lang )->escaped()
1684 . '</span>',
1685 $linksHtml
1686 );
1687
1688 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1689 return $result;
1690 }
1691
1692 }