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