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