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