Debian Codegraph @

skins/MinervaNeue/includes/Skins/SkinMinerva.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Minerva\Skins;
22
23 use MediaWiki\Cache\GenderCache;
24 use MediaWiki\Extension\Notifications\Controller\NotificationController;
25 use MediaWiki\Html\Html;
26 use MediaWiki\Language\Language;
27 use MediaWiki\Linker\LinkRenderer;
28 use MediaWiki\Linker\LinkTarget;
29 use MediaWiki\Minerva\LanguagesHelper;
30 use MediaWiki\Minerva\Menu\Definitions;
31 use MediaWiki\Minerva\Menu\Main\AdvancedMainMenuBuilder;
32 use MediaWiki\Minerva\Menu\Main\DefaultMainMenuBuilder;
33 use MediaWiki\Minerva\Menu\Main\MainMenuDirector;
34 use MediaWiki\Minerva\Menu\PageActions\PageActions;
35 use MediaWiki\Minerva\Menu\User\AdvancedUserMenuBuilder;
36 use MediaWiki\Minerva\Menu\User\DefaultUserMenuBuilder;
37 use MediaWiki\Minerva\Menu\User\UserMenuDirector;
38 use MediaWiki\Minerva\Permissions\IMinervaPagePermissions;
39 use MediaWiki\Minerva\Permissions\MinervaPagePermissions;
40 use MediaWiki\Minerva\SkinOptions;
41 use MediaWiki\Registration\ExtensionRegistry;
42 use MediaWiki\Revision\RevisionLookup;
43 use MediaWiki\SpecialPage\SpecialPage;
44 use MediaWiki\Title\NamespaceInfo;
45 use MediaWiki\Title\Title;
46 use MediaWiki\User\Options\UserOptionsManager;
47 use MediaWiki\User\UserIdentityUtils;
48 use MediaWiki\Utils\MWTimestamp;
49 use RuntimeException;
50 use SkinMustache;
51 use SkinTemplate;
52 use SpecialMobileHistory;
53
54 /**
55 * Minerva: Born from the godhead of Jupiter with weapons!
56 * A skin that works on both desktop and mobile
57 * @ingroup Skins
58 */
59 class SkinMinerva extends SkinMustache {
60 /** @const LEAD_SECTION_NUMBER integer which corresponds to the lead section
61 * in editing mode
62 */
63 public const LEAD_SECTION_NUMBER = 0;
64
65 /** @var string Name of this skin */
66 public $skinname = 'minerva';
67 /** @var string Name of this used template */
68 public $template = 'MinervaTemplate';
69
70 /** @var array|null */
71 private ?array $contentNavigationUrls;
72
73 private GenderCache $genderCache;
74 private LinkRenderer $linkRenderer;
75 private LanguagesHelper $languagesHelper;
76 private Definitions $definitions;
77 private PageActions $pageActions;
78 private IMinervaPagePermissions $permissions;
79 private SkinOptions $skinOptions;
80 private SkinUserPageHelper $skinUserPageHelper;
81 private NamespaceInfo $namespaceInfo;
82 private RevisionLookup $revisionLookup;
83 private UserIdentityUtils $userIdentityUtils;
84 private UserOptionsManager $userOptionsManager;
85
86 /**
87 * @param GenderCache $genderCache
88 * @param LinkRenderer $linkRenderer
89 * @param LanguagesHelper $languagesHelper
90 * @param Definitions $definitions
91 * @param PageActions $pageActions
92 * @param MinervaPagePermissions $permissions
93 * @param SkinOptions $skinOptions
94 * @param SkinUserPageHelper $skinUserPageHelper
95 * @param NamespaceInfo $namespaceInfo
96 * @param RevisionLookup $revisionLookup
97 * @param UserIdentityUtils $userIdentityUtils
98 * @param UserOptionsManager $userOptionsManager
99 * @param array $options
100 */
101 public function __construct(
102 GenderCache $genderCache,
103 LinkRenderer $linkRenderer,
104 LanguagesHelper $languagesHelper,
105 Definitions $definitions,
106 PageActions $pageActions,
107 MinervaPagePermissions $permissions,
108 SkinOptions $skinOptions,
109 SkinUserPageHelper $skinUserPageHelper,
110 NamespaceInfo $namespaceInfo,
111 RevisionLookup $revisionLookup,
112 UserIdentityUtils $userIdentityUtils,
113 UserOptionsManager $userOptionsManager,
114 $options = []
115 ) {
116 parent::__construct( $options );
117 $this->genderCache = $genderCache;
118 $this->linkRenderer = $linkRenderer;
119 $this->languagesHelper = $languagesHelper;
120 $this->definitions = $definitions
121 ->setContext( $this->getContext() );
122 $this->pageActions = $pageActions;
123 $this->permissions = $permissions
124 ->setContext( $this->getContext() );
125 $this->skinOptions = $skinOptions;
126 $this->skinUserPageHelper = $skinUserPageHelper
127 ->setContext( $this->getContext() )
128 ->setTitle( $this->getTitle() );
129 $this->namespaceInfo = $namespaceInfo;
130 $this->revisionLookup = $revisionLookup;
131 $this->userIdentityUtils = $userIdentityUtils;
132 $this->userOptionsManager = $userOptionsManager;
133 }
134
135 /**
136 * @return bool
137 */
138 private function hasPageActions(): bool {
139 $title = $this->getTitle();
140 return !$title->isSpecialPage() && !$title->isMainPage() &&
141 $this->getActionName() === 'view';
142 }
143
144 /**
145 * @return bool
146 */
147 private function hasSecondaryActions(): bool {
148 return !$this->skinUserPageHelper->isUserPage();
149 }
150
151 /**
152 * @return bool
153 */
154 private function isFallbackEditor(): bool {
155 return $this->getActionName() === 'edit';
156 }
157
158 /**
159 * Returns available page actions if the page has any.
160 *
161 * @param array $nav result of SkinTemplate::buildContentNavigationUrls
162 * @return array|null
163 */
164 private function getPageActions( array $nav ): ?array {
165 if ( $this->isFallbackEditor() || !$this->hasPageActions() ) {
166 return null;
167 }
168
169 $pageActionsDirector = $this->pageActions->getPageActionsDirector( $this->getContext() );
170 $sidebar = $this->buildSidebar();
171 $actions = $nav['actions'] ?? [];
172 $views = $nav['views'] ?? [];
173 return $pageActionsDirector->buildMenu( $sidebar['TOOLBOX'], $actions, $views );
174 }
175
176 /**
177 * A notification icon that links to Special:Mytalk when Echo is not installed.
178 * Consider upstreaming this to core or removing at a future date.
179 *
180 * @return array
181 */
182 private function getNotificationFallbackButton(): array {
183 return [
184 'icon' => 'bellOutline',
185 'href' => SpecialPage::getTitleFor( 'Mytalk' )->getLocalURL(
186 [ 'returnto' => $this->getTitle()->getPrefixedText() ]
187 ),
188 ];
189 }
190
191 /**
192 * @param array $alert
193 * @param array $notice
194 * @return array
195 */
196 private function getCombinedNotificationButton( array $alert, array $notice ): array {
197 // Start by just copying alert data
198 $combinedNotification = $alert;
199 // Sum the notifications from the two original buttons
200 $notifCount = ( $alert['data']['counter-num'] ?? 0 ) + ( $notice['data']['counter-num'] ?? 0 );
201 $combinedNotification['data']['counter-num'] = $notifCount;
202 // @phan-suppress-next-line PhanUndeclaredClassReference
203 if ( class_exists( NotificationController::class ) ) {
204 $combinedNotification['data']['counter-text'] =
205 // @phan-suppress-next-line PhanUndeclaredClassMethod
206 NotificationController::formatNotificationCount( $notifCount );
207 } else {
208 $combinedNotification['data']['counter-text'] = $notifCount;
209 }
210 // This text is not shown, but re-use the counter text for accessibility.
211 $combinedNotification['text'] = $alert['data']['counter-text'];
212
213 $linkClassAlert = $alert['link-class'] ?? [];
214 $linkClassNotice = $notice['link-class'] ?? [];
215 $hasUnseenAlerts = is_array( $linkClassAlert ) &&
216 in_array( 'mw-echo-unseen-notifications', $linkClassAlert );
217 $hasUnseenNotices = is_array( $linkClassNotice ) &&
218 in_array( 'mw-echo-unseen-notifications', $linkClassNotice );
219 // The circle should only appear if there are unseen notifications.
220 // Once the notifications are seen (by opening the notification drawer)
221 // then the icon reverts to a gray circle, but on page refresh
222 // it should revert back to a bell icon.
223 // If you try and change this behaviour, at time of writing
224 // (December 2022) JavaScript will correct it.
225 if ( $notifCount > 0 && ( $hasUnseenAlerts || $hasUnseenNotices ) ) {
226 return $this->getNotificationCircleButton( $combinedNotification );
227 } else {
228 return $this->getNotificationButton( $combinedNotification );
229 }
230 }
231
232 /**
233 * Minerva differs from other skins in that for users with unread notifications
234 * instead of a bell with a small square indicating the number of notifications
235 * it shows a red circle with a number inside. Ideally Vector and Minerva would
236 * be treated the same but we'd need to talk to a designer about consolidating these
237 * before making such a decision.
238 *
239 * @param array $notification
240 * @return array
241 */
242 private function getNotificationCircleButton( array $notification ): array {
243 $notification['icon'] = 'circle';
244 $linkClass = $notification['link-class'] ?? [];
245 $linkClass[] = 'notification-count';
246 $linkClass[] = 'notification-unseen';
247 $linkClass[] = 'mw-echo-unseen-notifications';
248 $notification['link-class'] = $linkClass;
249 return $notification;
250 }
251
252 /**
253 * Removes the OOUI icon class and adds Minerva notification classes.
254 *
255 * @param array $notification
256 * @return array
257 */
258 private function getNotificationButton( array $notification ): array {
259 $linkClass = $notification['link-class'];
260 $notification['link-class'] = array_filter(
261 $linkClass,
262 static function ( $class ) {
263 return $class !== 'oo-ui-icon-bellOutline';
264 }
265 );
266 $notification['icon'] = 'bellOutline';
267 return $notification;
268 }
269
270 /**
271 * Caches content navigation urls locally for use inside getTemplateData
272 *
273 * @inheritDoc
274 */
275 protected function runOnSkinTemplateNavigationHooks( SkinTemplate $skin, &$contentNavigationUrls ) {
276 parent::runOnSkinTemplateNavigationHooks( $skin, $contentNavigationUrls );
277 // There are some SkinTemplate modifications that occur after the execution of this hook
278 // to add rel attributes and ID attributes.
279 // The only one Minerva needs is this one so we manually add it.
280 foreach ( array_keys( $contentNavigationUrls['associated-pages'] ) as $id ) {
281 if ( in_array( $id, [ 'user_talk', 'talk' ] ) ) {
282 $contentNavigationUrls['associated-pages'][ $id ]['rel'] = 'discussion';
283 }
284 }
285 $this->contentNavigationUrls = $contentNavigationUrls;
286
287 //
288 // Echo Technical debt!!
289 // * Convert the Echo button into a single button
290 // * Switch out the icon.
291 //
292 if ( $this->getUser()->isRegistered() ) {
293 if ( count( $contentNavigationUrls['notifications'] ) === 0 ) {
294 // Shown to logged in users when Echo is not installed:
295 $contentNavigationUrls['notifications']['mytalks'] = $this->getNotificationFallbackButton();
296 } elseif ( $this->skinOptions->get( SkinOptions::SINGLE_ECHO_BUTTON ) ) {
297 // Combine notification icons. Minerva only shows one entry point to notifications.
298 // This can be reconsidered with a solution to https://phabricator.wikimedia.org/T142981
299 $alert = $contentNavigationUrls['notifications']['notifications-alert'] ?? null;
300 $notice = $contentNavigationUrls['notifications']['notifications-notice'] ?? null;
301 if ( $alert && $notice ) {
302 unset( $contentNavigationUrls['notifications']['notifications-notice'] );
303 $contentNavigationUrls['notifications']['notifications-alert'] =
304 $this->getCombinedNotificationButton( $alert, $notice );
305 }
306 } else {
307 // Show desktop alert icon.
308 $alert = $contentNavigationUrls['notifications']['notifications-alert'] ?? null;
309 if ( $alert ) {
310 // Correct the icon to be the bell filled rather than the outline to match
311 // Echo's badge.
312 $linkClass = $alert['link-class'] ?? [];
313 $alert['link-class'] = array_filter( $linkClass, static function ( $class ) {
314 return $class !== 'oo-ui-icon-bellOutline';
315 } );
316 $contentNavigationUrls['notifications']['notifications-alert'] = $alert;
317 }
318 }
319 }
320 }
321
322 /**
323 * @inheritDoc
324 */
325 public function getTemplateData(): array {
326 $data = parent::getTemplateData();
327 // FIXME: Can we use $data instead of calling buildContentNavigationUrls ?
328 $nav = $this->contentNavigationUrls;
329 if ( $nav === null ) {
330 throw new RuntimeException( 'contentNavigationUrls was not set as expected.' );
331 }
332 if ( !$this->hasCategoryLinks() ) {
333 unset( $data['html-categories'] );
334 }
335
336 // Special handling for certain pages.
337 // This is technical debt that should be upstreamed to core.
338 $isUserPage = $this->skinUserPageHelper->isUserPage();
339 $isUserPageAccessible = $this->skinUserPageHelper->isUserPageAccessibleToCurrentUser();
340 if ( $isUserPage && $isUserPageAccessible ) {
341 $data['html-title-heading'] = $this->getUserPageHeadingHtml( $data['html-title-heading' ] );
342 }
343
344 $usermessage = $data['html-user-message'] ?? '';
345 if ( $usermessage ) {
346 $data['html-user-message'] = Html::warningBox(
347 '<span class="minerva-icon minerva-icon--userTalk-warning"></span>&nbsp;'
348 . $usermessage,
349 'minerva-anon-talk-message'
350 );
351 }
352 $allLanguages = $data['data-portlets']['data-languages']['array-items'] ?? [];
353 $allVariants = $data['data-portlets']['data-variants']['array-items'] ?? [];
354 $notifications = $data['data-portlets']['data-notifications']['array-items'] ?? [];
355 $associatedPages = $data['data-portlets']['data-associated-pages'] ?? [];
356
357 return $data + [
358 'has-minerva-languages' => $allLanguages || $allVariants,
359 'array-minerva-banners' => $this->prepareBanners( $data['html-site-notice'] ),
360 'data-minerva-search-box' => $data['data-search-box'] + [
361 'data-btn' => [
362 'data-icon' => [
363 'icon' => 'search',
364 ],
365 'label' => $this->msg( 'searchbutton' )->escaped(),
366 'classes' => 'skin-minerva-search-trigger',
367 'array-attributes' => [
368 [
369 'key' => 'id',
370 'value' => 'searchIcon',
371 ]
372 ]
373 ],
374 ],
375 'data-minerva-main-menu-btn' => [
376 'data-icon' => [
377 'icon' => 'menu',
378 ],
379 'tag-name' => 'label',
380 'classes' => 'toggle-list__toggle',
381 'array-attributes' => [
382 [
383 'key' => 'for',
384 'value' => 'main-menu-input',
385 ],
386 [
387 'key' => 'id',
388 'value' => 'mw-mf-main-menu-button',
389 ],
390 [
391 'key' => 'aria-hidden',
392 'value' => 'true',
393 ],
394 [
395 'key' => 'data-event-name',
396 'value' => 'ui.mainmenu',
397 ],
398 ],
399 'text' => $this->msg( 'mobile-frontend-main-menu-button-tooltip' )->escaped(),
400 ],
401 'data-minerva-main-menu' => $this->getMainMenu()->getMenuData(
402 $nav,
403 $this->buildSidebar()
404 )['items'],
405 'html-minerva-tagline' => $this->getTaglineHtml(),
406 'html-minerva-user-menu' => $this->getPersonalToolsMenu( $nav['user-menu'] ),
407 'is-minerva-beta' => $this->skinOptions->get( SkinOptions::BETA_MODE ),
408 'data-minerva-notifications' => $notifications ? [
409 'array-buttons' => $this->getNotificationButtons( $notifications ),
410 ] : null,
411 'data-minerva-tabs' => $this->getTabsData( $nav, $associatedPages ),
412 'data-minerva-page-actions' => $this->getPageActions( $nav ),
413 'data-minerva-secondary-actions' => $this->getSecondaryActions( $nav ),
414 'html-minerva-subject-link' => $this->getSubjectPage(),
415 'data-minerva-history-link' => $this->getHistoryLink( $this->getTitle() ),
416 ];
417 }
418
419 /**
420 * Prepares the notification badges for the Button template.
421 *
422 * @internal
423 * @param array $notifications
424 * @return array
425 */
426 public static function getNotificationButtons( array $notifications ): array {
427 $btns = [];
428
429 foreach ( $notifications as $notification ) {
430 $linkData = $notification['array-links'][ 0 ] ?? [];
431 $icon = $linkData['icon'] ?? null;
432 if ( !$icon ) {
433 continue;
434 }
435 $id = $notification['id'] ?? null;
436 $classes = '';
437 $attributes = [];
438
439 // We don't want to output multiple attributes.
440 // Iterate through the attributes and pull out ID and class which
441 // will be defined separately.
442 foreach ( $linkData[ 'array-attributes' ] as $keyValuePair ) {
443 if ( $keyValuePair['key'] === 'class' ) {
444 $classes = $keyValuePair['value'];
445 } elseif ( $keyValuePair['key'] === 'id' ) {
446 // ignore. We want to use the LI `id` instead.
447 } else {
448 $attributes[] = $keyValuePair;
449 }
450 }
451 // add LI ID to end for use on the button.
452 if ( $id ) {
453 $attributes[] = [
454 'key' => 'id',
455 'value' => $id,
456 ];
457 }
458 $btns[] = [
459 'tag-name' => 'a',
460 // FIXME: Move preg_replace when Echo no longer provides this class.
461 'classes' => preg_replace( '/oo-ui-icon-(bellOutline|tray)/', '', $classes ),
462 'array-attributes' => $attributes,
463 'data-icon' => [
464 'icon' => $icon,
465 ],
466 'label' => $linkData['text'] ?? '',
467 ];
468 }
469 return $btns;
470 }
471
472 /**
473 * @return bool
474 */
475 private function isHistoryPage(): bool {
476 return $this->getRequest()->getRawVal( 'action' ) === 'history';
477 }
478
479 /**
480 * Tabs are available if a page has page actions but is not the talk page of
481 * the main page.
482 *
483 * Special pages have tabs if SkinOptions::TABS_ON_SPECIALS is enabled.
484 * This is used by Extension:GrowthExperiments
485 *
486 * @return bool
487 */
488 private function hasPageTabs(): bool {
489 $title = $this->getTitle();
490 $isSpecialPageOrHistory = $title->isSpecialPage() ||
491 $this->isHistoryPage();
492 $subjectPage = $this->namespaceInfo->getSubjectPage( $title );
493 $isMainPageTalk = Title::newFromLinkTarget( $subjectPage )->isMainPage();
494 return (
495 $this->hasPageActions() && !$isMainPageTalk &&
496 $this->skinOptions->get( SkinOptions::TALK_AT_TOP )
497 ) || (
498 $isSpecialPageOrHistory &&
499 $this->skinOptions->get( SkinOptions::TABS_ON_SPECIALS )
500 );
501 }
502
503 /**
504 * @param array $contentNavigationUrls
505 * @param array $associatedPages - data-associated-pages from template data, currently only used for ID
506 * @return array
507 */
508 private function getTabsData( array $contentNavigationUrls, array $associatedPages ): array {
509 $hasPageTabs = $this->hasPageTabs();
510 if ( !$hasPageTabs ) {
511 return [];
512 }
513 return $contentNavigationUrls ? [
514 'items' => array_values( $contentNavigationUrls['associated-pages'] ),
515 'id' => $associatedPages['id'] ?? null,
516 ] : [];
517 }
518
519 /**
520 * Build the Main Menu Director by passing the skin options
521 *
522 * @return MainMenuDirector
523 */
524 protected function getMainMenu(): MainMenuDirector {
525 $showMobileOptions = $this->skinOptions->get( SkinOptions::MOBILE_OPTIONS );
526 // Add a donate link (see https://phabricator.wikimedia.org/T219793)
527 $showDonateLink = $this->skinOptions->get( SkinOptions::SHOW_DONATE );
528 $builder = $this->skinOptions->get( SkinOptions::MAIN_MENU_EXPANDED ) ?
529 new AdvancedMainMenuBuilder(
530 $showMobileOptions,
531 $showDonateLink,
532 $this->definitions
533 ) :
534 new DefaultMainMenuBuilder(
535 $showMobileOptions,
536 $showDonateLink,
537 $this->getUser(),
538 $this->definitions,
539 $this->userIdentityUtils
540 );
541 return new MainMenuDirector( $builder );
542 }
543
544 /**
545 * Prepare all Minerva menus
546 *
547 * @param array $personalUrls result of SkinTemplate::buildPersonalUrls
548 * @return string|null
549 */
550 private function getPersonalToolsMenu( array $personalUrls ): ?string {
551 $builder = $this->skinOptions->get( SkinOptions::PERSONAL_MENU ) ?
552 new AdvancedUserMenuBuilder(
553 $this->getContext(),
554 $this->getUser(),
555 $this->definitions
556 ) :
557 new DefaultUserMenuBuilder();
558
559 $userMenuDirector = new UserMenuDirector(
560 $builder,
561 $this->getSkin()
562 );
563 return $userMenuDirector->renderMenuData( $personalUrls );
564 }
565
566 /**
567 * @return string
568 */
569 protected function getSubjectPage(): string {
570 $title = $this->getTitle();
571
572 // If it's a talk page, add a link to the main namespace page
573 // In AMC we do not need to do this as there is an easy way back to the article page
574 // via the talk/article tabs.
575 if ( $title->isTalkPage() && !$this->skinOptions->get( SkinOptions::TALK_AT_TOP ) ) {
576 // if it's a talk page for which we have a special message, use it
577 switch ( $title->getNamespace() ) {
578 case NS_USER_TALK:
579 $msg = 'mobile-frontend-talk-back-to-userpage';
580 break;
581 case NS_PROJECT_TALK:
582 $msg = 'mobile-frontend-talk-back-to-projectpage';
583 break;
584 case NS_FILE_TALK:
585 $msg = 'mobile-frontend-talk-back-to-filepage';
586 break;
587 default:
588 // generic (all other NS)
589 $msg = 'mobile-frontend-talk-back-to-page';
590 }
591 $subjectPage = $this->namespaceInfo->getSubjectPage( $title );
592
593 return $this->linkRenderer->makeLink(
594 $subjectPage,
595 $this->msg( $msg, $title->getText() )->text(),
596 [
597 'data-event-name' => 'talk.returnto',
598 'class' => 'return-link'
599 ]
600 );
601 } else {
602 return '';
603 }
604 }
605
606 /**
607 * Modifies the template data before parsing in SkinMustache.
608 *
609 * @inheritDoc
610 */
611 final protected function doEditSectionLinksHTML( array $links, Language $lang ): string {
612 $transformedLinks = [];
613 foreach ( $links as $key => $link ) {
614 $transformedLinks[] = $link + [
615 'data-icon' => [
616 'icon' => $link['icon'],
617 ],
618 ];
619 }
620 return parent::doEditSectionLinksHTML( $transformedLinks, $lang );
621 }
622
623 /**
624 * Takes a title and returns classes to apply to the body tag
625 * @param Title $title
626 * @return string
627 */
628 public function getPageClasses( $title ): string {
629 $className = parent::getPageClasses( $title );
630 $className .= ' ' . ( $this->skinOptions->get( SkinOptions::BETA_MODE )
631 ? 'beta' : 'stable' );
632
633 if ( $this->getUser()->isRegistered() ) {
634 $className .= ' is-authenticated';
635 }
636
637 // The new treatment should only apply to the main namespace
638 if (
639 $title->getNamespace() === NS_MAIN &&
640 $this->skinOptions->get( SkinOptions::PAGE_ISSUES )
641 ) {
642 $className .= ' issues-group-B';
643 }
644
645 return $className;
646 }
647
648 /**
649 * Converts "1", "2", and "0" to equivalent values.
650 *
651 * @return string
652 */
653 private static function resolveNightModeQueryValue( string $value ): string {
654 switch ( $value ) {
655 case 'day':
656 case 'night':
657 case 'os':
658 return $value;
659 case '1':
660 return 'night';
661 case '2':
662 return 'os';
663 default:
664 return 'day';
665 }
666 }
667
668 /**
669 * Provides skin-specific modifications to the HTML element attributes
670 *
671 * Currently only used for adding the night mode class
672 *
673 * @return array
674 */
675 public function getHtmlElementAttributes(): array {
676 $attributes = parent::getHtmlElementAttributes();
677
678 // check to see if night mode is enabled via query params or by config
679 $webRequest = $this->getRequest();
680 $forceNightMode = $webRequest->getRawVal( 'minervanightmode' );
681
682 // get skin config of night mode to check what is execluded
683 $nightModeConfig = $this->getConfig()->get( 'MinervaNightModeOptions' );
684 $featuresHelper = new FeaturesHelper();
685 $shouldDisableNightMode = $featuresHelper->shouldDisableNightMode( $nightModeConfig,
686 $webRequest,
687 $this->getTitle()
688 );
689
690 if (
691 $this->skinOptions->get( SkinOptions::NIGHT_MODE ) || $forceNightMode !== null
692 ) {
693 $user = $this->getUser();
694 $value = $this->userOptionsManager->getOption( $user, 'minerva-theme' );
695
696 // if forcing a (valid) setting via query params, take priority over the user option
697 if ( $forceNightMode !== null && in_array( $forceNightMode, [ '1', '0', '2', 'day', 'night', 'os' ] ) ) {
698 $value = self::resolveNightModeQueryValue( $forceNightMode );
699 }
700
701 // For T356653 add a class to the page to allow the client to detect we've
702 // intentionally disabled night mode.
703 if ( $shouldDisableNightMode ) {
704 $attributes[ 'class' ] .= ' skin-night-mode-page-disabled';
705 return $attributes;
706 }
707
708 $attributes[ 'class' ] .= " skin-theme-clientpref-$value";
709 }
710
711 return $attributes;
712 }
713
714 /**
715 * Whether the output page contains category links and the category feature is enabled.
716 * @return bool
717 */
718 private function hasCategoryLinks(): bool {
719 if ( !$this->skinOptions->get( SkinOptions::CATEGORIES ) ) {
720 return false;
721 }
722 $categoryLinks = $this->getOutput()->getCategoryLinks();
723
724 if ( !count( $categoryLinks ) ) {
725 return false;
726 }
727 return !empty( $categoryLinks['normal'] ) || !empty( $categoryLinks['hidden'] );
728 }
729
730 /**
731 * Get a history link which describes author and relative time of last edit
732 * @param Title $title The Title object of the page being viewed
733 * @param string $timestamp
734 * @return array
735 */
736 protected function getRelativeHistoryLink( Title $title, string $timestamp ): array {
737 $user = $this->getUser();
738 $userDate = $this->getLanguage()->userDate( $timestamp, $user );
739 $text = $this->msg(
740 'minerva-last-modified-date', $userDate,
741 $this->getLanguage()->userTime( $timestamp, $user )
742 )->parse();
743 return [
744 // Use $edit['timestamp'] (Unix format) instead of $timestamp (MW format)
745 'data-timestamp' => wfTimestamp( TS_UNIX, $timestamp ),
746 'href' => $this->getHistoryUrl( $title ),
747 'text' => $text,
748 ] + $this->getRevisionEditorData( $title );
749 }
750
751 /**
752 * Get a history link which makes no reference to user or last edited time
753 * @param Title $title The Title object of the page being viewed
754 * @return array
755 */
756 protected function getGenericHistoryLink( Title $title ): array {
757 $text = $this->msg( 'mobile-frontend-history' )->plain();
758 return [
759 'href' => $this->getHistoryUrl( $title ),
760 'text' => $text,
761 ];
762 }
763
764 /**
765 * Checks if the Special:History page is being used.
766 * @param Title $title The Title object of the page being viewed
767 * @return bool
768 */
769 private function shouldUseSpecialHistory( Title $title ): bool {
770 return ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' ) &&
771 SpecialMobileHistory::shouldUseSpecialHistory( $title, $this->getUser() );
772 }
773
774 /**
775 * Get the URL for the history page for the given title using Special:History
776 * when available.
777 * @param Title $title The Title object of the page being viewed
778 * @return string
779 */
780 protected function getHistoryUrl( Title $title ): string {
781 return $this->shouldUseSpecialHistory( $title ) ?
782 SpecialPage::getTitleFor( 'History', $title )->getLocalURL() :
783 $title->getLocalURL( [ 'action' => 'history' ] );
784 }
785
786 /**
787 * Prepare the content for the 'last edited' message, e.g. 'Last edited on 30 August
788 * 2013, at 23:31'. This message is different for the main page since main page
789 * content is typically transcluded rather than edited directly.
790 *
791 * The relative time is only rendered on the latest revision.
792 * For older revisions the last modified information will not render with a relative time
793 * nor will it show the name of the editor.
794 * @param Title $title The Title object of the page being viewed
795 * @return array|null
796 */
797 protected function getHistoryLink( Title $title ): ?array {
798 if ( !$title->exists() ||
799 $this->getActionName() !== 'view'
800 ) {
801 return null;
802 }
803 // Do not show the last modified bar on diff pages [T350515]
804 $request = $this->getRequest();
805 if ( $request->getCheck( 'diff' ) ) {
806 return null;
807 }
808
809 $out = $this->getOutput();
810
811 if ( !$out->getRevisionId() || !$out->isRevisionCurrent() || $title->isMainPage() ) {
812 $historyLink = $this->getGenericHistoryLink( $title );
813 } else {
814 // Get rev_timestamp of current revision (preloaded by MediaWiki core)
815 $timestamp = $out->getRevisionTimestamp();
816 if ( !$timestamp ) {
817 # No cached timestamp, load it from the database
818 $timestamp = $this->revisionLookup->getTimestampFromId( $out->getRevisionId() );
819 }
820 $historyLink = $this->getRelativeHistoryLink( $title, $timestamp );
821 }
822
823 return $historyLink + [
824 'historyIcon' => [
825 'icon' => 'modified-history',
826 'size' => 'medium'
827 ],
828 'arrowIcon' => [
829 'icon' => 'expand',
830 'size' => 'small'
831 ]
832 ];
833 }
834
835 /**
836 * Returns data attributes representing the editor for the current revision.
837 * @param LinkTarget $title The Title object of the page being viewed
838 * @return array representing user with name and gender fields. Empty if the editor no longer
839 * exists in the database or is hidden from public view.
840 */
841 private function getRevisionEditorData( LinkTarget $title ): array {
842 $rev = $this->revisionLookup->getRevisionByTitle( $title );
843 $result = [];
844 if ( $rev ) {
845 $revUser = $rev->getUser();
846 // Note the user will only be returned if that information is public
847 if ( $revUser ) {
848 $editorName = $revUser->getName();
849 $editorGender = $this->genderCache->getGenderOf( $revUser, __METHOD__ );
850 $result += [
851 'data-user-name' => $editorName,
852 'data-user-gender' => $editorGender,
853 ];
854 }
855 }
856 return $result;
857 }
858
859 /**
860 * Returns the HTML representing the tagline
861 * @return string HTML for tagline
862 */
863 protected function getTaglineHtml(): string {
864 $tagline = '';
865
866 $pageUser = $this->skinUserPageHelper->getPageUser();
867 if ( $pageUser ) {
868 $fromDate = $pageUser->getRegistration();
869
870 if ( $this->skinUserPageHelper->isUserPageAccessibleToCurrentUser() && is_string( $fromDate ) ) {
871 $fromDateTs = wfTimestamp( TS_UNIX, $fromDate );
872
873 // This is shown when js is disabled. js enhancement made due to caching
874 $tagline = $this->msg( 'mobile-frontend-user-page-member-since',
875 $this->getLanguage()->userDate( new MWTimestamp( $fromDateTs ), $this->getUser() ),
876 $pageUser )->text();
877
878 // Define html attributes for usage with js enhancement (unix timestamp, gender)
879 $attrs = [ 'id' => 'tagline-userpage',
880 'data-userpage-registration-date' => $fromDateTs,
881 'data-userpage-gender' => $this->genderCache->getGenderOf( $pageUser, __METHOD__ ) ];
882 }
883 } else {
884 if ( $this->getTitle() ) {
885 $out = $this->getOutput();
886 $tagline = $out->getProperty( 'wgMFDescription' );
887 }
888 }
889
890 $attrs[ 'class' ] = 'tagline';
891 return Html::element( 'div', $attrs, $tagline );
892 }
893
894 /**
895 * Returns the HTML representing the heading.
896 *
897 * @param string $heading The heading suggested by core.
898 * @return string HTML for header
899 */
900 private function getUserPageHeadingHtml( string $heading ): string {
901 // The heading is just the username without namespace
902 return Html::element( 'h1',
903 // These IDs and classes should match Skin::getTemplateData
904 [
905 'id' => 'firstHeading',
906 'class' => 'firstHeading mw-first-heading mw-minerva-user-heading',
907 ],
908 $this->skinUserPageHelper->getPageUser()->getName()
909 );
910 }
911
912 /**
913 * Load internal banner content to show in pre content in template
914 * Beware of HTML caching when using this function.
915 * Content set as "internalbanner"
916 * @param string $siteNotice HTML fragment
917 * @return array
918 */
919 protected function prepareBanners( string $siteNotice ): array {
920 $banners = [];
921 if ( $siteNotice && $this->getConfig()->get( 'MinervaEnableSiteNotice' ) ) {
922 $banners[] = $siteNotice;
923 } else {
924 $banners[] = '<div id="siteNotice"></div>';
925 }
926 return $banners;
927 }
928
929 /**
930 * Returns an array with details for a language button.
931 * @return array
932 */
933 protected function getLanguageButton(): array {
934 return [
935 'array-attributes' => [
936 [
937 'key' => 'href',
938 'value' => '#p-lang'
939 ]
940 ],
941 'tag-name' => 'a',
942 'classes' => 'language-selector button',
943 'label' => $this->msg( 'mobile-frontend-language-article-heading' )->text()
944 ];
945 }
946
947 /**
948 * Returns an array with details for a talk button.
949 * @param Title $talkTitle Title object of the talk page
950 * @param string $label Button label
951 * @return array
952 */
953 protected function getTalkButton( Title $talkTitle, string $label ): array {
954 return [
955 'array-attributes' => [
956 [
957 'key' => 'href',
958 'value' => $talkTitle->getLinkURL(),
959 ],
960 [
961 'key' => 'data-title',
962 'value' => $talkTitle->getFullText(),
963 ]
964 ],
965 'tag-name' => 'a',
966 'classes' => 'talk button',
967 'label' => $label,
968 ];
969 }
970
971 /**
972 * Returns an array of links for page secondary actions
973 * @param array $contentNavigationUrls
974 * @return array|null
975 */
976 protected function getSecondaryActions( array $contentNavigationUrls ): ?array {
977 if ( $this->isFallbackEditor() || !$this->hasSecondaryActions() ) {
978 return null;
979 }
980
981 $buttons = [];
982 // always add a button to link to the talk page
983 // it will link to the wikitext talk page
984 $title = $this->getTitle();
985 $subjectPage = Title::newFromLinkTarget( $this->namespaceInfo->getSubjectPage( $title ) );
986 $talkAtBottom = !$this->skinOptions->get( SkinOptions::TALK_AT_TOP ) ||
987 $subjectPage->isMainPage();
988 if ( !$this->skinUserPageHelper->isUserPage() &&
989 $this->permissions->isTalkAllowed() && $talkAtBottom &&
990 // When showing talk at the bottom we restrict this so it is not shown to anons
991 // https://phabricator.wikimedia.org/T54165
992 // This whole code block can be removed when SkinOptions::TALK_AT_TOP is always true
993 $this->getUser()->isRegistered()
994 ) {
995 $namespaces = $contentNavigationUrls['associated-pages'];
996 // FIXME [core]: This seems unnecessary..
997 $subjectId = $title->getNamespaceKey( '' );
998 $talkId = $subjectId === 'main' ? 'talk' : "{$subjectId}_talk";
999
1000 if ( isset( $namespaces[$talkId] ) ) {
1001 $talkButton = $namespaces[$talkId];
1002 $talkTitle = Title::newFromLinkTarget( $this->namespaceInfo->getTalkPage( $title ) );
1003
1004 $buttons['talk'] = $this->getTalkButton( $talkTitle, $talkButton['text'] );
1005 }
1006 }
1007
1008 if (
1009 $this->languagesHelper->doesTitleHasLanguagesOrVariants( $this->getOutput(), $title ) &&
1010 $title->isMainPage()
1011 ) {
1012 $buttons['language'] = $this->getLanguageButton();
1013 }
1014
1015 return $buttons;
1016 }
1017
1018 /**
1019 * @inheritDoc
1020 * @return array
1021 */
1022 protected function getJsConfigVars(): array {
1023 return array_merge( parent::getJsConfigVars(), [
1024 'wgMinervaPermissions' => [
1025 'watchable' => $this->permissions->isAllowed( IMinervaPagePermissions::WATCHABLE ),
1026 'watch' => $this->permissions->isAllowed( IMinervaPagePermissions::WATCH ),
1027 ],
1028 'wgMinervaFeatures' => $this->skinOptions->getAll(),
1029 'wgMinervaDownloadNamespaces' => $this->getConfig()->get( 'MinervaDownloadNamespaces' ),
1030 ] );
1031 }
1032
1033 /**
1034 * Returns the javascript entry modules to load. Only modules that need to
1035 * be overriden or added conditionally should be placed here.
1036 * @return array
1037 */
1038 public function getDefaultModules(): array {
1039 $modules = parent::getDefaultModules();
1040
1041 // FIXME: T223204: Dequeue default content modules except for the history
1042 // action. Allow default content modules on history action in order to
1043 // enable toggling of the filters.
1044 // Long term this won't be necessary when T111565 is resolved and a
1045 // more general solution can be used.
1046 if ( $this->getActionName() !== 'history' ) {
1047 // dequeue default content modules (toc, collapsible, etc.)
1048 $modules['content'] = array_diff( $modules['content'], [
1049 // T111565
1050 'jquery.makeCollapsible',
1051 // Minerva provides its own implementation. Loading this will break display.
1052 'mediawiki.toc'
1053 ] );
1054 // dequeue styles associated with `content` key.
1055 $modules['styles']['content'] = array_diff( $modules['styles']['content'], [
1056 // T111565
1057 'jquery.makeCollapsible.styles',
1058 ] );
1059 }
1060
1061 $modules['styles']['skin.page'] = $this->getPageSpecificStyles();
1062 $modules['styles']['skin.features'] = $this->getFeatureSpecificStyles();
1063
1064 return $modules;
1065 }
1066
1067 /**
1068 * Provide styles required to present the server rendered page in this skin. Additional styles
1069 * may be loaded dynamically by the client.
1070 *
1071 * Any styles returned by this method are loaded on the critical rendering path as linked
1072 * stylesheets. I.e., they are required to load on the client before first paint.
1073 *
1074 * @return array
1075 */
1076 protected function getPageSpecificStyles(): array {
1077 $styles = [];
1078 $title = $this->getTitle();
1079 $request = $this->getRequest();
1080 $requestAction = $this->getActionName();
1081 $viewAction = $requestAction === 'view';
1082
1083 // Warning box styles are needed when reviewing old revisions
1084 // and inside the fallback editor styles to action=edit page.
1085 if (
1086 $title->getNamespace() !== NS_MAIN ||
1087 $request->getCheck( 'oldid' ) ||
1088 !$viewAction
1089 ) {
1090 $styles[] = 'skins.minerva.messageBox.styles';
1091 }
1092
1093 if ( $title->isMainPage() ) {
1094 $styles[] = 'skins.minerva.mainPage.styles';
1095 } elseif ( $this->skinUserPageHelper->isUserPage() ) {
1096 $styles[] = 'skins.minerva.userpage.styles';
1097 }
1098
1099 if ( $this->getUser()->isRegistered() ) {
1100 $styles[] = 'skins.minerva.loggedin.styles';
1101 }
1102
1103 // When any of these features are enabled in production
1104 // remove the if condition
1105 // and move the associated LESS file inside `skins.minerva.amc.styles`
1106 // into a more appropriate module.
1107 if (
1108 // T356117 - enable on all special pages - some special pages e.g. Special:Contribute have tabs.
1109 $title->isSpecialPage() ||
1110 ( $this->isHistoryPage() && !$this->shouldUseSpecialHistory( $title ) ) ||
1111 $this->skinOptions->get( SkinOptions::PERSONAL_MENU ) ||
1112 $this->skinOptions->get( SkinOptions::TALK_AT_TOP ) ||
1113 $this->skinOptions->get( SkinOptions::HISTORY_IN_PAGE_ACTIONS ) ||
1114 $this->skinOptions->get( SkinOptions::TOOLBAR_SUBMENU )
1115 ) {
1116 // SkinOptions::PERSONAL_MENU + SkinOptions::TOOLBAR_SUBMENU uses ToggleList
1117 // SkinOptions::TALK_AT_TOP uses tabs.less
1118 // SkinOptions::HISTORY_IN_PAGE_ACTIONS + SkinOptions::TOOLBAR_SUBMENU uses pageactions.less
1119 $styles[] = 'skins.minerva.amc.styles';
1120 }
1121
1122 return $styles;
1123 }
1124
1125 /**
1126 * Provide styles required to present the server rendered page with related features in this skin.
1127 * Additional styles may be loaded dynamically by the client.
1128 *
1129 * Any styles returned by this method are loaded on the critical rendering path as linked
1130 * stylesheets. I.e., they are required to load on the client before first paint.
1131 *
1132 * @return array
1133 */
1134 protected function getFeatureSpecificStyles(): array {
1135 $styles = [];
1136
1137 if ( $this->hasCategoryLinks() ) {
1138 $styles[] = 'skins.minerva.categories.styles';
1139 }
1140
1141 if ( $this->skinOptions->get( SkinOptions::PERSONAL_MENU ) ) {
1142 // If ever enabled as the default, please remove the duplicate icons
1143 // inside skins.minerva.mainMenu.icons. See comment for MAIN_MENU_EXPANDED
1144 $styles[] = 'skins.minerva.personalMenu.icons';
1145 }
1146
1147 if (
1148 $this->skinOptions->get( SkinOptions::MAIN_MENU_EXPANDED )
1149 ) {
1150 // If ever enabled as the default, please review skins.minerva.mainMenu.icons
1151 // and remove any unneeded icons
1152 $styles[] = 'skins.minerva.mainMenu.advanced.icons';
1153 }
1154
1155 if (
1156 $this->skinOptions->get( SkinOptions::PERSONAL_MENU ) ||
1157 $this->skinOptions->get( SkinOptions::TOOLBAR_SUBMENU )
1158 ) {
1159 // SkinOptions::PERSONAL_MENU requires the `userTalk` icon.
1160 // SkinOptions::TOOLBAR_SUBMENU requires the rest of the icons including `overflow`.
1161 // Note `skins.minerva.overflow.icons` is pulled down by skins.minerva.scripts but the menu can
1162 // work without JS.
1163 $styles[] = 'skins.minerva.overflow.icons';
1164 }
1165
1166 return $styles;
1167 }
1168 }