Merge "language: Add generate-normalize-data maintenance script"
[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 'mediawiki.user',
200 ],
201 // modules that enhance the content in some way
202 'content' => [
203 'mediawiki.page.ready',
204 ],
205 // modules relating to search functionality
206 'search' => [],
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 $modules['search'][] = 'mediawiki.searchSuggest';
246
247 if ( $user->getBoolOption( 'editsectiononrightclick' ) ) {
248 $modules['user'][] = 'mediawiki.action.view.rightClickEdit';
249 }
250
251 // Crazy edit-on-double-click stuff
252 if ( $out->isArticle() && $user->getOption( 'editondblclick' ) ) {
253 $modules['user'][] = 'mediawiki.action.view.dblClickEdit';
254 }
255
256 if ( $out->isSyndicated() ) {
257 $modules['styles']['syndicate'][] = 'mediawiki.feedlink';
258 }
259
260 return $modules;
261 }
262
263 /**
264 * Preload the existence of three commonly-requested pages in a single query
265 */
266 protected function preloadExistence() {
267 $titles = [];
268
269 // User/talk link
270 $user = $this->getUser();
271 if ( $user->isLoggedIn() ) {
272 $titles[] = $user->getUserPage();
273 $titles[] = $user->getTalkPage();
274 }
275
276 // Check, if the page can hold some kind of content, otherwise do nothing
277 $title = $this->getRelevantTitle();
278 if ( $title->canExist() ) {
279 if ( $title->isTalkPage() ) {
280 $titles[] = $title->getSubjectPage();
281 } else {
282 $titles[] = $title->getTalkPage();
283 }
284 }
285
286 // Footer links (used by SkinTemplate::prepareQuickTemplate)
287 foreach ( [
288 $this->footerLinkTitle( 'privacy', 'privacypage' ),
289 $this->footerLinkTitle( 'aboutsite', 'aboutpage' ),
290 $this->footerLinkTitle( 'disclaimers', 'disclaimerpage' ),
291 ] as $title ) {
292 if ( $title ) {
293 $titles[] = $title;
294 }
295 }
296
297 Hooks::run( 'SkinPreloadExistence', [ &$titles, $this ] );
298
299 if ( $titles ) {
300 $lb = new LinkBatch( $titles );
301 $lb->setCaller( __METHOD__ );
302 $lb->execute();
303 }
304 }
305
306 /**
307 * Get the current revision ID
308 *
309 * @return int
310 */
311 public function getRevisionId() {
312 return $this->getOutput()->getRevisionId();
313 }
314
315 /**
316 * Whether the revision displayed is the latest revision of the page
317 *
318 * @return bool
319 */
320 public function isRevisionCurrent() {
321 $revID = $this->getRevisionId();
322 return $revID == 0 || $revID == $this->getTitle()->getLatestRevID();
323 }
324
325 /**
326 * Set the "relevant" title
327 * @see self::getRelevantTitle()
328 * @param Title $t
329 */
330 public function setRelevantTitle( $t ) {
331 $this->mRelevantTitle = $t;
332 }
333
334 /**
335 * Return the "relevant" title.
336 * A "relevant" title is not necessarily the actual title of the page.
337 * Special pages like Special:MovePage use set the page they are acting on
338 * as their "relevant" title, this allows the skin system to display things
339 * such as content tabs which belong to to that page instead of displaying
340 * a basic special page tab which has almost no meaning.
341 *
342 * @return Title
343 */
344 public function getRelevantTitle() {
345 if ( isset( $this->mRelevantTitle ) ) {
346 return $this->mRelevantTitle;
347 }
348 return $this->getTitle();
349 }
350
351 /**
352 * Set the "relevant" user
353 * @see self::getRelevantUser()
354 * @param User $u
355 */
356 public function setRelevantUser( $u ) {
357 $this->mRelevantUser = $u;
358 }
359
360 /**
361 * Return the "relevant" user.
362 * A "relevant" user is similar to a relevant title. Special pages like
363 * Special:Contributions mark the user which they are relevant to so that
364 * things like the toolbox can display the information they usually are only
365 * able to display on a user's userpage and talkpage.
366 * @return User
367 */
368 public function getRelevantUser() {
369 if ( isset( $this->mRelevantUser ) ) {
370 return $this->mRelevantUser;
371 }
372 $title = $this->getRelevantTitle();
373 if ( $title->hasSubjectNamespace( NS_USER ) ) {
374 $rootUser = $title->getRootText();
375 if ( User::isIP( $rootUser ) ) {
376 $this->mRelevantUser = User::newFromName( $rootUser, false );
377 } else {
378 $user = User::newFromName( $rootUser, false );
379
380 if ( $user ) {
381 $user->load( User::READ_NORMAL );
382
383 if ( $user->isLoggedIn() ) {
384 $this->mRelevantUser = $user;
385 }
386 }
387 }
388 return $this->mRelevantUser;
389 }
390 return null;
391 }
392
393 /**
394 * Outputs the HTML generated by other functions.
395 * @param OutputPage|null $out
396 */
397 abstract function outputPage( OutputPage $out = null );
398
399 /**
400 * @param array $data
401 * @param string|null $nonce OutputPage::getCSPNonce()
402 * @return string|WrappedString HTML
403 */
404 public static function makeVariablesScript( $data, $nonce = null ) {
405 if ( $data ) {
406 return ResourceLoader::makeInlineScript(
407 ResourceLoader::makeConfigSetScript( $data ),
408 $nonce
409 );
410 }
411 return '';
412 }
413
414 /**
415 * Get the query to generate a dynamic stylesheet
416 *
417 * @return array
418 */
419 public static function getDynamicStylesheetQuery() {
420 global $wgSquidMaxage;
421
422 return [
423 'action' => 'raw',
424 'maxage' => $wgSquidMaxage,
425 'usemsgcache' => 'yes',
426 'ctype' => 'text/css',
427 'smaxage' => $wgSquidMaxage,
428 ];
429 }
430
431 /**
432 * Hook point for adding style modules to OutputPage.
433 *
434 * @deprecated since 1.32 Use getDefaultModules() instead.
435 * @param OutputPage $out Legacy parameter, identical to $this->getOutput()
436 */
437 public function setupSkinUserCss( OutputPage $out ) {
438 // Stub.
439 }
440
441 /**
442 * TODO: document
443 * @param Title $title
444 * @return string
445 */
446 function getPageClasses( $title ) {
447 $numeric = 'ns-' . $title->getNamespace();
448
449 if ( $title->isSpecialPage() ) {
450 $type = 'ns-special';
451 // T25315: provide a class based on the canonical special page name without subpages
452 list( $canonicalName ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
453 if ( $canonicalName ) {
454 $type .= ' ' . Sanitizer::escapeClass( "mw-special-$canonicalName" );
455 } else {
456 $type .= ' mw-invalidspecialpage';
457 }
458 } elseif ( $title->isTalkPage() ) {
459 $type = 'ns-talk';
460 } else {
461 $type = 'ns-subject';
462 }
463
464 $name = Sanitizer::escapeClass( 'page-' . $title->getPrefixedText() );
465 $root = Sanitizer::escapeClass( 'rootpage-' . $title->getRootTitle()->getPrefixedText() );
466
467 return "$numeric $type $name $root";
468 }
469
470 /**
471 * Return values for <html> element
472 * @return array Array of associative name-to-value elements for <html> element
473 */
474 public function getHtmlElementAttributes() {
475 $lang = $this->getLanguage();
476 return [
477 'lang' => $lang->getHtmlCode(),
478 'dir' => $lang->getDir(),
479 'class' => 'client-nojs',
480 ];
481 }
482
483 /**
484 * This will be called by OutputPage::headElement when it is creating the
485 * "<body>" tag, skins can override it if they have a need to add in any
486 * body attributes or classes of their own.
487 * @param OutputPage $out
488 * @param array &$bodyAttrs
489 */
490 function addToBodyAttributes( $out, &$bodyAttrs ) {
491 // does nothing by default
492 }
493
494 /**
495 * URL to the logo
496 * @return string
497 */
498 function getLogo() {
499 global $wgLogo;
500 return $wgLogo;
501 }
502
503 /**
504 * Whether the logo should be preloaded with an HTTP link header or not
505 * @since 1.29
506 * @return bool
507 */
508 public function shouldPreloadLogo() {
509 return false;
510 }
511
512 /**
513 * @return string HTML
514 */
515 function getCategoryLinks() {
516 global $wgUseCategoryBrowser;
517
518 $out = $this->getOutput();
519 $allCats = $out->getCategoryLinks();
520
521 if ( !count( $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 = wfMessage( '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 ( $wgUseCategoryBrowser ) {
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
719 if ( $this->getTitle()->userCan( 'deletedhistory', $this->getUser() ) &&
720 ( !$this->getTitle()->exists() || $action == 'history' ) ) {
721 $n = $this->getTitle()->isDeleted();
722
723 if ( $n ) {
724 if ( $this->getTitle()->quickUserCan( 'undelete', $this->getUser() ) ) {
725 $msg = 'thisisdeleted';
726 } else {
727 $msg = 'viewdeleted';
728 }
729
730 return $this->msg( $msg )->rawParams(
731 Linker::linkKnown(
732 SpecialPage::getTitleFor( 'Undelete', $this->getTitle()->getPrefixedDBkey() ),
733 $this->msg( 'restorelink' )->numParams( $n )->escaped() )
734 )->escaped();
735 }
736 }
737
738 return '';
739 }
740
741 /**
742 * @param OutputPage|null $out Defaults to $this->getOutput() if left as null
743 * @return string
744 */
745 function subPageSubtitle( $out = null ) {
746 if ( $out === null ) {
747 $out = $this->getOutput();
748 }
749 $title = $out->getTitle();
750 $subpages = '';
751
752 if ( !Hooks::run( 'SkinSubPageSubtitle', [ &$subpages, $this, $out ] ) ) {
753 return $subpages;
754 }
755
756 if ( $out->isArticle() && MWNamespace::hasSubpages( $title->getNamespace() ) ) {
757 $ptext = $title->getPrefixedText();
758 if ( strpos( $ptext, '/' ) !== false ) {
759 $links = explode( '/', $ptext );
760 array_pop( $links );
761 $c = 0;
762 $growinglink = '';
763 $display = '';
764 $lang = $this->getLanguage();
765
766 foreach ( $links as $link ) {
767 $growinglink .= $link;
768 $display .= $link;
769 $linkObj = Title::newFromText( $growinglink );
770
771 if ( is_object( $linkObj ) && $linkObj->isKnown() ) {
772 $getlink = Linker::linkKnown(
773 $linkObj,
774 htmlspecialchars( $display )
775 );
776
777 $c++;
778
779 if ( $c > 1 ) {
780 $subpages .= $lang->getDirMarkEntity() . $this->msg( 'pipe-separator' )->escaped();
781 } else {
782 $subpages .= '&lt; ';
783 }
784
785 $subpages .= $getlink;
786 $display = '';
787 } else {
788 $display .= '/';
789 }
790 $growinglink .= '/';
791 }
792 }
793 }
794
795 return $subpages;
796 }
797
798 /**
799 * @return string
800 */
801 function getSearchLink() {
802 $searchPage = SpecialPage::getTitleFor( 'Search' );
803 return $searchPage->getLocalURL();
804 }
805
806 /**
807 * @return string
808 */
809 function escapeSearchLink() {
810 return htmlspecialchars( $this->getSearchLink() );
811 }
812
813 /**
814 * @param string $type
815 * @return string
816 */
817 function getCopyright( $type = 'detect' ) {
818 global $wgRightsPage, $wgRightsUrl, $wgRightsText;
819
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 if ( $wgRightsPage ) {
837 $title = Title::newFromText( $wgRightsPage );
838 $link = Linker::linkKnown( $title, $wgRightsText );
839 } elseif ( $wgRightsUrl ) {
840 $link = Linker::makeExternalLink( $wgRightsUrl, $wgRightsText );
841 } elseif ( $wgRightsText ) {
842 $link = $wgRightsText;
843 } else {
844 # Give up now
845 return '';
846 }
847
848 // Allow for site and per-namespace customization of copyright notice.
849 // @todo Remove deprecated $forContent param from hook handlers and then remove here.
850 $forContent = true;
851
852 Hooks::run(
853 'SkinCopyrightFooter',
854 [ $this->getTitle(), $type, &$msg, &$link, &$forContent ]
855 );
856
857 return $this->msg( $msg )->rawParams( $link )->text();
858 }
859
860 /**
861 * @return null|string
862 */
863 function getCopyrightIcon() {
864 global $wgRightsUrl, $wgRightsText, $wgRightsIcon, $wgFooterIcons;
865
866 $out = '';
867
868 if ( $wgFooterIcons['copyright']['copyright'] ) {
869 $out = $wgFooterIcons['copyright']['copyright'];
870 } elseif ( $wgRightsIcon ) {
871 $icon = htmlspecialchars( $wgRightsIcon );
872
873 if ( $wgRightsUrl ) {
874 $url = htmlspecialchars( $wgRightsUrl );
875 $out .= '<a href="' . $url . '">';
876 }
877
878 $text = htmlspecialchars( $wgRightsText );
879 $out .= "<img src=\"$icon\" alt=\"$text\" width=\"88\" height=\"31\" />";
880
881 if ( $wgRightsUrl ) {
882 $out .= '</a>';
883 }
884 }
885
886 return $out;
887 }
888
889 /**
890 * Gets the powered by MediaWiki icon.
891 * @return string
892 */
893 function getPoweredBy() {
894 global $wgResourceBasePath;
895
896 $url1 = htmlspecialchars(
897 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png"
898 );
899 $url1_5 = htmlspecialchars(
900 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png"
901 );
902 $url2 = htmlspecialchars(
903 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png"
904 );
905 $text = '<a href="//www.mediawiki.org/"><img src="' . $url1
906 . '" srcset="' . $url1_5 . ' 1.5x, ' . $url2 . ' 2x" '
907 . 'height="31" width="88" alt="Powered by MediaWiki" /></a>';
908 Hooks::run( 'SkinGetPoweredBy', [ &$text, $this ] );
909 return $text;
910 }
911
912 /**
913 * Get the timestamp of the latest revision, formatted in user language
914 *
915 * @return string
916 */
917 protected function lastModified() {
918 $timestamp = $this->getOutput()->getRevisionTimestamp();
919
920 # No cached timestamp, load it from the database
921 if ( $timestamp === null ) {
922 $timestamp = Revision::getTimestampFromId( $this->getTitle(), $this->getRevisionId() );
923 }
924
925 if ( $timestamp ) {
926 $d = $this->getLanguage()->userDate( $timestamp, $this->getUser() );
927 $t = $this->getLanguage()->userTime( $timestamp, $this->getUser() );
928 $s = ' ' . $this->msg( 'lastmodifiedat', $d, $t )->parse();
929 } else {
930 $s = '';
931 }
932
933 if ( MediaWikiServices::getInstance()->getDBLoadBalancer()->getLaggedReplicaMode() ) {
934 $s .= ' <strong>' . $this->msg( 'laggedslavemode' )->parse() . '</strong>';
935 }
936
937 return $s;
938 }
939
940 /**
941 * @param string $align
942 * @return string
943 */
944 function logoText( $align = '' ) {
945 if ( $align != '' ) {
946 $a = " style='float: {$align};'";
947 } else {
948 $a = '';
949 }
950
951 $mp = $this->msg( 'mainpage' )->escaped();
952 $mptitle = Title::newMainPage();
953 $url = ( is_object( $mptitle ) ? htmlspecialchars( $mptitle->getLocalURL() ) : '' );
954
955 $logourl = $this->getLogo();
956 $s = "<a href='{$url}'><img{$a} src='{$logourl}' alt='[{$mp}]' /></a>";
957
958 return $s;
959 }
960
961 /**
962 * Renders a $wgFooterIcons icon according to the method's arguments
963 * @param array $icon The icon to build the html for, see $wgFooterIcons
964 * for the format of this array.
965 * @param bool|string $withImage Whether to use the icon's image or output
966 * a text-only footericon.
967 * @return string HTML
968 */
969 function makeFooterIcon( $icon, $withImage = 'withImage' ) {
970 if ( is_string( $icon ) ) {
971 $html = $icon;
972 } else { // Assuming array
973 $url = $icon["url"] ?? null;
974 unset( $icon["url"] );
975 if ( isset( $icon["src"] ) && $withImage === 'withImage' ) {
976 // do this the lazy way, just pass icon data as an attribute array
977 $html = Html::element( 'img', $icon );
978 } else {
979 $html = htmlspecialchars( $icon["alt"] );
980 }
981 if ( $url ) {
982 global $wgExternalLinkTarget;
983 $html = Html::rawElement( 'a',
984 [ "href" => $url, "target" => $wgExternalLinkTarget ],
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 global $wgStylePath;
1112
1113 if ( $this->stylename === null ) {
1114 $class = static::class;
1115 throw new MWException( "$class::\$stylename must be set to use getSkinStylePath()" );
1116 }
1117
1118 return "$wgStylePath/{$this->stylename}/$name";
1119 }
1120
1121 /* these are used extensively in SkinTemplate, but also some other places */
1122
1123 /**
1124 * @param string|string[] $urlaction
1125 * @return string
1126 */
1127 static function makeMainPageUrl( $urlaction = '' ) {
1128 $title = Title::newMainPage();
1129 self::checkTitle( $title, '' );
1130
1131 return $title->getLinkURL( $urlaction );
1132 }
1133
1134 /**
1135 * Make a URL for a Special Page using the given query and protocol.
1136 *
1137 * If $proto is set to null, make a local URL. Otherwise, make a full
1138 * URL with the protocol specified.
1139 *
1140 * @param string $name Name of the Special page
1141 * @param string|string[] $urlaction Query to append
1142 * @param string|null $proto Protocol to use or null for a local URL
1143 * @return string
1144 */
1145 static function makeSpecialUrl( $name, $urlaction = '', $proto = null ) {
1146 $title = SpecialPage::getSafeTitleFor( $name );
1147 if ( is_null( $proto ) ) {
1148 return $title->getLocalURL( $urlaction );
1149 } else {
1150 return $title->getFullURL( $urlaction, false, $proto );
1151 }
1152 }
1153
1154 /**
1155 * @param string $name
1156 * @param string $subpage
1157 * @param string|string[] $urlaction
1158 * @return string
1159 */
1160 static function makeSpecialUrlSubpage( $name, $subpage, $urlaction = '' ) {
1161 $title = SpecialPage::getSafeTitleFor( $name, $subpage );
1162 return $title->getLocalURL( $urlaction );
1163 }
1164
1165 /**
1166 * @param string $name
1167 * @param string|string[] $urlaction
1168 * @return string
1169 */
1170 static function makeI18nUrl( $name, $urlaction = '' ) {
1171 $title = Title::newFromText( wfMessage( $name )->inContentLanguage()->text() );
1172 self::checkTitle( $title, $name );
1173 return $title->getLocalURL( $urlaction );
1174 }
1175
1176 /**
1177 * @param string $name
1178 * @param string|string[] $urlaction
1179 * @return string
1180 */
1181 static function makeUrl( $name, $urlaction = '' ) {
1182 $title = Title::newFromText( $name );
1183 self::checkTitle( $title, $name );
1184
1185 return $title->getLocalURL( $urlaction );
1186 }
1187
1188 /**
1189 * If url string starts with http, consider as external URL, else
1190 * internal
1191 * @param string $name
1192 * @return string URL
1193 */
1194 static function makeInternalOrExternalUrl( $name ) {
1195 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $name ) ) {
1196 return $name;
1197 } else {
1198 return self::makeUrl( $name );
1199 }
1200 }
1201
1202 /**
1203 * this can be passed the NS number as defined in Language.php
1204 * @param string $name
1205 * @param string|string[] $urlaction
1206 * @param int $namespace
1207 * @return string
1208 */
1209 static function makeNSUrl( $name, $urlaction = '', $namespace = NS_MAIN ) {
1210 $title = Title::makeTitleSafe( $namespace, $name );
1211 self::checkTitle( $title, $name );
1212
1213 return $title->getLocalURL( $urlaction );
1214 }
1215
1216 /**
1217 * these return an array with the 'href' and boolean 'exists'
1218 * @param string $name
1219 * @param string|string[] $urlaction
1220 * @return array
1221 */
1222 static function makeUrlDetails( $name, $urlaction = '' ) {
1223 $title = Title::newFromText( $name );
1224 self::checkTitle( $title, $name );
1225
1226 return [
1227 'href' => $title->getLocalURL( $urlaction ),
1228 'exists' => $title->isKnown(),
1229 ];
1230 }
1231
1232 /**
1233 * Make URL details where the article exists (or at least it's convenient to think so)
1234 * @param string $name Article name
1235 * @param string|string[] $urlaction
1236 * @return array
1237 */
1238 static function makeKnownUrlDetails( $name, $urlaction = '' ) {
1239 $title = Title::newFromText( $name );
1240 self::checkTitle( $title, $name );
1241
1242 return [
1243 'href' => $title->getLocalURL( $urlaction ),
1244 'exists' => true
1245 ];
1246 }
1247
1248 /**
1249 * make sure we have some title to operate on
1250 *
1251 * @param Title &$title
1252 * @param string $name
1253 */
1254 static function checkTitle( &$title, $name ) {
1255 if ( !is_object( $title ) ) {
1256 $title = Title::newFromText( $name );
1257 if ( !is_object( $title ) ) {
1258 $title = Title::newFromText( '--error: link target missing--' );
1259 }
1260 }
1261 }
1262
1263 /**
1264 * Build an array that represents the sidebar(s), the navigation bar among them.
1265 *
1266 * BaseTemplate::getSidebar can be used to simplify the format and id generation in new skins.
1267 *
1268 * The format of the returned array is [ heading => content, ... ], where:
1269 * - heading is the heading of a navigation portlet. It is either:
1270 * - magic string to be handled by the skins ('SEARCH' / 'LANGUAGES' / 'TOOLBOX' / ...)
1271 * - a message name (e.g. 'navigation'), the message should be HTML-escaped by the skin
1272 * - plain text, which should be HTML-escaped by the skin
1273 * - content is the contents of the portlet. It is either:
1274 * - HTML text (<ul><li>...</li>...</ul>)
1275 * - array of link data in a format accepted by BaseTemplate::makeListItem()
1276 * - (for a magic string as a key, any value)
1277 *
1278 * Note that extensions can control the sidebar contents using the SkinBuildSidebar hook
1279 * and can technically insert anything in here; skin creators are expected to handle
1280 * values described above.
1281 *
1282 * @return array
1283 */
1284 public function buildSidebar() {
1285 global $wgEnableSidebarCache, $wgSidebarCacheExpiry;
1286
1287 $callback = function ( $old = null, &$ttl = null ) {
1288 $bar = [];
1289 $this->addToSidebar( $bar, 'sidebar' );
1290 Hooks::run( 'SkinBuildSidebar', [ $this, &$bar ] );
1291 if ( MessageCache::singleton()->isDisabled() ) {
1292 $ttl = WANObjectCache::TTL_UNCACHEABLE; // bug T133069
1293 }
1294
1295 return $bar;
1296 };
1297
1298 $msgCache = MessageCache::singleton();
1299 $wanCache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1300
1301 $sidebar = $wgEnableSidebarCache
1302 ? $wanCache->getWithSetCallback(
1303 $wanCache->makeKey( 'sidebar', $this->getLanguage()->getCode() ),
1304 $wgSidebarCacheExpiry,
1305 $callback,
1306 [
1307 'checkKeys' => [
1308 // Unless there is both no exact $code override nor an i18n definition
1309 // in the software, the only MediaWiki page to check is for $code.
1310 $msgCache->getCheckKey( $this->getLanguage()->getCode() )
1311 ],
1312 'lockTSE' => 30
1313 ]
1314 )
1315 : $callback();
1316
1317 // Apply post-processing to the cached value
1318 Hooks::run( 'SidebarBeforeOutput', [ $this, &$sidebar ] );
1319
1320 return $sidebar;
1321 }
1322
1323 /**
1324 * Add content from a sidebar system message
1325 * Currently only used for MediaWiki:Sidebar (but may be used by Extensions)
1326 *
1327 * This is just a wrapper around addToSidebarPlain() for backwards compatibility
1328 *
1329 * @param array &$bar
1330 * @param string $message
1331 */
1332 public function addToSidebar( &$bar, $message ) {
1333 $this->addToSidebarPlain( $bar, wfMessage( $message )->inContentLanguage()->plain() );
1334 }
1335
1336 /**
1337 * Add content from plain text
1338 * @since 1.17
1339 * @param array &$bar
1340 * @param string $text
1341 * @return array
1342 */
1343 function addToSidebarPlain( &$bar, $text ) {
1344 $lines = explode( "\n", $text );
1345
1346 $heading = '';
1347 $messageTitle = $this->getConfig()->get( 'EnableSidebarCache' )
1348 ? Title::newMainPage() : $this->getTitle();
1349
1350 foreach ( $lines as $line ) {
1351 if ( strpos( $line, '*' ) !== 0 ) {
1352 continue;
1353 }
1354 $line = rtrim( $line, "\r" ); // for Windows compat
1355
1356 if ( strpos( $line, '**' ) !== 0 ) {
1357 $heading = trim( $line, '* ' );
1358 if ( !array_key_exists( $heading, $bar ) ) {
1359 $bar[$heading] = [];
1360 }
1361 } else {
1362 $line = trim( $line, '* ' );
1363
1364 if ( strpos( $line, '|' ) !== false ) { // sanity check
1365 $line = MessageCache::singleton()->transform( $line, false, null, $messageTitle );
1366 $line = array_map( 'trim', explode( '|', $line, 2 ) );
1367 if ( count( $line ) !== 2 ) {
1368 // Second sanity check, could be hit by people doing
1369 // funky stuff with parserfuncs... (T35321)
1370 continue;
1371 }
1372
1373 $extraAttribs = [];
1374
1375 $msgLink = $this->msg( $line[0] )->title( $messageTitle )->inContentLanguage();
1376 if ( $msgLink->exists() ) {
1377 $link = $msgLink->text();
1378 if ( $link == '-' ) {
1379 continue;
1380 }
1381 } else {
1382 $link = $line[0];
1383 }
1384 $msgText = $this->msg( $line[1] )->title( $messageTitle );
1385 if ( $msgText->exists() ) {
1386 $text = $msgText->text();
1387 } else {
1388 $text = $line[1];
1389 }
1390
1391 if ( preg_match( '/^(?i:' . wfUrlProtocols() . ')/', $link ) ) {
1392 $href = $link;
1393
1394 // Parser::getExternalLinkAttribs won't work here because of the Namespace things
1395 global $wgNoFollowLinks, $wgNoFollowDomainExceptions;
1396 if ( $wgNoFollowLinks && !wfMatchesDomainList( $href, $wgNoFollowDomainExceptions ) ) {
1397 $extraAttribs['rel'] = 'nofollow';
1398 }
1399
1400 global $wgExternalLinkTarget;
1401 if ( $wgExternalLinkTarget ) {
1402 $extraAttribs['target'] = $wgExternalLinkTarget;
1403 }
1404 } else {
1405 $title = Title::newFromText( $link );
1406
1407 if ( $title ) {
1408 $title = $title->fixSpecialName();
1409 $href = $title->getLinkURL();
1410 } else {
1411 $href = 'INVALID-TITLE';
1412 }
1413 }
1414
1415 $bar[$heading][] = array_merge( [
1416 'text' => $text,
1417 'href' => $href,
1418 'id' => Sanitizer::escapeIdForAttribute( 'n-' . strtr( $line[1], ' ', '-' ) ),
1419 'active' => false,
1420 ], $extraAttribs );
1421 } else {
1422 continue;
1423 }
1424 }
1425 }
1426
1427 return $bar;
1428 }
1429
1430 /**
1431 * Gets new talk page messages for the current user and returns an
1432 * appropriate alert message (or an empty string if there are no messages)
1433 * @return string
1434 */
1435 function getNewtalks() {
1436 $newMessagesAlert = '';
1437 $user = $this->getUser();
1438 $newtalks = $user->getNewMessageLinks();
1439 $out = $this->getOutput();
1440
1441 // Allow extensions to disable or modify the new messages alert
1442 if ( !Hooks::run( 'GetNewMessagesAlert', [ &$newMessagesAlert, $newtalks, $user, $out ] ) ) {
1443 return '';
1444 }
1445 if ( $newMessagesAlert ) {
1446 return $newMessagesAlert;
1447 }
1448
1449 if ( count( $newtalks ) == 1 && $newtalks[0]['wiki'] === wfWikiID() ) {
1450 $uTalkTitle = $user->getTalkPage();
1451 $lastSeenRev = $newtalks[0]['rev'] ?? null;
1452 $nofAuthors = 0;
1453 if ( $lastSeenRev !== null ) {
1454 $plural = true; // Default if we have a last seen revision: if unknown, use plural
1455 $latestRev = Revision::newFromTitle( $uTalkTitle, false, Revision::READ_NORMAL );
1456 if ( $latestRev !== null ) {
1457 // Singular if only 1 unseen revision, plural if several unseen revisions.
1458 $plural = $latestRev->getParentId() !== $lastSeenRev->getId();
1459 $nofAuthors = $uTalkTitle->countAuthorsBetween(
1460 $lastSeenRev, $latestRev, 10, 'include_new' );
1461 }
1462 } else {
1463 // Singular if no revision -> diff link will show latest change only in any case
1464 $plural = false;
1465 }
1466 $plural = $plural ? 999 : 1;
1467 // 999 signifies "more than one revision". We don't know how many, and even if we did,
1468 // the number of revisions or authors is not necessarily the same as the number of
1469 // "messages".
1470 $newMessagesLink = Linker::linkKnown(
1471 $uTalkTitle,
1472 $this->msg( 'newmessageslinkplural' )->params( $plural )->escaped(),
1473 [],
1474 [ 'redirect' => 'no' ]
1475 );
1476
1477 $newMessagesDiffLink = Linker::linkKnown(
1478 $uTalkTitle,
1479 $this->msg( 'newmessagesdifflinkplural' )->params( $plural )->escaped(),
1480 [],
1481 $lastSeenRev !== null
1482 ? [ 'oldid' => $lastSeenRev->getId(), 'diff' => 'cur' ]
1483 : [ 'diff' => 'cur' ]
1484 );
1485
1486 if ( $nofAuthors >= 1 && $nofAuthors <= 10 ) {
1487 $newMessagesAlert = $this->msg(
1488 'youhavenewmessagesfromusers',
1489 $newMessagesLink,
1490 $newMessagesDiffLink
1491 )->numParams( $nofAuthors, $plural );
1492 } else {
1493 // $nofAuthors === 11 signifies "11 or more" ("more than 10")
1494 $newMessagesAlert = $this->msg(
1495 $nofAuthors > 10 ? 'youhavenewmessagesmanyusers' : 'youhavenewmessages',
1496 $newMessagesLink,
1497 $newMessagesDiffLink
1498 )->numParams( $plural );
1499 }
1500 $newMessagesAlert = $newMessagesAlert->text();
1501 # Disable CDN cache
1502 $out->setCdnMaxage( 0 );
1503 } elseif ( count( $newtalks ) ) {
1504 $sep = $this->msg( 'newtalkseparator' )->escaped();
1505 $msgs = [];
1506
1507 foreach ( $newtalks as $newtalk ) {
1508 $msgs[] = Xml::element(
1509 'a',
1510 [ 'href' => $newtalk['link'] ], $newtalk['wiki']
1511 );
1512 }
1513 $parts = implode( $sep, $msgs );
1514 $newMessagesAlert = $this->msg( 'youhavenewmessagesmulti' )->rawParams( $parts )->escaped();
1515 $out->setCdnMaxage( 0 );
1516 }
1517
1518 return $newMessagesAlert;
1519 }
1520
1521 /**
1522 * Get a cached notice
1523 *
1524 * @param string $name Message name, or 'default' for $wgSiteNotice
1525 * @return string|bool HTML fragment, or false to indicate that the caller
1526 * should fall back to the next notice in its sequence
1527 */
1528 private function getCachedNotice( $name ) {
1529 global $wgRenderHashAppend;
1530
1531 $needParse = false;
1532
1533 if ( $name === 'default' ) {
1534 // special case
1535 global $wgSiteNotice;
1536 $notice = $wgSiteNotice;
1537 if ( empty( $notice ) ) {
1538 return false;
1539 }
1540 } else {
1541 $msg = $this->msg( $name )->inContentLanguage();
1542 if ( $msg->isBlank() ) {
1543 return '';
1544 } elseif ( $msg->isDisabled() ) {
1545 return false;
1546 }
1547 $notice = $msg->plain();
1548 }
1549
1550 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
1551 $parsed = $cache->getWithSetCallback(
1552 // Use the extra hash appender to let eg SSL variants separately cache
1553 // Key is verified with md5 hash of unparsed wikitext
1554 $cache->makeKey( $name, $wgRenderHashAppend, md5( $notice ) ),
1555 // TTL in seconds
1556 600,
1557 function () use ( $notice ) {
1558 return $this->getOutput()->parse( $notice );
1559 }
1560 );
1561
1562 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1563 return Html::rawElement(
1564 'div',
1565 [
1566 'id' => 'localNotice',
1567 'lang' => $contLang->getHtmlCode(),
1568 'dir' => $contLang->getDir()
1569 ],
1570 $parsed
1571 );
1572 }
1573
1574 /**
1575 * Get the site notice
1576 *
1577 * @return string HTML fragment
1578 */
1579 function getSiteNotice() {
1580 $siteNotice = '';
1581
1582 if ( Hooks::run( 'SiteNoticeBefore', [ &$siteNotice, $this ] ) ) {
1583 if ( is_object( $this->getUser() ) && $this->getUser()->isLoggedIn() ) {
1584 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1585 } else {
1586 $anonNotice = $this->getCachedNotice( 'anonnotice' );
1587 if ( $anonNotice === false ) {
1588 $siteNotice = $this->getCachedNotice( 'sitenotice' );
1589 } else {
1590 $siteNotice = $anonNotice;
1591 }
1592 }
1593 if ( $siteNotice === false ) {
1594 $siteNotice = $this->getCachedNotice( 'default' );
1595 }
1596 }
1597
1598 Hooks::run( 'SiteNoticeAfter', [ &$siteNotice, $this ] );
1599 return $siteNotice;
1600 }
1601
1602 /**
1603 * Create a section edit link.
1604 *
1605 * @param Title $nt The title being linked to (may not be the same as
1606 * the current page, if the section is included from a template)
1607 * @param string $section The designation of the section being pointed to,
1608 * to be included in the link, like "&section=$section"
1609 * @param string|null $tooltip The tooltip to use for the link: will be escaped
1610 * and wrapped in the 'editsectionhint' message
1611 * @param string $lang Language code
1612 * @return string HTML to use for edit link
1613 */
1614 public function doEditSectionLink( Title $nt, $section, $tooltip = null, $lang = false ) {
1615 // HTML generated here should probably have userlangattributes
1616 // added to it for LTR text on RTL pages
1617
1618 $lang = wfGetLangObj( $lang );
1619
1620 $attribs = [];
1621 if ( !is_null( $tooltip ) ) {
1622 $attribs['title'] = wfMessage( 'editsectionhint' )->rawParams( $tooltip )
1623 ->inLanguage( $lang )->text();
1624 }
1625
1626 $links = [
1627 'editsection' => [
1628 'text' => wfMessage( 'editsection' )->inLanguage( $lang )->escaped(),
1629 'targetTitle' => $nt,
1630 'attribs' => $attribs,
1631 'query' => [ 'action' => 'edit', 'section' => $section ],
1632 'options' => [ 'noclasses', 'known' ]
1633 ]
1634 ];
1635
1636 Hooks::run( 'SkinEditSectionLinks', [ $this, $nt, $section, $tooltip, &$links, $lang ] );
1637
1638 $result = '<span class="mw-editsection"><span class="mw-editsection-bracket">[</span>';
1639
1640 $linksHtml = [];
1641 foreach ( $links as $k => $linkDetails ) {
1642 $linksHtml[] = Linker::link(
1643 $linkDetails['targetTitle'],
1644 $linkDetails['text'],
1645 $linkDetails['attribs'],
1646 $linkDetails['query'],
1647 $linkDetails['options']
1648 );
1649 }
1650
1651 $result .= implode(
1652 '<span class="mw-editsection-divider">'
1653 . wfMessage( 'pipe-separator' )->inLanguage( $lang )->escaped()
1654 . '</span>',
1655 $linksHtml
1656 );
1657
1658 $result .= '<span class="mw-editsection-bracket">]</span></span>';
1659 // Deprecated, use SkinEditSectionLinks hook instead
1660 Hooks::run(
1661 'DoEditSectionLink',
1662 [ $this, $nt, $section, $tooltip, &$result, $lang ],
1663 '1.25'
1664 );
1665 return $result;
1666 }
1667
1668 }