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