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