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