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