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