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