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