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