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