Debian Codegraph @

includes/skins/SkinTemplate.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © Gabriel Wicke -- http://www.aulinx.de/
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\Debug\MWDebug;
24 use MediaWiki\Html\Html;
25 use MediaWiki\Language\LanguageCode;
26 use MediaWiki\Linker\Linker;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Message\Message;
30 use MediaWiki\Permissions\Authority;
31 use MediaWiki\ResourceLoader as RL;
32 use MediaWiki\Skin\SkinComponentUtils;
33 use MediaWiki\SpecialPage\SpecialPage;
34 use MediaWiki\Specials\Contribute\ContributeFactory;
35 use MediaWiki\Title\Title;
36 use Wikimedia\Message\MessageSpecifier;
37
38 /**
39 * Base class for QuickTemplate-based skins.
40 *
41 * The template data is filled in SkinTemplate::prepareQuickTemplate.
42 *
43 * @stable to extend
44 * @ingroup Skins
45 */
46 class SkinTemplate extends Skin {
47 /**
48 * @var string For QuickTemplate, the name of the subclass which will
49 * actually fill the template.
50 */
51 public $template;
52
53 /** @var string */
54 public $thispage;
55 /** @var string */
56 public $titletxt;
57 /** @var string */
58 public $userpage;
59 /** @var bool TODO: Rename this to $isRegistered (but that's a breaking change) */
60 public $loggedin;
61 /** @var string */
62 public $username;
63 /** @var array */
64 public $userpageUrlDetails;
65
66 /** @var bool */
67 private $isTempUser;
68
69 /** @var bool */
70 private $isNamedUser;
71
72 /** @var bool */
73 private $isAnonUser;
74
75 /** @var bool */
76 private $templateContextSet = false;
77 /** @var array|null */
78 private $contentNavigationCached;
79 /** @var array|null */
80 private $portletsCached;
81
82 /**
83 * Create the template engine object; we feed it a bunch of data
84 * and eventually it spits out some HTML. Should have interface
85 * roughly equivalent to PHPTAL 0.7.
86 *
87 * @param string $classname
88 * @return QuickTemplate
89 */
90 protected function setupTemplate( $classname ) {
91 return new $classname( $this->getConfig() );
92 }
93
94 /**
95 * @return QuickTemplate
96 */
97 protected function setupTemplateForOutput() {
98 $this->setupTemplateContext();
99 $template = $this->options['template'] ?? $this->template;
100 if ( !$template ) {
101 throw new RuntimeException(
102 'SkinTemplate skins must define a `template` either as a public'
103 . ' property of by passing in a`template` option to the constructor.'
104 );
105 }
106 $tpl = $this->setupTemplate( $template );
107 return $tpl;
108 }
109
110 /**
111 * Setup class properties that are necessary prior to calling
112 * setupTemplateForOutput. It must be called inside
113 * prepareQuickTemplate.
114 * This function may set local class properties that will be used
115 * by other methods, but should not make assumptions about the
116 * implementation of setupTemplateForOutput
117 * @since 1.35
118 */
119 final protected function setupTemplateContext() {
120 if ( $this->templateContextSet ) {
121 return;
122 }
123
124 $request = $this->getRequest();
125 $user = $this->getUser();
126 $title = $this->getTitle();
127 $this->thispage = $title->getPrefixedDBkey();
128 $this->titletxt = $title->getPrefixedText();
129 $userpageTitle = $user->getUserPage();
130 $this->userpage = $userpageTitle->getPrefixedText();
131 $this->loggedin = $user->isRegistered();
132 $this->username = $user->getName();
133 $this->isTempUser = $user->isTemp();
134 $this->isNamedUser = $this->loggedin && !$this->isTempUser;
135 $this->isAnonUser = $user->isAnon();
136
137 if ( $this->isNamedUser ) {
138 $this->userpageUrlDetails = self::makeUrlDetails( $userpageTitle );
139 } else {
140 # This won't be used in the standard skins, but we define it to preserve the interface
141 # To save time, we check for existence
142 $this->userpageUrlDetails = self::makeKnownUrlDetails( $userpageTitle );
143 }
144
145 $this->templateContextSet = true;
146 }
147
148 /**
149 * Subclasses not wishing to use the QuickTemplate
150 * render method can rewrite this method, for example to use
151 * TemplateParser::processTemplate
152 * @since 1.35
153 * @return string HTML is the contents of the body tag e.g. <body>...</body>
154 */
155 public function generateHTML() {
156 $tpl = $this->prepareQuickTemplate();
157 $options = $this->getOptions();
158 $out = $this->getOutput();
159 // execute template
160 ob_start();
161 $tpl->execute();
162 $html = ob_get_contents();
163 ob_end_clean();
164
165 return $html;
166 }
167
168 /**
169 * Initialize various variables and generate the template
170 * @stable to override
171 */
172 public function outputPage() {
173 Profiler::instance()->setAllowOutput();
174 $out = $this->getOutput();
175
176 $this->initPage( $out );
177 $out->addJsConfigVars( $this->getJsConfigVars() );
178
179 // result may be an error
180 echo $this->generateHTML();
181 }
182
183 /**
184 * @inheritDoc
185 */
186 public function getTemplateData() {
187 return parent::getTemplateData() + $this->getPortletsTemplateData();
188 }
189
190 /**
191 * initialize various variables and generate the template
192 *
193 * @since 1.23
194 * @return QuickTemplate The template to be executed by outputPage
195 */
196 protected function prepareQuickTemplate() {
197 $title = $this->getTitle();
198 $request = $this->getRequest();
199 $out = $this->getOutput();
200 $config = $this->getConfig();
201 $tpl = $this->setupTemplateForOutput();
202
203 $tpl->set( 'title', $out->getPageTitle() );
204 $tpl->set( 'pagetitle', $out->getHTMLTitle() );
205
206 $tpl->set( 'thispage', $this->thispage );
207 $tpl->set( 'titleprefixeddbkey', $this->thispage );
208 $tpl->set( 'titletext', $title->getText() );
209 $tpl->set( 'articleid', $title->getArticleID() );
210
211 $tpl->set( 'isarticle', $out->isArticle() );
212
213 $tpl->set( 'subtitle', $this->prepareSubtitle() );
214 $tpl->set( 'undelete', $this->prepareUndeleteLink() );
215
216 $tpl->set( 'catlinks', $this->getCategories() );
217 $feeds = $this->buildFeedUrls();
218 $tpl->set( 'feeds', count( $feeds ) ? $feeds : false );
219
220 $tpl->set( 'mimetype', $config->get( MainConfigNames::MimeType ) );
221 $tpl->set( 'charset', 'UTF-8' );
222 $tpl->set( 'wgScript', $config->get( MainConfigNames::Script ) );
223 $tpl->set( 'skinname', $this->skinname );
224 $tpl->set( 'skinclass', static::class );
225 $tpl->set( 'skin', $this );
226 $tpl->set( 'printable', $out->isPrintable() );
227 $tpl->set( 'handheld', $request->getBool( 'handheld' ) );
228 $tpl->set( 'loggedin', $this->loggedin );
229 $tpl->set( 'notspecialpage', !$title->isSpecialPage() );
230
231 $searchTitle = SpecialPage::newSearchPage( $this->getUser() );
232 $searchLink = $searchTitle->getLocalURL();
233 $tpl->set( 'searchaction', $searchLink );
234 $tpl->deprecate( 'searchaction', '1.36' );
235
236 $tpl->set( 'searchtitle', $searchTitle->getPrefixedDBkey() );
237 $tpl->set( 'search', trim( $request->getVal( 'search', '' ) ) );
238 $tpl->set( 'stylepath', $config->get( MainConfigNames::StylePath ) );
239 $tpl->set( 'articlepath', $config->get( MainConfigNames::ArticlePath ) );
240 $tpl->set( 'scriptpath', $config->get( MainConfigNames::ScriptPath ) );
241 $tpl->set( 'serverurl', $config->get( MainConfigNames::Server ) );
242 $tpl->set( 'sitename', $config->get( MainConfigNames::Sitename ) );
243
244 $userLang = $this->getLanguage();
245 $userLangCode = $userLang->getHtmlCode();
246 $userLangDir = $userLang->getDir();
247
248 $tpl->set( 'lang', $userLangCode );
249 $tpl->set( 'dir', $userLangDir );
250 $tpl->set( 'rtl', $userLang->isRTL() );
251
252 $logos = RL\SkinModule::getAvailableLogos( $config, $userLangCode );
253 $tpl->set( 'logopath', $logos['1x'] );
254
255 $tpl->set( 'showjumplinks', true ); // showjumplinks preference has been removed
256 $tpl->set( 'username', $this->loggedin ? $this->username : null );
257 $tpl->set( 'userpage', $this->userpage );
258 $tpl->set( 'userpageurl', $this->userpageUrlDetails['href'] );
259 $tpl->set( 'userlang', $userLangCode );
260
261 // Users can have their language set differently than the
262 // content of the wiki. For these users, tell the web browser
263 // that interface elements are in a different language.
264 $tpl->set( 'userlangattributes', $this->prepareUserLanguageAttributes() );
265 $tpl->set( 'specialpageattributes', '' ); # obsolete
266 // Used by VectorBeta to insert HTML before content but after the
267 // heading for the page title. Defaults to empty string.
268 $tpl->set( 'prebodyhtml', '' );
269
270 $tpl->set( 'newtalk', $this->getNewtalks() );
271 $tpl->set( 'logo', $this->logoText() );
272
273 $footerData = $this->getComponent( 'footer' )->getTemplateData();
274 $tpl->set( 'copyright', $footerData['info']['copyright'] ?? false );
275 // No longer used
276 $tpl->set( 'viewcount', false );
277 $tpl->set( 'lastmod', $footerData['info']['lastmod'] ?? false );
278 $tpl->set( 'credits', $footerData['info']['credits'] ?? false );
279 $tpl->set( 'numberofwatchingusers', false );
280
281 $tpl->set( 'disclaimer', $footerData['places']['disclaimer'] ?? false );
282 $tpl->set( 'privacy', $footerData['places']['privacy'] ?? false );
283 $tpl->set( 'about', $footerData['places']['about'] ?? false );
284
285 // Flatten for compat with the 'footerlinks' key in QuickTemplate-based skins.
286 $flattenedfooterlinks = [];
287 foreach ( $footerData as $category => $data ) {
288 if ( $category !== 'data-icons' ) {
289 foreach ( $data['array-items'] as $item ) {
290 $key = str_replace( 'data-', '', $category );
291 $flattenedfooterlinks[$key][] = $item['name'];
292 // For full support with BaseTemplate we also need to
293 // copy over the keys.
294 $tpl->set( $item['name'], $item['html'] );
295 }
296 }
297 }
298 $tpl->set( 'footerlinks', $flattenedfooterlinks );
299 $tpl->set( 'footericons', $this->getFooterIcons() );
300
301 $tpl->set( 'indicators', $out->getIndicators() );
302
303 $tpl->set( 'sitenotice', $this->getSiteNotice() );
304 $tpl->set( 'printfooter', $this->printSource() );
305 // Wrap the bodyText with #mw-content-text element
306 $tpl->set( 'bodytext', $this->wrapHTML( $title, $out->getHTML() ) );
307
308 $tpl->set( 'language_urls', $this->getLanguages() ?: false );
309
310 $content_navigation = $this->buildContentNavigationUrlsInternal();
311 # Personal toolbar
312 $tpl->set( 'personal_urls', $this->makeSkinTemplatePersonalUrls( $content_navigation ) );
313 // The user-menu, notifications, and user-interface-preferences are new content navigation entries which aren't
314 // expected to be part of content_navigation or content_actions. Adding them in there breaks skins that do not
315 // expect it. (See T316196)
316 unset(
317 $content_navigation['user-menu'],
318 $content_navigation['notifications'],
319 $content_navigation['user-page'],
320 $content_navigation['user-interface-preferences'],
321 $content_navigation['category-normal'],
322 $content_navigation['category-hidden'],
323 $content_navigation['associated-pages']
324 );
325 $content_actions = $this->buildContentActionUrls( $content_navigation );
326 $tpl->set( 'content_navigation', $content_navigation );
327 $tpl->set( 'content_actions', $content_actions );
328
329 $tpl->set( 'sidebar', $this->buildSidebar() );
330 $tpl->set( 'nav_urls', $this->buildNavUrls() );
331
332 $tpl->set( 'debug', '' );
333 $tpl->set( 'debughtml', MWDebug::getHTMLDebugLog() );
334
335 // Set the bodytext to another key so that skins can just output it on its own
336 // and output printfooter and debughtml separately
337 $tpl->set( 'bodycontent', $tpl->data['bodytext'] );
338
339 // Append printfooter and debughtml onto bodytext so that skins that
340 // were already using bodytext before they were split out don't suddenly
341 // start not outputting information.
342 $tpl->data['bodytext'] .= Html::rawElement(
343 'div',
344 [ 'class' => 'printfooter' ],
345 "\n{$tpl->data['printfooter']}"
346 ) . "\n";
347 $tpl->data['bodytext'] .= $tpl->data['debughtml'];
348
349 // allow extensions adding stuff after the page content.
350 // See Skin::afterContentHook() for further documentation.
351 $tpl->set( 'dataAfterContent', $this->afterContentHook() );
352
353 return $tpl;
354 }
355
356 /**
357 * Get the HTML for the personal tools list
358 * @since 1.31
359 *
360 * @param array|null $personalTools
361 * @param array $options
362 * @return string
363 */
364 public function makePersonalToolsList( $personalTools = null, $options = [] ) {
365 $personalTools ??= $this->getPersonalToolsForMakeListItem(
366 $this->buildPersonalUrls()
367 );
368
369 $html = '';
370 foreach ( $personalTools as $key => $item ) {
371 $html .= $this->makeListItem( $key, $item, $options );
372 }
373 return $html;
374 }
375
376 /**
377 * Get personal tools for the user
378 *
379 * @since 1.31
380 *
381 * @return array[]
382 */
383 public function getStructuredPersonalTools() {
384 return $this->getPersonalToolsForMakeListItem(
385 $this->buildPersonalUrls()
386 );
387 }
388
389 /**
390 * Build array of urls for personal toolbar
391 *
392 * @param bool $includeNotifications Since 1.36, notifications are optional
393 * @return array
394 */
395 protected function buildPersonalUrls( bool $includeNotifications = true ) {
396 $this->setupTemplateContext();
397 $title = $this->getTitle();
398 $authority = $this->getAuthority();
399 $request = $this->getRequest();
400 $pageurl = $title->getLocalURL();
401 $services = MediaWikiServices::getInstance();
402 $authManager = $services->getAuthManager();
403 $groupPermissionsLookup = $services->getGroupPermissionsLookup();
404 $tempUserConfig = $services->getTempUserConfig();
405 $returnto = SkinComponentUtils::getReturnToParam( $title, $request, $authority );
406 $shouldHideUserLinks = $this->isAnonUser && $tempUserConfig->isKnown();
407
408 /* set up the default links for the personal toolbar */
409 $personal_urls = [];
410
411 if ( $this->loggedin ) {
412 $this->addPersonalPageItem( $personal_urls, '' );
413
414 // Merge notifications into the personal menu for older skins.
415 if ( $includeNotifications ) {
416 $contentNavigation = $this->buildContentNavigationUrlsInternal();
417
418 $personal_urls += $contentNavigation['notifications'];
419 }
420
421 $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage );
422 $personal_urls['mytalk'] = [
423 'text' => $this->msg( 'mytalk' )->text(),
424 'href' => &$usertalkUrlDetails['href'],
425 'class' => $usertalkUrlDetails['exists'] ? false : 'new',
426 'exists' => $usertalkUrlDetails['exists'],
427 'active' => ( $usertalkUrlDetails['href'] == $pageurl ),
428 'icon' => 'userTalk'
429 ];
430 if ( !$this->isTempUser ) {
431 $href = SkinComponentUtils::makeSpecialUrl( 'Preferences' );
432 $personal_urls['preferences'] = [
433 'text' => $this->msg( 'mypreferences' )->text(),
434 'href' => $href,
435 'active' => ( $href == $pageurl ),
436 'icon' => 'settings',
437 ];
438 }
439
440 if ( $authority->isAllowed( 'viewmywatchlist' ) ) {
441 $personal_urls['watchlist'] = self::buildWatchlistData();
442 }
443
444 # We need to do an explicit check for Special:Contributions, as we
445 # have to match both the title, and the target, which could come
446 # from request values (Special:Contributions?target=Jimbo_Wales)
447 # or be specified in "subpage" form
448 # (Special:Contributions/Jimbo_Wales). The plot
449 # thickens, because the Title object is altered for special pages,
450 # so it doesn't contain the original alias-with-subpage.
451 $origTitle = Title::newFromText( $request->getText( 'title' ) );
452 if ( $origTitle instanceof Title && $origTitle->isSpecialPage() ) {
453 [ $spName, $spPar ] =
454 MediaWikiServices::getInstance()->getSpecialPageFactory()->
455 resolveAlias( $origTitle->getText() );
456 $active = $spName == 'Contributions'
457 && ( ( $spPar && $spPar == $this->username )
458 || $request->getText( 'target' ) == $this->username );
459 } else {
460 $active = false;
461 }
462
463 $personal_urls = $this->makeContributionsLink( $personal_urls, 'mycontris', $this->username, $active );
464
465 // if we can't set the user, we can't unset it either
466 if ( $request->getSession()->canSetUser() ) {
467 $personal_urls['logout'] = $this->buildLogoutLinkData();
468 }
469 } elseif ( !$shouldHideUserLinks ) {
470 $canEdit = $authority->isAllowed( 'edit' );
471 $canEditWithTemp = $tempUserConfig->isAutoCreateAction( 'edit' );
472 // No need to show Talk and Contributions to anons if they can't contribute!
473 if ( $canEdit || $canEditWithTemp ) {
474 // Non interactive placeholder for anonymous users.
475 // It's unstyled by default (black color). Skin that
476 // needs it, can style it using the 'pt-anonuserpage' id.
477 // Skin that does not need it should unset it.
478 $personal_urls['anonuserpage'] = [
479 'text' => $this->msg( 'notloggedin' )->text(),
480 ];
481 }
482 if ( $canEdit ) {
483 // Because of caching, we can't link directly to the IP talk and
484 // contributions pages. Instead we use the special page shortcuts
485 // (which work correctly regardless of caching). This means we can't
486 // determine whether these links are active or not, but since major
487 // skins (MonoBook, Vector) don't use this information, it's not a
488 // huge loss.
489 $personal_urls['anontalk'] = [
490 'text' => $this->msg( 'anontalk' )->text(),
491 'href' => SkinComponentUtils::makeSpecialUrlSubpage( 'Mytalk', false ),
492 'active' => false,
493 'icon' => 'userTalk',
494 ];
495 $personal_urls = $this->makeContributionsLink( $personal_urls, 'anoncontribs', null, false );
496 }
497 }
498
499 if ( !$this->loggedin ) {
500 $useCombinedLoginLink = $this->useCombinedLoginLink();
501 $login_url = $this->buildLoginData( $returnto, $useCombinedLoginLink );
502 $createaccount_url = $this->buildCreateAccountData( $returnto );
503
504 if (
505 $authManager->canCreateAccounts()
506 && $authority->isAllowed( 'createaccount' )
507 && !$useCombinedLoginLink
508 ) {
509 $personal_urls['createaccount'] = $createaccount_url;
510 }
511
512 if ( $authManager->canAuthenticateNow() ) {
513 // TODO: easy way to get anon authority
514 $key = $groupPermissionsLookup->groupHasPermission( '*', 'read' )
515 ? 'login'
516 : 'login-private';
517 $personal_urls[$key] = $login_url;
518 }
519 }
520
521 return $personal_urls;
522 }
523
524 /**
525 * Returns if a combined login/signup link will be used
526 * @unstable
527 *
528 * @return bool
529 */
530 protected function useCombinedLoginLink() {
531 $services = MediaWikiServices::getInstance();
532 $authManager = $services->getAuthManager();
533 $useCombinedLoginLink = $this->getConfig()->get( MainConfigNames::UseCombinedLoginLink );
534 if ( !$authManager->canCreateAccounts() || !$authManager->canAuthenticateNow() ) {
535 // don't show combined login/signup link if one of those is actually not available
536 $useCombinedLoginLink = false;
537 }
538
539 return $useCombinedLoginLink;
540 }
541
542 /**
543 * Build "Login" link
544 * @unstable
545 *
546 * @param string[] $returnto query params for the page to return to
547 * @param bool $useCombinedLoginLink when set a single link to login form will be created
548 * with alternative label.
549 * @return array
550 */
551 protected function buildLoginData( $returnto, $useCombinedLoginLink ) {
552 $title = $this->getTitle();
553
554 $loginlink = $this->getAuthority()->isAllowed( 'createaccount' )
555 && $useCombinedLoginLink ? 'nav-login-createaccount' : 'pt-login';
556
557 $login_url = [
558 'single-id' => 'pt-login',
559 'text' => $this->msg( $loginlink )->text(),
560 'href' => SkinComponentUtils::makeSpecialUrl( 'Userlogin', $returnto ),
561 'active' => $title->isSpecial( 'Userlogin' )
562 || ( $title->isSpecial( 'CreateAccount' ) && $useCombinedLoginLink ),
563 'icon' => 'logIn'
564 ];
565
566 return $login_url;
567 }
568
569 /**
570 * @param array $links return value from OutputPage::getCategoryLinks
571 * @return array of data
572 */
573 private function getCategoryPortletsData( array $links ): array {
574 $categories = [];
575 foreach ( $links as $group => $groupLinks ) {
576 $allLinks = [];
577 $groupName = 'category-' . $group;
578 foreach ( $groupLinks as $i => $link ) {
579 $allLinks[$groupName . '-' . $i] = [
580 'html' => $link,
581 ];
582 }
583 $categories[ $groupName ] = $allLinks;
584 }
585 return $categories;
586 }
587
588 /**
589 * Extends category links with Skin::getAfterPortlet functionality.
590 * @return string HTML
591 */
592 public function getCategoryLinks() {
593 $afterPortlet = $this->getPortletsTemplateData()['data-portlets']['data-category-normal']['html-after-portal']
594 ?? '';
595 return parent::getCategoryLinks() . $afterPortlet;
596 }
597
598 /**
599 * @return array of portlet data for all portlets
600 */
601 private function getPortletsTemplateData() {
602 if ( $this->portletsCached ) {
603 return $this->portletsCached;
604 }
605 $portlets = [];
606 $contentNavigation = $this->buildContentNavigationUrlsInternal();
607 $sidebar = [];
608 $sidebarData = $this->buildSidebar();
609 foreach ( $sidebarData as $name => $items ) {
610 if ( is_array( $items ) ) {
611 // Numeric strings gets an integer when set as key, cast back - T73639
612 $name = (string)$name;
613 switch ( $name ) {
614 // ignore search
615 case 'SEARCH':
616 break;
617 // Map toolbox to `tb` id.
618 case 'TOOLBOX':
619 $sidebar[] = $this->getPortletData( 'tb', $items );
620 break;
621 // Languages is no longer be tied to sidebar
622 case 'LANGUAGES':
623 // The language portal will be added provided either
624 // languages exist or there is a value in html-after-portal
625 // for example to show the add language wikidata link (T252800)
626 $portal = $this->getPortletData( 'lang', $items );
627 if ( count( $items ) || $portal['html-after-portal'] ) {
628 $portlets['data-languages'] = $portal;
629 }
630 break;
631 default:
632 $sidebar[] = $this->getPortletData( $name, $items );
633 break;
634 }
635 }
636 }
637
638 foreach ( $contentNavigation as $name => $items ) {
639 if ( $name === 'user-menu' ) {
640 $items = $this->getPersonalToolsForMakeListItem( $items, true );
641 }
642
643 $portlets['data-' . $name] = $this->getPortletData( $name, $items );
644 }
645
646 // A menu that includes the notifications. This will be deprecated in future versions
647 // of the skin API spec.
648 $portlets['data-personal'] = $this->getPortletData(
649 'personal',
650 $this->getPersonalToolsForMakeListItem(
651 $this->injectLegacyMenusIntoPersonalTools( $contentNavigation )
652 )
653 );
654
655 $this->portletsCached = [
656 'data-portlets' => $portlets,
657 'data-portlets-sidebar' => [
658 'data-portlets-first' => $sidebar[0] ?? null,
659 'array-portlets-rest' => array_slice( $sidebar, 1 ),
660 ],
661 ];
662 return $this->portletsCached;
663 }
664
665 /**
666 * Build data required for "Logout" link.
667 *
668 * @unstable
669 *
670 * @since 1.37
671 *
672 * @return array Array of data required to create a logout link.
673 */
674 final protected function buildLogoutLinkData() {
675 $title = $this->getTitle();
676 $request = $this->getRequest();
677 $authority = $this->getAuthority();
678 $returnto = SkinComponentUtils::getReturnToParam( $title, $request, $authority );
679 $isTemp = $this->isTempUser;
680 $msg = $isTemp ? 'templogout' : 'pt-userlogout';
681
682 return [
683 'single-id' => 'pt-logout',
684 'text' => $this->msg( $msg )->text(),
685 'data-mw' => 'interface',
686 'href' => SkinComponentUtils::makeSpecialUrl( 'Userlogout',
687 // Note: userlogout link must always contain an & character, otherwise we might not be able
688 // to detect a buggy precaching proxy (T19790)
689 ( $title->isSpecial( 'Preferences' ) ? [] : $returnto ) ),
690 'active' => false,
691 'icon' => 'logOut'
692 ];
693 }
694
695 /**
696 * Build "Create Account" link data.
697 * @unstable
698 *
699 * @param string[] $returnto query params for the page to return to
700 * @return array
701 */
702 protected function buildCreateAccountData( $returnto ) {
703 $title = $this->getTitle();
704
705 return [
706 'single-id' => 'pt-createaccount',
707 'text' => $this->msg( 'pt-createaccount' )->text(),
708 'href' => SkinComponentUtils::makeSpecialUrl( 'CreateAccount', $returnto ),
709 'active' => $title->isSpecial( 'CreateAccount' ),
710 'icon' => 'userAdd'
711 ];
712 }
713
714 /**
715 * Add the userpage link to the array
716 *
717 * @param array &$links Links array to append to
718 * @param string $idSuffix Something to add to the IDs to make them unique
719 */
720 private function addPersonalPageItem( &$links, $idSuffix ) {
721 if ( $this->isNamedUser ) { // T340152
722 $links['userpage'] = $this->buildPersonalPageItem( 'pt-userpage' . $idSuffix );
723 }
724 }
725
726 /**
727 * Build a user page link data.
728 *
729 * @param string $id of user page item to be output in HTML attribute (optional)
730 * @return array
731 */
732 protected function buildPersonalPageItem( $id = 'pt-userpage' ): array {
733 $linkClasses = $this->userpageUrlDetails['exists'] ? [] : [ 'new' ];
734 // T335440 Temp accounts dont show a user page link
735 // But we still need to update the user icon, as its used by other UI elements
736 $icon = $this->isTempUser ? 'userTemporary' : 'userAvatar';
737 $href = &$this->userpageUrlDetails['href'];
738 return [
739 'id' => $id,
740 'single-id' => 'pt-userpage',
741 'text' => $this->username,
742 'href' => $href,
743 'link-class' => $linkClasses,
744 'exists' => $this->userpageUrlDetails['exists'],
745 'active' => ( $this->userpageUrlDetails['href'] == $this->getTitle()->getLocalURL() ),
746 'icon' => $icon,
747 ];
748 }
749
750 /**
751 * Build a watchlist link data.
752 *
753 * @return array Array of data required to create a watchlist link.
754 */
755 private function buildWatchlistData() {
756 $href = SkinComponentUtils::makeSpecialUrl( 'Watchlist' );
757 $pageurl = $this->getTitle()->getLocalURL();
758
759 return [
760 'single-id' => 'pt-watchlist',
761 'text' => $this->msg( 'mywatchlist' )->text(),
762 'href' => $href,
763 'active' => ( $href == $pageurl ),
764 'icon' => 'watchlist'
765 ];
766 }
767
768 /**
769 * Builds an array with tab definition
770 *
771 * @param Title $title Page Where the tab links to
772 * @param string|string[]|MessageSpecifier $message Message or an array of message keys
773 * (will fall back)
774 * @param bool $selected Display the tab as selected
775 * @param string $query Query string attached to tab URL
776 * @param bool $checkEdit Check if $title exists and mark with .new if one doesn't
777 *
778 * @return array
779 * @param-taint $message tainted
780 */
781 public function tabAction( $title, $message, $selected, $query = '', $checkEdit = false ) {
782 $classes = [];
783 if ( $selected ) {
784 $classes[] = 'selected';
785 }
786 $exists = true;
787 $services = MediaWikiServices::getInstance();
788 $linkClass = $services->getLinkRenderer()->getLinkClasses( $title );
789 if ( $checkEdit && !$title->isKnown() ) {
790 // Selected tabs should not show as red link. It doesn't make sense
791 // to show a red link on a page the user has already navigated to.
792 // https://phabricator.wikimedia.org/T294129#7451549
793 if ( !$selected ) {
794 // For historic reasons we add to the LI element
795 $classes[] = 'new';
796 // but adding the class to the A element is more appropriate.
797 $linkClass .= ' new';
798 }
799 $exists = false;
800 if ( $query !== '' ) {
801 $query = 'action=edit&redlink=1&' . $query;
802 } else {
803 $query = 'action=edit&redlink=1';
804 }
805 }
806
807 if ( $message instanceof MessageSpecifier ) {
808 $msg = new Message( $message );
809 } else {
810 // wfMessageFallback will nicely accept $message as an array of fallbacks
811 // or just a single key
812 $msg = wfMessageFallback( $message );
813 }
814 $msg->setContext( $this->getContext() );
815 if ( !$msg->isDisabled() ) {
816 $text = $msg->text();
817 } else {
818 $text = $services->getLanguageConverterFactory()
819 ->getLanguageConverter( $services->getContentLanguage() )
820 ->convertNamespace(
821 $services->getNamespaceInfo()
822 ->getSubject( $title->getNamespace() )
823 );
824 }
825
826 $result = [
827 'class' => implode( ' ', $classes ),
828 'text' => $text,
829 'href' => $title->getLocalURL( $query ),
830 'exists' => $exists,
831 'primary' => true ];
832 if ( $linkClass !== '' ) {
833 $result['link-class'] = trim( $linkClass );
834 }
835
836 return $result;
837 }
838
839 /**
840 * Get a message label that skins can override.
841 *
842 * @param string $labelMessageKey
843 * @param mixed $param for the message
844 * @return string
845 */
846 private function getSkinNavOverrideableLabel( $labelMessageKey, $param = null ) {
847 $skname = $this->skinname;
848 // The following messages can be used here:
849 // * skin-action-addsection
850 // * skin-action-delete
851 // * skin-action-move
852 // * skin-action-protect
853 // * skin-action-undelete
854 // * skin-action-unprotect
855 // * skin-action-viewdeleted
856 // * skin-action-viewsource
857 // * skin-view-create
858 // * skin-view-create-local
859 // * skin-view-edit
860 // * skin-view-edit-local
861 // * skin-view-foreign
862 // * skin-view-history
863 // * skin-view-view
864 $msg = wfMessageFallback(
865 "$skname-$labelMessageKey",
866 "skin-$labelMessageKey"
867 )->setContext( $this->getContext() );
868
869 if ( $param ) {
870 if ( is_numeric( $param ) ) {
871 $msg->numParams( $param );
872 } else {
873 $msg->params( $param );
874 }
875 }
876 return $msg->text();
877 }
878
879 /**
880 * @param string $name
881 * @param string|array $urlaction
882 * @return array
883 */
884 private function makeTalkUrlDetails( $name, $urlaction = '' ) {
885 $title = Title::newFromTextThrow( $name )->getTalkPage();
886 return [
887 'href' => $title->getLocalURL( $urlaction ),
888 'exists' => $title->isKnown(),
889 ];
890 }
891
892 /**
893 * Get the attributes for the watch link.
894 * @param string $mode Either 'watch' or 'unwatch'
895 * @param Authority $performer
896 * @param Title $title
897 * @param string|null $action
898 * @param bool $onPage
899 * @return array
900 */
901 private function getWatchLinkAttrs(
902 string $mode, Authority $performer, Title $title, ?string $action, bool $onPage
903 ): array {
904 $isWatchMode = $action == 'watch';
905 $class = 'mw-watchlink ' . (
906 $onPage && ( $isWatchMode || $action == 'unwatch' ) ? 'selected' : ''
907 );
908
909 $services = MediaWikiServices::getInstance();
910 $watchlistManager = $services->getWatchlistManager();
911 $watchIcon = $watchlistManager->isWatched( $performer, $title ) ? 'unStar' : 'star';
912 $watchExpiry = null;
913 // Modify tooltip and add class identifying the page is temporarily watched, if applicable.
914 if ( $this->getConfig()->get( MainConfigNames::WatchlistExpiry ) &&
915 $watchlistManager->isTempWatched( $performer, $title )
916 ) {
917 $class .= ' mw-watchlink-temp';
918 $watchIcon = 'halfStar';
919
920 $watchStore = $services->getWatchedItemStore();
921 $watchedItem = $watchStore->getWatchedItem( $performer->getUser(), $title );
922 $diffInDays = $watchedItem->getExpiryInDays();
923 $watchExpiry = $watchedItem->getExpiry( TS_ISO_8601 );
924 if ( $diffInDays ) {
925 $msgParams = [ $diffInDays ];
926 // Resolves to tooltip-ca-unwatch-expiring message
927 $tooltip = 'ca-unwatch-expiring';
928 } else {
929 // Resolves to tooltip-ca-unwatch-expiring-hours message
930 $tooltip = 'ca-unwatch-expiring-hours';
931 }
932 }
933
934 return [
935 'class' => $class,
936 'icon' => $watchIcon,
937 // uses 'watch' or 'unwatch' message
938 'text' => $this->msg( $mode )->text(),
939 'single-id' => $tooltip ?? null,
940 'tooltip-params' => $msgParams ?? null,
941 'href' => $title->getLocalURL( [ 'action' => $mode ] ),
942 // Set a data-mw=interface attribute, which the mediawiki.page.ajax
943 // module will look for to make sure it's a trusted link
944 'data' => [
945 'mw' => 'interface',
946 'mw-expiry' => $watchExpiry,
947 ],
948 ];
949 }
950
951 /**
952 * Run hooks relating to navigation menu data.
953 * Skins should extend this if they want to run opinionated transformations to the data after all
954 * hooks have been run. Note hooks are run in an arbitrary order.
955 *
956 * @param SkinTemplate $skin
957 * @param array &$content_navigation representing all menus.
958 * @since 1.37
959 */
960 protected function runOnSkinTemplateNavigationHooks( SkinTemplate $skin, &$content_navigation ) {
961 $beforeHookAssociatedPages = array_keys( $content_navigation['associated-pages'] );
962 $beforeHookNamespaces = array_keys( $content_navigation['namespaces'] );
963
964 // Equiv to SkinTemplateContentActions, run
965 $this->getHookRunner()->onSkinTemplateNavigation__Universal(
966 $skin, $content_navigation );
967 // The new `associatedPages` menu (added in 1.39)
968 // should be backwards compatibile with `namespaces`.
969 // To do this we look for hook modifications to both keys. If modifications are not
970 // made the new key, but are made to the old key, associatedPages reverts back to the
971 // links in the namespaces menu.
972 // It's expected in future that `namespaces` menu will become an alias for `associatedPages`
973 // at which point this code can be removed.
974 $afterHookNamespaces = array_keys( $content_navigation[ 'namespaces' ] );
975 $afterHookAssociatedPages = array_keys( $content_navigation[ 'associated-pages' ] );
976 $associatedPagesChanged = count( array_diff( $afterHookAssociatedPages, $beforeHookAssociatedPages ) ) > 0;
977 $namespacesChanged = count( array_diff( $afterHookNamespaces, $beforeHookNamespaces ) ) > 0;
978 // If some change occurred to namespaces via the hook, revert back to namespaces.
979 if ( !$associatedPagesChanged && $namespacesChanged ) {
980 $content_navigation['associated-pages'] = $content_navigation['namespaces'];
981 }
982 }
983
984 /**
985 * a structured array of links usually used for the tabs in a skin
986 *
987 * There are 4 standard sections
988 * namespaces: Used for namespace tabs like special, page, and talk namespaces
989 * views: Used for primary page views like read, edit, history
990 * actions: Used for most extra page actions like deletion, protection, etc...
991 * variants: Used to list the language variants for the page
992 *
993 * Each section's value is a key/value array of links for that section.
994 * The links themselves have these common keys:
995 * - class: The css classes to apply to the tab
996 * - text: The text to display on the tab
997 * - href: The href for the tab to point to
998 * - rel: An optional rel= for the tab's link
999 * - redundant: If true the tab will be dropped in skins using content_actions
1000 * this is useful for tabs like "Read" which only have meaning in skins that
1001 * take special meaning from the grouped structure of content_navigation
1002 *
1003 * Views also have an extra key which can be used:
1004 * - primary: If this is not true skins like vector may try to hide the tab
1005 * when the user has limited space in their browser window
1006 *
1007 * content_navigation using code also expects these ids to be present on the
1008 * links, however these are usually automatically generated by SkinTemplate
1009 * itself and are not necessary when using a hook. The only things these may
1010 * matter to are people modifying content_navigation after it's initial creation:
1011 * - id: A "preferred" id, most skins are best off outputting this preferred
1012 * id for best compatibility.
1013 * - tooltiponly: This is set to true for some tabs in cases where the system
1014 * believes that the accesskey should not be added to the tab.
1015 *
1016 * @return array
1017 */
1018 private function buildContentNavigationUrlsInternal() {
1019 if ( $this->contentNavigationCached ) {
1020 return $this->contentNavigationCached;
1021 }
1022 // Display tabs for the relevant title rather than always the title itself
1023 $title = $this->getRelevantTitle();
1024 $onPage = $title->equals( $this->getTitle() );
1025
1026 $out = $this->getOutput();
1027 $request = $this->getRequest();
1028 $performer = $this->getAuthority();
1029 $action = $this->getContext()->getActionName();
1030 $services = MediaWikiServices::getInstance();
1031 $permissionManager = $services->getPermissionManager();
1032 $categoriesData = $this->getCategoryPortletsData( $this->getOutput()->getCategoryLinks() );
1033 $userPageLink = [];
1034 $this->addPersonalPageItem( $userPageLink, '-2' );
1035
1036 $content_navigation = $categoriesData + [
1037 // Modern keys: Please ensure these get unset inside Skin::prepareQuickTemplate
1038 'user-interface-preferences' => [],
1039 'user-page' => $userPageLink,
1040 'user-menu' => $this->buildPersonalUrls( false ),
1041 'notifications' => [],
1042 'associated-pages' => [],
1043 // Legacy keys
1044 'namespaces' => [],
1045 'views' => [],
1046 'actions' => [],
1047 'variants' => []
1048 ];
1049
1050 $associatedPages = [];
1051 $namespaces = [];
1052 $userCanRead = $this->getAuthority()->probablyCan( 'read', $title );
1053
1054 // Checks if page is some kind of content
1055 if ( $title->canExist() ) {
1056 // Gets page objects for the associatedPages namespaces
1057 $subjectPage = $title->getSubjectPage();
1058 $talkPage = $title->getTalkPage();
1059
1060 // Determines if this is a talk page
1061 $isTalk = $title->isTalkPage();
1062
1063 // Generates XML IDs from namespace names
1064 $subjectId = $title->getNamespaceKey( '' );
1065
1066 if ( $subjectId == 'main' ) {
1067 $talkId = 'talk';
1068 } else {
1069 $talkId = "{$subjectId}_talk";
1070 }
1071
1072 // Adds namespace links
1073 if ( $subjectId === 'user' ) {
1074 $subjectMsg = $this->msg( 'nstab-user', $subjectPage->getRootText() );
1075 } else {
1076 // The following messages are used here:
1077 // * nstab-main
1078 // * nstab-media
1079 // * nstab-special
1080 // * nstab-project
1081 // * nstab-image
1082 // * nstab-mediawiki
1083 // * nstab-template
1084 // * nstab-help
1085 // * nstab-category
1086 // * nstab-<subject namespace key>
1087 $subjectMsg = [ "nstab-$subjectId" ];
1088
1089 if ( $subjectPage->isMainPage() ) {
1090 array_unshift( $subjectMsg, 'nstab-mainpage' );
1091 }
1092 }
1093
1094 $associatedPages[$subjectId] = $this->tabAction(
1095 $subjectPage, $subjectMsg, !$isTalk, '', $userCanRead
1096 );
1097 $associatedPages[$subjectId]['context'] = 'subject';
1098 // Use the following messages if defined or talk if not:
1099 // * nstab-talk, nstab-user_talk, nstab-media_talk, nstab-project_talk
1100 // * nstab-image_talk, nstab-mediawiki_talk, nstab-template_talk
1101 // * nstab-help_talk, nstab-category_talk,
1102 // * nstab-<subject namespace key>_talk
1103 $associatedPages[$talkId] = $this->tabAction(
1104 $talkPage, [ "nstab-$talkId", "talk" ], $isTalk, '', $userCanRead
1105 );
1106 $associatedPages[$talkId]['context'] = 'talk';
1107
1108 if ( $userCanRead ) {
1109 // Adds "view" view link
1110 if ( $title->isKnown() ) {
1111 $content_navigation['views']['view'] = $this->tabAction(
1112 $isTalk ? $talkPage : $subjectPage,
1113 'view-view',
1114 ( $onPage && ( $action == 'view' || $action == 'purge' ) ), '', true
1115 );
1116 $content_navigation['views']['view']['text'] = $this->getSkinNavOverrideableLabel(
1117 'view-view'
1118 );
1119 // signal to hide this from simple content_actions
1120 $content_navigation['views']['view']['redundant'] = true;
1121 }
1122
1123 $page = $this->canUseWikiPage() ? $this->getWikiPage() : false;
1124 $isRemoteContent = $page && !$page->isLocal();
1125
1126 // If it is a non-local file, show a link to the file in its own repository
1127 // @todo abstract this for remote content that isn't a file
1128 if ( $isRemoteContent ) {
1129 $content_navigation['views']['view-foreign'] = [
1130 'class' => '',
1131 'text' => $this->getSkinNavOverrideableLabel(
1132 'view-foreign', $page->getWikiDisplayName()
1133 ),
1134 'href' => $page->getSourceURL(),
1135 'primary' => false,
1136 ];
1137 }
1138
1139 // Checks if user can edit the current page if it exists or create it otherwise
1140 if ( $this->getAuthority()->probablyCan( 'edit', $title ) ) {
1141 // Builds CSS class for talk page links
1142 $isTalkClass = $isTalk ? ' istalk' : '';
1143 // Whether the user is editing the page
1144 $isEditing = $onPage && ( $action == 'edit' || $action == 'submit' );
1145 $isRedirect = $page && $page->isRedirect();
1146 // Whether to show the "Add a new section" tab
1147 // Checks if this is a current rev of talk page and is not forced to be hidden
1148 $showNewSection = !$out->forceHideNewSectionLink()
1149 && ( ( $isTalk && !$isRedirect && $out->isRevisionCurrent() ) || $out->showNewSectionLink() );
1150 $section = $request->getVal( 'section' );
1151
1152 if ( $title->exists()
1153 || ( $title->inNamespace( NS_MEDIAWIKI )
1154 && $title->getDefaultMessageText() !== false
1155 )
1156 ) {
1157 $msgKey = $isRemoteContent ? 'edit-local' : 'edit';
1158 } else {
1159 $msgKey = $isRemoteContent ? 'create-local' : 'create';
1160 }
1161 $content_navigation['views']['edit'] = [
1162 'class' => ( $isEditing && ( $section !== 'new' || !$showNewSection )
1163 ? 'selected'
1164 : ''
1165 ) . $isTalkClass,
1166 'text' => $this->getSkinNavOverrideableLabel(
1167 "view-$msgKey"
1168 ),
1169 'single-id' => "ca-$msgKey",
1170 'href' => $title->getLocalURL( $this->editUrlOptions() ),
1171 'primary' => !$isRemoteContent, // don't collapse this in vector
1172 ];
1173
1174 // section link
1175 if ( $showNewSection ) {
1176 // Adds new section link
1177 // $content_navigation['actions']['addsection']
1178 $content_navigation['views']['addsection'] = [
1179 'class' => ( $isEditing && $section == 'new' ) ? 'selected' : false,
1180 'text' => $this->getSkinNavOverrideableLabel(
1181 "action-addsection"
1182 ),
1183 'href' => $title->getLocalURL( 'action=edit&section=new' )
1184 ];
1185 }
1186 // Checks if the page has some kind of viewable source content
1187 } elseif ( $title->hasSourceText() ) {
1188 // Adds view source view link
1189 $content_navigation['views']['viewsource'] = [
1190 'class' => ( $onPage && $action == 'edit' ) ? 'selected' : false,
1191 'text' => $this->getSkinNavOverrideableLabel(
1192 "action-viewsource"
1193 ),
1194 'href' => $title->getLocalURL( $this->editUrlOptions() ),
1195 'primary' => true, // don't collapse this in vector
1196 ];
1197 }
1198
1199 // Checks if the page exists
1200 if ( $title->exists() ) {
1201 // Adds history view link
1202 $content_navigation['views']['history'] = [
1203 'class' => ( $onPage && $action == 'history' ) ? 'selected' : false,
1204 'text' => $this->getSkinNavOverrideableLabel(
1205 'view-history'
1206 ),
1207 'href' => $title->getLocalURL( 'action=history' ),
1208 ];
1209
1210 if ( $this->getAuthority()->probablyCan( 'delete', $title ) ) {
1211 $content_navigation['actions']['delete'] = [
1212 'icon' => 'trash',
1213 'class' => ( $onPage && $action == 'delete' ) ? 'selected' : false,
1214 'text' => $this->getSkinNavOverrideableLabel(
1215 'action-delete'
1216 ),
1217 'href' => $title->getLocalURL( [
1218 'action' => 'delete',
1219 'oldid' => $out->getRevisionId(),
1220 ] )
1221 ];
1222 }
1223
1224 if ( $this->getAuthority()->probablyCan( 'move', $title ) ) {
1225 $moveTitle = SpecialPage::getTitleFor( 'Movepage', $title->getPrefixedDBkey() );
1226 $content_navigation['actions']['move'] = [
1227 'class' => $this->getTitle()->isSpecial( 'Movepage' ) ? 'selected' : false,
1228 'text' => $this->getSkinNavOverrideableLabel(
1229 'action-move'
1230 ),
1231 'icon' => 'move',
1232 'href' => $moveTitle->getLocalURL()
1233 ];
1234 }
1235 } else {
1236 // article doesn't exist or is deleted
1237 if ( $this->getAuthority()->probablyCan( 'deletedhistory', $title ) ) {
1238 $n = $title->getDeletedEditsCount();
1239 if ( $n ) {
1240 $undelTitle = SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedDBkey() );
1241 // If the user can't undelete but can view deleted
1242 // history show them a "View .. deleted" tab instead.
1243 $msgKey = $this->getAuthority()->probablyCan( 'undelete', $title ) ?
1244 'undelete' : 'viewdeleted';
1245 $content_navigation['actions']['undelete'] = [
1246 'class' => $this->getTitle()->isSpecial( 'Undelete' ) ? 'selected' : false,
1247 'text' => $this->getSkinNavOverrideableLabel(
1248 "action-$msgKey", $n
1249 ),
1250 'icon' => 'trash',
1251 'href' => $undelTitle->getLocalURL()
1252 ];
1253 }
1254 }
1255 }
1256
1257 $restrictionStore = $services->getRestrictionStore();
1258 if ( $this->getAuthority()->probablyCan( 'protect', $title ) &&
1259 $restrictionStore->listApplicableRestrictionTypes( $title ) &&
1260 $permissionManager->getNamespaceRestrictionLevels(
1261 $title->getNamespace(),
1262 $performer->getUser()
1263 ) !== [ '' ]
1264 ) {
1265 $isProtected = $restrictionStore->isProtected( $title );
1266 $mode = $isProtected ? 'unprotect' : 'protect';
1267 $content_navigation['actions'][$mode] = [
1268 'class' => ( $onPage && $action == $mode ) ? 'selected' : false,
1269 'text' => $this->getSkinNavOverrideableLabel(
1270 "action-$mode"
1271 ),
1272 'icon' => $isProtected ? 'unLock' : 'lock',
1273 'href' => $title->getLocalURL( "action=$mode" )
1274 ];
1275 }
1276
1277 if ( $this->loggedin && $this->getAuthority()
1278 ->isAllowedAll( 'viewmywatchlist', 'editmywatchlist' )
1279 ) {
1280 /**
1281 * The following actions use messages which, if made particular to
1282 * the any specific skins, would break the Ajax code which makes this
1283 * action happen entirely inline. OutputPage::getJSVars
1284 * defines a set of messages in a javascript object - and these
1285 * messages are assumed to be global for all skins. Without making
1286 * a change to that procedure these messages will have to remain as
1287 * the global versions.
1288 */
1289 $mode = MediaWikiServices::getInstance()->getWatchlistManager()
1290 ->isWatched( $performer, $title ) ? 'unwatch' : 'watch';
1291
1292 // Add the watch/unwatch link.
1293 $content_navigation['actions'][$mode] = $this->getWatchLinkAttrs(
1294 $mode,
1295 $performer,
1296 $title,
1297 $action,
1298 $onPage
1299 );
1300 }
1301 }
1302
1303 // Add language variants
1304 $languageConverterFactory = MediaWikiServices::getInstance()->getLanguageConverterFactory();
1305
1306 if ( $userCanRead && !$languageConverterFactory->isConversionDisabled() ) {
1307 $pageLang = $title->getPageLanguage();
1308 $converter = $languageConverterFactory
1309 ->getLanguageConverter( $pageLang );
1310 // Checks that language conversion is enabled and variants exist
1311 // And if it is not in the special namespace
1312 if ( $converter->hasVariants() ) {
1313 // Gets list of language variants
1314 $variants = $converter->getVariants();
1315 // Gets preferred variant (note that user preference is
1316 // only possible for wiki content language variant)
1317 $preferred = $converter->getPreferredVariant();
1318 if ( $action === 'view' ) {
1319 $params = $request->getQueryValues();
1320 unset( $params['title'] );
1321 } else {
1322 $params = [];
1323 }
1324 // Loops over each variant
1325 foreach ( $variants as $code ) {
1326 // Gets variant name from language code
1327 $varname = $pageLang->getVariantname( $code );
1328 // Appends variant link
1329 $content_navigation['variants'][] = [
1330 'class' => ( $code == $preferred ) ? 'selected' : false,
1331 'text' => $varname,
1332 'href' => $title->getLocalURL( [ 'variant' => $code ] + $params ),
1333 'lang' => LanguageCode::bcp47( $code ),
1334 'hreflang' => LanguageCode::bcp47( $code ),
1335 ];
1336 }
1337 }
1338 }
1339 $namespaces = $associatedPages;
1340 } else {
1341 // If it's not content, and a request URL is set it's got to be a special page
1342 try {
1343 $url = $request->getRequestURL();
1344 } catch ( MWException $e ) {
1345 $url = false;
1346 }
1347 $namespaces['special'] = [
1348 'class' => 'selected',
1349 'text' => $this->msg( 'nstab-special' )->text(),
1350 'href' => $url, // @see: T4457, T4510
1351 'context' => 'subject'
1352 ];
1353 $associatedPages += $this->getSpecialPageAssociatedNavigationLinks( $title );
1354 }
1355
1356 $content_navigation['namespaces'] = $namespaces;
1357 $content_navigation['associated-pages'] = $associatedPages;
1358 $this->runOnSkinTemplateNavigationHooks( $this, $content_navigation );
1359
1360 // Setup xml ids and tooltip info
1361 foreach ( $content_navigation as $section => &$links ) {
1362 foreach ( $links as $key => &$link ) {
1363 // Allow links to set their own id for backwards compatibility reasons.
1364 if ( isset( $link['id'] ) || isset( $link['html' ] ) ) {
1365 continue;
1366 }
1367 $xmlID = $key;
1368 if ( isset( $link['context'] ) && $link['context'] == 'subject' ) {
1369 $xmlID = 'ca-nstab-' . $xmlID;
1370 } elseif ( isset( $link['context'] ) && $link['context'] == 'talk' ) {
1371 $xmlID = 'ca-talk';
1372 $link['rel'] = 'discussion';
1373 } elseif ( $section == 'variants' ) {
1374 $xmlID = 'ca-varlang-' . $xmlID;
1375 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
1376 $link['class'] .= ' ca-variants-' . $link['lang'];
1377 } else {
1378 $xmlID = 'ca-' . $xmlID;
1379 }
1380 $link['id'] = $xmlID;
1381 }
1382 }
1383
1384 # We don't want to give the watch tab an accesskey if the
1385 # page is being edited, because that conflicts with the
1386 # accesskey on the watch checkbox. We also don't want to
1387 # give the edit tab an accesskey, because that's fairly
1388 # superfluous and conflicts with an accesskey (Ctrl-E) often
1389 # used for editing in Safari.
1390 if ( in_array( $action, [ 'edit', 'submit' ] ) ) {
1391 if ( isset( $content_navigation['views']['edit'] ) ) {
1392 $content_navigation['views']['edit']['tooltiponly'] = true;
1393 }
1394 if ( isset( $content_navigation['actions']['watch'] ) ) {
1395 $content_navigation['actions']['watch']['tooltiponly'] = true;
1396 }
1397 if ( isset( $content_navigation['actions']['unwatch'] ) ) {
1398 $content_navigation['actions']['unwatch']['tooltiponly'] = true;
1399 }
1400 }
1401
1402 $this->contentNavigationCached = $content_navigation;
1403 return $content_navigation;
1404 }
1405
1406 /**
1407 * Return a list of pages that have been marked as related to/associated with
1408 * the special page for display.
1409 *
1410 * @param Title $title
1411 * @return array
1412 */
1413 private function getSpecialPageAssociatedNavigationLinks( Title $title ): array {
1414 $specialAssociatedNavigationLinks = [];
1415 $specialFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1416 $special = $specialFactory->getPage( $title->getText() );
1417 if ( $special === null ) {
1418 // not a valid special page
1419 return [];
1420 }
1421 $special->setContext( $this );
1422 $associatedNavigationLinks = $special->getAssociatedNavigationLinks();
1423 // If there are no subpages, we should not render
1424 if ( count( $associatedNavigationLinks ) === 0 ) {
1425 return [];
1426 }
1427
1428 foreach ( $associatedNavigationLinks as $i => $relatedTitleText ) {
1429 $relatedTitle = Title::newFromText( $relatedTitleText );
1430 $special = $specialFactory->getPage( $relatedTitle->getText() );
1431 if ( $special === null ) {
1432 $text = $relatedTitle->getText();
1433 } else {
1434 $text = $special->getShortDescription( $relatedTitle->getSubpageText() );
1435 }
1436 $specialAssociatedNavigationLinks['special-specialAssociatedNavigationLinks-link-' . $i ] = [
1437 'text' => $text,
1438 'href' => $relatedTitle->getLocalURL(),
1439 'class' => $relatedTitle->fixSpecialName()->equals( $title->fixSpecialName() ) ? 'selected' : '',
1440 ];
1441 }
1442 return $specialAssociatedNavigationLinks;
1443 }
1444
1445 /**
1446 * an array of edit links by default used for the tabs
1447 * @param array $content_navigation
1448 * @return array
1449 */
1450 private function buildContentActionUrls( $content_navigation ) {
1451 // content_actions has been replaced with content_navigation for backwards
1452 // compatibility and also for skins that just want simple tabs content_actions
1453 // is now built by flattening the content_navigation arrays into one
1454
1455 $content_actions = [];
1456
1457 foreach ( $content_navigation as $links ) {
1458 foreach ( $links as $key => $value ) {
1459 if ( isset( $value['redundant'] ) && $value['redundant'] ) {
1460 // Redundant tabs are dropped from content_actions
1461 continue;
1462 }
1463
1464 // content_actions used to have ids built using the "ca-$key" pattern
1465 // so the xmlID based id is much closer to the actual $key that we want
1466 // for that reason we'll just strip out the ca- if present and use
1467 // the latter potion of the "id" as the $key
1468 if ( isset( $value['id'] ) && substr( $value['id'], 0, 3 ) == 'ca-' ) {
1469 $key = substr( $value['id'], 3 );
1470 }
1471
1472 if ( isset( $content_actions[$key] ) ) {
1473 wfDebug( __METHOD__ . ": Found a duplicate key for $key while flattening " .
1474 "content_navigation into content_actions." );
1475 continue;
1476 }
1477
1478 $content_actions[$key] = $value;
1479 }
1480 }
1481
1482 return $content_actions;
1483 }
1484
1485 /**
1486 * Insert legacy menu items from content navigation into the personal toolbar.
1487 *
1488 * @internal
1489 *
1490 * @param array $contentNavigation
1491 * @return array
1492 */
1493 final protected function injectLegacyMenusIntoPersonalTools(
1494 array $contentNavigation
1495 ): array {
1496 $userMenu = $contentNavigation['user-menu'] ?? [];
1497 // userpage is only defined for logged-in users, and wfArrayInsertAfter requires the
1498 // $after parameter to be a known key in the array.
1499 if ( isset( $contentNavigation['user-menu']['userpage'] ) && isset( $contentNavigation['notifications'] ) ) {
1500 $userMenu = wfArrayInsertAfter(
1501 $userMenu,
1502 $contentNavigation['notifications'],
1503 'userpage'
1504 );
1505 }
1506 if ( isset( $contentNavigation['user-interface-preferences'] ) ) {
1507 return array_merge(
1508 $contentNavigation['user-interface-preferences'],
1509 $userMenu
1510 );
1511 }
1512 return $userMenu;
1513 }
1514
1515 /**
1516 * Build the personal urls array.
1517 *
1518 * @internal
1519 *
1520 * @param array $contentNavigation
1521 * @return array
1522 */
1523 private function makeSkinTemplatePersonalUrls(
1524 array $contentNavigation
1525 ): array {
1526 if ( isset( $contentNavigation['user-menu'] ) ) {
1527 return $this->injectLegacyMenusIntoPersonalTools( $contentNavigation );
1528 }
1529 return [];
1530 }
1531
1532 /**
1533 * @since 1.35
1534 * @param array $attrs (optional) will be passed to tooltipAndAccesskeyAttribs
1535 * and decorate the resulting input
1536 * @return string of HTML input
1537 */
1538 public function makeSearchInput( $attrs = [] ) {
1539 // It's possible that getTemplateData might be calling
1540 // Skin::makeSearchInput. To avoid infinite recursion create a
1541 // new instance of the search component here.
1542 $searchBox = $this->getComponent( 'search-box' );
1543 $data = $searchBox->getTemplateData();
1544
1545 return Html::element( 'input',
1546 $data[ 'array-input-attributes' ] + $attrs
1547 );
1548 }
1549
1550 /**
1551 * @since 1.35
1552 * @param string $mode representing the type of button wanted
1553 * either `go`, `fulltext` or `image`
1554 * @param array $attrs (optional)
1555 * @return string of HTML button
1556 */
1557 final public function makeSearchButton( $mode, $attrs = [] ) {
1558 // It's possible that getTemplateData might be calling
1559 // Skin::makeSearchInput. To avoid infinite recursion create a
1560 // new instance of the search component here.
1561 $searchBox = $this->getComponent( 'search-box' );
1562 $searchData = $searchBox->getTemplateData();
1563
1564 switch ( $mode ) {
1565 case 'go':
1566 $attrs['value'] ??= $this->msg( 'searcharticle' )->text();
1567 return Html::element(
1568 'input',
1569 array_merge(
1570 $searchData[ 'array-button-go-attributes' ], $attrs
1571 )
1572 );
1573 case 'fulltext':
1574 $attrs['value'] ??= $this->msg( 'searchbutton' )->text();
1575 return Html::element(
1576 'input',
1577 array_merge(
1578 $searchData[ 'array-button-fulltext-attributes' ], $attrs
1579 )
1580 );
1581 case 'image':
1582 $buttonAttrs = [
1583 'type' => 'submit',
1584 'name' => 'button',
1585 ];
1586 $buttonAttrs = array_merge(
1587 $buttonAttrs,
1588 Linker::tooltipAndAccesskeyAttribs( 'search-fulltext' ),
1589 $attrs
1590 );
1591 unset( $buttonAttrs['src'] );
1592 unset( $buttonAttrs['alt'] );
1593 unset( $buttonAttrs['width'] );
1594 unset( $buttonAttrs['height'] );
1595 $imgAttrs = [
1596 'src' => $attrs['src'],
1597 'alt' => $attrs['alt'] ?? $this->msg( 'searchbutton' )->text(),
1598 'width' => $attrs['width'] ?? null,
1599 'height' => $attrs['height'] ?? null,
1600 ];
1601 return Html::rawElement( 'button', $buttonAttrs, Html::element( 'img', $imgAttrs ) );
1602 default:
1603 throw new InvalidArgumentException( 'Unknown mode passed to ' . __METHOD__ );
1604 }
1605 }
1606
1607 /**
1608 * @return bool
1609 */
1610 private function isSpecialContributeShowable(): bool {
1611 return ContributeFactory::isEnabledOnCurrentSkin(
1612 $this,
1613 $this->getConfig()->get( MainConfigNames::SpecialContributeSkinsEnabled )
1614 );
1615 }
1616
1617 /**
1618 * @param array &$personal_urls
1619 * @param string $key
1620 * @param string|null $userName
1621 * @param bool $active
1622 *
1623 * @return array
1624 */
1625 private function makeContributionsLink(
1626 array &$personal_urls,
1627 string $key,
1628 ?string $userName = null,
1629 bool $active = false
1630 ): array {
1631 $isSpecialContributeShowable = $this->isSpecialContributeShowable();
1632 $subpage = $userName ?? false;
1633 $user = $this->getUser();
1634 // If the "Contribute" page is showable and the user is anon. or has no edit count,
1635 // direct them to the "Contribute" page instead of the "Contributions" or "Mycontributions" pages.
1636 // Explanation:
1637 // a. For logged-in users: In wikis where the "Contribute" page is enabled, we only want
1638 // to navigate logged-in users to the "Contribute", when they have done no edits. Otherwise, we
1639 // want to navigate them to the "Mycontributions" page to easily access their edits/contributions.
1640 // Currently, the "Contribute" page is used as target for all logged-in users.
1641 // b. For anon. users: In wikis where the "Contribute" page is enabled, we still navigate the
1642 // anonymous users to the "Contribute" page.
1643 // Task: T369041
1644 if ( $isSpecialContributeShowable && (int)$user->getEditCount() === 0 ) {
1645 $href = SkinComponentUtils::makeSpecialUrlSubpage(
1646 'Contribute',
1647 false
1648 );
1649 $personal_urls['contribute'] = [
1650 'text' => $this->msg( 'contribute' )->text(),
1651 'href' => $href,
1652 'active' => $href == $this->getTitle()->getLocalURL(),
1653 'icon' => 'edit'
1654 ];
1655 } else {
1656 $href = SkinComponentUtils::makeSpecialUrlSubpage(
1657 $subpage !== false ? 'Contributions' : 'Mycontributions',
1658 $subpage
1659 );
1660 $personal_urls[$key] = [
1661 'text' => $this->msg( $key )->text(),
1662 'href' => $href,
1663 'active' => $active,
1664 'icon' => 'userContributions'
1665 ];
1666 }
1667 return $personal_urls;
1668 }
1669
1670 }