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