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