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