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