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