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