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