SkinTemplate.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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. use MediaWiki\Auth\AuthManager;
  21. use MediaWiki\MediaWikiServices;
  22. /**
  23. * Base class for template-based skins.
  24. *
  25. * Template-filler skin base class
  26. * Formerly generic PHPTal (http://phptal.sourceforge.net/) skin
  27. * Based on Brion's smarty skin
  28. * @copyright Copyright © Gabriel Wicke -- http://www.aulinx.de/
  29. *
  30. * @todo Needs some serious refactoring into functions that correspond
  31. * to the computations individual esi snippets need. Most importantly no body
  32. * parsing for most of those of course.
  33. *
  34. * @ingroup Skins
  35. */
  36. class SkinTemplate extends Skin {
  37. /**
  38. * @var string Name of our skin, it probably needs to be all lower case.
  39. * Child classes should override the default.
  40. */
  41. public $skinname = 'monobook';
  42. /**
  43. * @var string For QuickTemplate, the name of the subclass which will
  44. * actually fill the template. Child classes should override the default.
  45. */
  46. public $template = QuickTemplate::class;
  47. public $thispage;
  48. public $titletxt;
  49. public $userpage;
  50. public $thisquery;
  51. public $loggedin;
  52. public $username;
  53. public $userpageUrlDetails;
  54. /**
  55. * Create the template engine object; we feed it a bunch of data
  56. * and eventually it spits out some HTML. Should have interface
  57. * roughly equivalent to PHPTAL 0.7.
  58. *
  59. * @param string $classname
  60. * @return QuickTemplate
  61. * @private
  62. */
  63. function setupTemplate( $classname ) {
  64. return new $classname( $this->getConfig() );
  65. }
  66. /**
  67. * Generates array of language links for the current page
  68. *
  69. * @return array
  70. */
  71. public function getLanguages() {
  72. global $wgHideInterlanguageLinks;
  73. if ( $wgHideInterlanguageLinks ) {
  74. return [];
  75. }
  76. $userLang = $this->getLanguage();
  77. $languageLinks = [];
  78. foreach ( $this->getOutput()->getLanguageLinks() as $languageLinkText ) {
  79. $class = 'interlanguage-link interwiki-' . explode( ':', $languageLinkText, 2 )[0];
  80. $languageLinkTitle = Title::newFromText( $languageLinkText );
  81. if ( $languageLinkTitle ) {
  82. $ilInterwikiCode = $languageLinkTitle->getInterwiki();
  83. $ilLangName = Language::fetchLanguageName( $ilInterwikiCode );
  84. if ( strval( $ilLangName ) === '' ) {
  85. $ilDisplayTextMsg = wfMessage( "interlanguage-link-$ilInterwikiCode" );
  86. if ( !$ilDisplayTextMsg->isDisabled() ) {
  87. // Use custom MW message for the display text
  88. $ilLangName = $ilDisplayTextMsg->text();
  89. } else {
  90. // Last resort: fallback to the language link target
  91. $ilLangName = $languageLinkText;
  92. }
  93. } else {
  94. // Use the language autonym as display text
  95. $ilLangName = $this->formatLanguageName( $ilLangName );
  96. }
  97. // CLDR extension or similar is required to localize the language name;
  98. // otherwise we'll end up with the autonym again.
  99. $ilLangLocalName = Language::fetchLanguageName(
  100. $ilInterwikiCode,
  101. $userLang->getCode()
  102. );
  103. $languageLinkTitleText = $languageLinkTitle->getText();
  104. if ( $ilLangLocalName === '' ) {
  105. $ilFriendlySiteName = wfMessage( "interlanguage-link-sitename-$ilInterwikiCode" );
  106. if ( !$ilFriendlySiteName->isDisabled() ) {
  107. if ( $languageLinkTitleText === '' ) {
  108. $ilTitle = wfMessage(
  109. 'interlanguage-link-title-nonlangonly',
  110. $ilFriendlySiteName->text()
  111. )->text();
  112. } else {
  113. $ilTitle = wfMessage(
  114. 'interlanguage-link-title-nonlang',
  115. $languageLinkTitleText,
  116. $ilFriendlySiteName->text()
  117. )->text();
  118. }
  119. } else {
  120. // we have nothing friendly to put in the title, so fall back to
  121. // displaying the interlanguage link itself in the title text
  122. // (similar to what is done in page content)
  123. $ilTitle = $languageLinkTitle->getInterwiki() .
  124. ":$languageLinkTitleText";
  125. }
  126. } elseif ( $languageLinkTitleText === '' ) {
  127. $ilTitle = wfMessage(
  128. 'interlanguage-link-title-langonly',
  129. $ilLangLocalName
  130. )->text();
  131. } else {
  132. $ilTitle = wfMessage(
  133. 'interlanguage-link-title',
  134. $languageLinkTitleText,
  135. $ilLangLocalName
  136. )->text();
  137. }
  138. $ilInterwikiCodeBCP47 = LanguageCode::bcp47( $ilInterwikiCode );
  139. $languageLink = [
  140. 'href' => $languageLinkTitle->getFullURL(),
  141. 'text' => $ilLangName,
  142. 'title' => $ilTitle,
  143. 'class' => $class,
  144. 'link-class' => 'interlanguage-link-target',
  145. 'lang' => $ilInterwikiCodeBCP47,
  146. 'hreflang' => $ilInterwikiCodeBCP47,
  147. ];
  148. Hooks::run(
  149. 'SkinTemplateGetLanguageLink',
  150. [ &$languageLink, $languageLinkTitle, $this->getTitle(), $this->getOutput() ]
  151. );
  152. $languageLinks[] = $languageLink;
  153. }
  154. }
  155. return $languageLinks;
  156. }
  157. /**
  158. * @return QuickTemplate
  159. */
  160. protected function setupTemplateForOutput() {
  161. $request = $this->getRequest();
  162. $user = $this->getUser();
  163. $title = $this->getTitle();
  164. $tpl = $this->setupTemplate( $this->template );
  165. $this->thispage = $title->getPrefixedDBkey();
  166. $this->titletxt = $title->getPrefixedText();
  167. $this->userpage = $user->getUserPage()->getPrefixedText();
  168. $query = [];
  169. if ( !$request->wasPosted() ) {
  170. $query = $request->getValues();
  171. unset( $query['title'] );
  172. unset( $query['returnto'] );
  173. unset( $query['returntoquery'] );
  174. }
  175. $this->thisquery = wfArrayToCgi( $query );
  176. $this->loggedin = $user->isLoggedIn();
  177. $this->username = $user->getName();
  178. if ( $this->loggedin ) {
  179. $this->userpageUrlDetails = self::makeUrlDetails( $this->userpage );
  180. } else {
  181. # This won't be used in the standard skins, but we define it to preserve the interface
  182. # To save time, we check for existence
  183. $this->userpageUrlDetails = self::makeKnownUrlDetails( $this->userpage );
  184. }
  185. return $tpl;
  186. }
  187. /**
  188. * Initialize various variables and generate the template
  189. */
  190. function outputPage() {
  191. Profiler::instance()->setAllowOutput();
  192. $out = $this->getOutput();
  193. $this->initPage( $out );
  194. $tpl = $this->prepareQuickTemplate();
  195. // execute template
  196. $res = $tpl->execute();
  197. // result may be an error
  198. $this->printOrError( $res );
  199. }
  200. /**
  201. * Wrap the body text with language information and identifiable element
  202. *
  203. * @param Title $title
  204. * @param string $html body text
  205. * @return string html
  206. */
  207. protected function wrapHTML( $title, $html ) {
  208. # An ID that includes the actual body text; without categories, contentSub, ...
  209. $realBodyAttribs = [ 'id' => 'mw-content-text' ];
  210. # Add a mw-content-ltr/rtl class to be able to style based on text
  211. # direction when the content is different from the UI language (only
  212. # when viewing)
  213. # Most information on special pages and file pages is in user language,
  214. # rather than content language, so those will not get this
  215. if ( Action::getActionName( $this ) === 'view' &&
  216. ( !$title->inNamespaces( NS_SPECIAL, NS_FILE ) || $title->isRedirect() ) ) {
  217. $pageLang = $title->getPageViewLanguage();
  218. $realBodyAttribs['lang'] = $pageLang->getHtmlCode();
  219. $realBodyAttribs['dir'] = $pageLang->getDir();
  220. $realBodyAttribs['class'] = 'mw-content-' . $pageLang->getDir();
  221. }
  222. return Html::rawElement( 'div', $realBodyAttribs, $html );
  223. }
  224. /**
  225. * initialize various variables and generate the template
  226. *
  227. * @since 1.23
  228. * @return QuickTemplate The template to be executed by outputPage
  229. */
  230. protected function prepareQuickTemplate() {
  231. global $wgScript, $wgStylePath, $wgMimeType,
  232. $wgSitename, $wgLogo, $wgMaxCredits,
  233. $wgShowCreditsIfMax, $wgArticlePath,
  234. $wgScriptPath, $wgServer;
  235. $title = $this->getTitle();
  236. $request = $this->getRequest();
  237. $out = $this->getOutput();
  238. $tpl = $this->setupTemplateForOutput();
  239. $tpl->set( 'title', $out->getPageTitle() );
  240. $tpl->set( 'pagetitle', $out->getHTMLTitle() );
  241. $tpl->set( 'displaytitle', $out->mPageLinkTitle );
  242. $tpl->set( 'thispage', $this->thispage );
  243. $tpl->set( 'titleprefixeddbkey', $this->thispage );
  244. $tpl->set( 'titletext', $title->getText() );
  245. $tpl->set( 'articleid', $title->getArticleID() );
  246. $tpl->set( 'isarticle', $out->isArticle() );
  247. $subpagestr = $this->subPageSubtitle();
  248. if ( $subpagestr !== '' ) {
  249. $subpagestr = '<span class="subpages">' . $subpagestr . '</span>';
  250. }
  251. $tpl->set( 'subtitle', $subpagestr . $out->getSubtitle() );
  252. $undelete = $this->getUndeleteLink();
  253. if ( $undelete === '' ) {
  254. $tpl->set( 'undelete', '' );
  255. } else {
  256. $tpl->set( 'undelete', '<span class="subpages">' . $undelete . '</span>' );
  257. }
  258. $tpl->set( 'catlinks', $this->getCategories() );
  259. if ( $out->isSyndicated() ) {
  260. $feeds = [];
  261. foreach ( $out->getSyndicationLinks() as $format => $link ) {
  262. $feeds[$format] = [
  263. // Messages: feed-atom, feed-rss
  264. 'text' => $this->msg( "feed-$format" )->text(),
  265. 'href' => $link
  266. ];
  267. }
  268. $tpl->set( 'feeds', $feeds );
  269. } else {
  270. $tpl->set( 'feeds', false );
  271. }
  272. $tpl->set( 'mimetype', $wgMimeType );
  273. $tpl->set( 'charset', 'UTF-8' );
  274. $tpl->set( 'wgScript', $wgScript );
  275. $tpl->set( 'skinname', $this->skinname );
  276. $tpl->set( 'skinclass', static::class );
  277. $tpl->set( 'skin', $this );
  278. $tpl->set( 'stylename', $this->stylename );
  279. $tpl->set( 'printable', $out->isPrintable() );
  280. $tpl->set( 'handheld', $request->getBool( 'handheld' ) );
  281. $tpl->set( 'loggedin', $this->loggedin );
  282. $tpl->set( 'notspecialpage', !$title->isSpecialPage() );
  283. $tpl->set( 'searchaction', $this->getSearchLink() );
  284. $tpl->set( 'searchtitle', SpecialPage::getTitleFor( 'Search' )->getPrefixedDBkey() );
  285. $tpl->set( 'search', trim( $request->getVal( 'search' ) ) );
  286. $tpl->set( 'stylepath', $wgStylePath );
  287. $tpl->set( 'articlepath', $wgArticlePath );
  288. $tpl->set( 'scriptpath', $wgScriptPath );
  289. $tpl->set( 'serverurl', $wgServer );
  290. $tpl->set( 'logopath', $wgLogo );
  291. $tpl->set( 'sitename', $wgSitename );
  292. $userLang = $this->getLanguage();
  293. $userLangCode = $userLang->getHtmlCode();
  294. $userLangDir = $userLang->getDir();
  295. $tpl->set( 'lang', $userLangCode );
  296. $tpl->set( 'dir', $userLangDir );
  297. $tpl->set( 'rtl', $userLang->isRTL() );
  298. $tpl->set( 'capitalizeallnouns', $userLang->capitalizeAllNouns() ? ' capitalize-all-nouns' : '' );
  299. $tpl->set( 'showjumplinks', true ); // showjumplinks preference has been removed
  300. $tpl->set( 'username', $this->loggedin ? $this->username : null );
  301. $tpl->set( 'userpage', $this->userpage );
  302. $tpl->set( 'userpageurl', $this->userpageUrlDetails['href'] );
  303. $tpl->set( 'userlang', $userLangCode );
  304. // Users can have their language set differently than the
  305. // content of the wiki. For these users, tell the web browser
  306. // that interface elements are in a different language.
  307. $tpl->set( 'userlangattributes', '' );
  308. $tpl->set( 'specialpageattributes', '' ); # obsolete
  309. // Used by VectorBeta to insert HTML before content but after the
  310. // heading for the page title. Defaults to empty string.
  311. $tpl->set( 'prebodyhtml', '' );
  312. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  313. if (
  314. $userLangCode !== $contLang->getHtmlCode() ||
  315. $userLangDir !== $contLang->getDir()
  316. ) {
  317. $escUserlang = htmlspecialchars( $userLangCode );
  318. $escUserdir = htmlspecialchars( $userLangDir );
  319. // Attributes must be in double quotes because htmlspecialchars() doesn't
  320. // escape single quotes
  321. $attrs = " lang=\"$escUserlang\" dir=\"$escUserdir\"";
  322. $tpl->set( 'userlangattributes', $attrs );
  323. }
  324. $tpl->set( 'newtalk', $this->getNewtalks() );
  325. $tpl->set( 'logo', $this->logoText() );
  326. $tpl->set( 'copyright', false );
  327. // No longer used
  328. $tpl->set( 'viewcount', false );
  329. $tpl->set( 'lastmod', false );
  330. $tpl->set( 'credits', false );
  331. $tpl->set( 'numberofwatchingusers', false );
  332. if ( $title->exists() ) {
  333. if ( $out->isArticle() && $out->isRevisionCurrent() ) {
  334. if ( $wgMaxCredits != 0 ) {
  335. /** @var CreditsAction $action */
  336. $action = Action::factory(
  337. 'credits', $this->getWikiPage(), $this->getContext() );
  338. '@phan-var CreditsAction $action';
  339. $tpl->set( 'credits',
  340. $action->getCredits( $wgMaxCredits, $wgShowCreditsIfMax ) );
  341. } else {
  342. $tpl->set( 'lastmod', $this->lastModified() );
  343. }
  344. }
  345. if ( $out->showsCopyright() ) {
  346. $tpl->set( 'copyright', $this->getCopyright() );
  347. }
  348. }
  349. $tpl->set( 'copyrightico', $this->getCopyrightIcon() );
  350. $tpl->set( 'poweredbyico', $this->getPoweredBy() );
  351. $tpl->set( 'disclaimer', $this->disclaimerLink() );
  352. $tpl->set( 'privacy', $this->privacyLink() );
  353. $tpl->set( 'about', $this->aboutLink() );
  354. $tpl->set( 'footerlinks', [
  355. 'info' => [
  356. 'lastmod',
  357. 'numberofwatchingusers',
  358. 'credits',
  359. 'copyright',
  360. ],
  361. 'places' => [
  362. 'privacy',
  363. 'about',
  364. 'disclaimer',
  365. ],
  366. ] );
  367. global $wgFooterIcons;
  368. $tpl->set( 'footericons', $wgFooterIcons );
  369. foreach ( $tpl->data['footericons'] as $footerIconsKey => &$footerIconsBlock ) {
  370. if ( count( $footerIconsBlock ) > 0 ) {
  371. foreach ( $footerIconsBlock as &$footerIcon ) {
  372. if ( isset( $footerIcon['src'] ) ) {
  373. if ( !isset( $footerIcon['width'] ) ) {
  374. $footerIcon['width'] = 88;
  375. }
  376. if ( !isset( $footerIcon['height'] ) ) {
  377. $footerIcon['height'] = 31;
  378. }
  379. }
  380. }
  381. } else {
  382. unset( $tpl->data['footericons'][$footerIconsKey] );
  383. }
  384. }
  385. $tpl->set( 'indicators', $out->getIndicators() );
  386. $tpl->set( 'sitenotice', $this->getSiteNotice() );
  387. $tpl->set( 'printfooter', $this->printSource() );
  388. // Wrap the bodyText with #mw-content-text element
  389. $out->mBodytext = $this->wrapHTML( $title, $out->mBodytext );
  390. $tpl->set( 'bodytext', $out->mBodytext );
  391. $language_urls = $this->getLanguages();
  392. if ( count( $language_urls ) ) {
  393. $tpl->set( 'language_urls', $language_urls );
  394. } else {
  395. $tpl->set( 'language_urls', false );
  396. }
  397. # Personal toolbar
  398. $tpl->set( 'personal_urls', $this->buildPersonalUrls() );
  399. $content_navigation = $this->buildContentNavigationUrls();
  400. $content_actions = $this->buildContentActionUrls( $content_navigation );
  401. $tpl->set( 'content_navigation', $content_navigation );
  402. $tpl->set( 'content_actions', $content_actions );
  403. $tpl->set( 'sidebar', $this->buildSidebar() );
  404. $tpl->set( 'nav_urls', $this->buildNavUrls() );
  405. // Do this last in case hooks above add bottom scripts
  406. $tpl->set( 'bottomscripts', $this->bottomScripts() );
  407. // Set the head scripts near the end, in case the above actions resulted in added scripts
  408. $tpl->set( 'headelement', $out->headElement( $this ) );
  409. $tpl->set( 'debug', '' );
  410. $tpl->set( 'debughtml', $this->generateDebugHTML() );
  411. $tpl->set( 'reporttime', wfReportTime( $out->getCSPNonce() ) );
  412. // Avoid PHP 7.1 warning of passing $this by reference
  413. $skinTemplate = $this;
  414. // original version by hansm
  415. if ( !Hooks::run( 'SkinTemplateOutputPageBeforeExec', [ &$skinTemplate, &$tpl ] ) ) {
  416. wfDebug( __METHOD__ . ": Hook SkinTemplateOutputPageBeforeExec broke outputPage execution!\n" );
  417. }
  418. // Set the bodytext to another key so that skins can just output it on its own
  419. // and output printfooter and debughtml separately
  420. $tpl->set( 'bodycontent', $tpl->data['bodytext'] );
  421. // Append printfooter and debughtml onto bodytext so that skins that
  422. // were already using bodytext before they were split out don't suddenly
  423. // start not outputting information.
  424. $tpl->data['bodytext'] .= Html::rawElement(
  425. 'div',
  426. [ 'class' => 'printfooter' ],
  427. "\n{$tpl->data['printfooter']}"
  428. ) . "\n";
  429. $tpl->data['bodytext'] .= $tpl->data['debughtml'];
  430. // allow extensions adding stuff after the page content.
  431. // See Skin::afterContentHook() for further documentation.
  432. $tpl->set( 'dataAfterContent', $this->afterContentHook() );
  433. return $tpl;
  434. }
  435. /**
  436. * Get the HTML for the p-personal list
  437. * @return string
  438. */
  439. public function getPersonalToolsList() {
  440. return $this->makePersonalToolsList();
  441. }
  442. /**
  443. * Get the HTML for the personal tools list
  444. *
  445. * @since 1.31
  446. *
  447. * @param array|null $personalTools
  448. * @param array $options
  449. * @return string
  450. */
  451. public function makePersonalToolsList( $personalTools = null, $options = [] ) {
  452. $tpl = $this->setupTemplateForOutput();
  453. $tpl->set( 'personal_urls', $this->buildPersonalUrls() );
  454. $html = '';
  455. if ( $personalTools === null ) {
  456. $personalTools = ( $tpl instanceof BaseTemplate )
  457. ? $tpl->getPersonalTools()
  458. : [];
  459. }
  460. foreach ( $personalTools as $key => $item ) {
  461. $html .= $tpl->makeListItem( $key, $item, $options );
  462. }
  463. return $html;
  464. }
  465. /**
  466. * Get personal tools for the user
  467. *
  468. * @since 1.31
  469. *
  470. * @return array Array of personal tools
  471. */
  472. public function getStructuredPersonalTools() {
  473. $tpl = $this->setupTemplateForOutput();
  474. $tpl->set( 'personal_urls', $this->buildPersonalUrls() );
  475. return ( $tpl instanceof BaseTemplate ) ? $tpl->getPersonalTools() : [];
  476. }
  477. /**
  478. * Format language name for use in sidebar interlanguage links list.
  479. * By default it is capitalized.
  480. *
  481. * @param string $name Language name, e.g. "English" or "español"
  482. * @return string
  483. * @private
  484. */
  485. function formatLanguageName( $name ) {
  486. return $this->getLanguage()->ucfirst( $name );
  487. }
  488. /**
  489. * Output the string, or print error message if it's
  490. * an error object of the appropriate type.
  491. * For the base class, assume strings all around.
  492. *
  493. * @param string $str
  494. * @private
  495. */
  496. function printOrError( $str ) {
  497. echo $str;
  498. }
  499. /**
  500. * Output a boolean indicating if buildPersonalUrls should output separate
  501. * login and create account links or output a combined link
  502. * By default we simply return a global config setting that affects most skins
  503. * This is setup as a method so that like with $wgLogo and getLogo() a skin
  504. * can override this setting and always output one or the other if it has
  505. * a reason it can't output one of the two modes.
  506. * @return bool
  507. */
  508. function useCombinedLoginLink() {
  509. global $wgUseCombinedLoginLink;
  510. return $wgUseCombinedLoginLink;
  511. }
  512. /**
  513. * build array of urls for personal toolbar
  514. * @return array
  515. */
  516. protected function buildPersonalUrls() {
  517. $title = $this->getTitle();
  518. $request = $this->getRequest();
  519. $pageurl = $title->getLocalURL();
  520. $authManager = AuthManager::singleton();
  521. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  522. /* set up the default links for the personal toolbar */
  523. $personal_urls = [];
  524. # Due to T34276, if a user does not have read permissions,
  525. # $this->getTitle() will just give Special:Badtitle, which is
  526. # not especially useful as a returnto parameter. Use the title
  527. # from the request instead, if there was one.
  528. if ( $permissionManager->userHasRight( $this->getUser(), 'read' ) ) {
  529. $page = $this->getTitle();
  530. } else {
  531. $page = Title::newFromText( $request->getVal( 'title', '' ) );
  532. }
  533. $page = $request->getVal( 'returnto', $page );
  534. $returnto = [];
  535. if ( strval( $page ) !== '' ) {
  536. $returnto['returnto'] = $page;
  537. $query = $request->getVal( 'returntoquery', $this->thisquery );
  538. $paramsArray = wfCgiToArray( $query );
  539. $query = wfArrayToCgi( $paramsArray );
  540. if ( $query != '' ) {
  541. $returnto['returntoquery'] = $query;
  542. }
  543. }
  544. if ( $this->loggedin ) {
  545. $personal_urls['userpage'] = [
  546. 'text' => $this->username,
  547. 'href' => &$this->userpageUrlDetails['href'],
  548. 'class' => $this->userpageUrlDetails['exists'] ? false : 'new',
  549. 'exists' => $this->userpageUrlDetails['exists'],
  550. 'active' => ( $this->userpageUrlDetails['href'] == $pageurl ),
  551. 'dir' => 'auto'
  552. ];
  553. $usertalkUrlDetails = $this->makeTalkUrlDetails( $this->userpage );
  554. $personal_urls['mytalk'] = [
  555. 'text' => $this->msg( 'mytalk' )->text(),
  556. 'href' => &$usertalkUrlDetails['href'],
  557. 'class' => $usertalkUrlDetails['exists'] ? false : 'new',
  558. 'exists' => $usertalkUrlDetails['exists'],
  559. 'active' => ( $usertalkUrlDetails['href'] == $pageurl )
  560. ];
  561. $href = self::makeSpecialUrl( 'Preferences' );
  562. $personal_urls['preferences'] = [
  563. 'text' => $this->msg( 'mypreferences' )->text(),
  564. 'href' => $href,
  565. 'active' => ( $href == $pageurl )
  566. ];
  567. if ( $permissionManager->userHasRight( $this->getUser(), 'viewmywatchlist' ) ) {
  568. $href = self::makeSpecialUrl( 'Watchlist' );
  569. $personal_urls['watchlist'] = [
  570. 'text' => $this->msg( 'mywatchlist' )->text(),
  571. 'href' => $href,
  572. 'active' => ( $href == $pageurl )
  573. ];
  574. }
  575. # We need to do an explicit check for Special:Contributions, as we
  576. # have to match both the title, and the target, which could come
  577. # from request values (Special:Contributions?target=Jimbo_Wales)
  578. # or be specified in "sub page" form
  579. # (Special:Contributions/Jimbo_Wales). The plot
  580. # thickens, because the Title object is altered for special pages,
  581. # so it doesn't contain the original alias-with-subpage.
  582. $origTitle = Title::newFromText( $request->getText( 'title' ) );
  583. if ( $origTitle instanceof Title && $origTitle->isSpecialPage() ) {
  584. list( $spName, $spPar ) =
  585. MediaWikiServices::getInstance()->getSpecialPageFactory()->
  586. resolveAlias( $origTitle->getText() );
  587. $active = $spName == 'Contributions'
  588. && ( ( $spPar && $spPar == $this->username )
  589. || $request->getText( 'target' ) == $this->username );
  590. } else {
  591. $active = false;
  592. }
  593. $href = self::makeSpecialUrlSubpage( 'Contributions', $this->username );
  594. $personal_urls['mycontris'] = [
  595. 'text' => $this->msg( 'mycontris' )->text(),
  596. 'href' => $href,
  597. 'active' => $active
  598. ];
  599. // if we can't set the user, we can't unset it either
  600. if ( $request->getSession()->canSetUser() ) {
  601. $personal_urls['logout'] = [
  602. 'text' => $this->msg( 'pt-userlogout' )->text(),
  603. 'href' => self::makeSpecialUrl( 'Userlogout',
  604. // Note: userlogout link must always contain an & character, otherwise we might not be able
  605. // to detect a buggy precaching proxy (T19790)
  606. ( $title->isSpecial( 'Preferences' ) ? [] : $returnto ) ),
  607. 'active' => false
  608. ];
  609. }
  610. } else {
  611. $useCombinedLoginLink = $this->useCombinedLoginLink();
  612. if ( !$authManager->canCreateAccounts() || !$authManager->canAuthenticateNow() ) {
  613. // don't show combined login/signup link if one of those is actually not available
  614. $useCombinedLoginLink = false;
  615. }
  616. $loginlink = $permissionManager->userHasRight( $this->getUser(), 'createaccount' )
  617. && $useCombinedLoginLink ? 'nav-login-createaccount' : 'pt-login';
  618. $login_url = [
  619. 'text' => $this->msg( $loginlink )->text(),
  620. 'href' => self::makeSpecialUrl( 'Userlogin', $returnto ),
  621. 'active' => $title->isSpecial( 'Userlogin' )
  622. || $title->isSpecial( 'CreateAccount' ) && $useCombinedLoginLink,
  623. ];
  624. $createaccount_url = [
  625. 'text' => $this->msg( 'pt-createaccount' )->text(),
  626. 'href' => self::makeSpecialUrl( 'CreateAccount', $returnto ),
  627. 'active' => $title->isSpecial( 'CreateAccount' ),
  628. ];
  629. // No need to show Talk and Contributions to anons if they can't contribute!
  630. if ( $permissionManager->groupHasPermission( '*', 'edit' ) ) {
  631. // Because of caching, we can't link directly to the IP talk and
  632. // contributions pages. Instead we use the special page shortcuts
  633. // (which work correctly regardless of caching). This means we can't
  634. // determine whether these links are active or not, but since major
  635. // skins (MonoBook, Vector) don't use this information, it's not a
  636. // huge loss.
  637. $personal_urls['anontalk'] = [
  638. 'text' => $this->msg( 'anontalk' )->text(),
  639. 'href' => self::makeSpecialUrlSubpage( 'Mytalk', false ),
  640. 'active' => false
  641. ];
  642. $personal_urls['anoncontribs'] = [
  643. 'text' => $this->msg( 'anoncontribs' )->text(),
  644. 'href' => self::makeSpecialUrlSubpage( 'Mycontributions', false ),
  645. 'active' => false
  646. ];
  647. }
  648. if (
  649. $authManager->canCreateAccounts()
  650. && $permissionManager->userHasRight( $this->getUser(), 'createaccount' )
  651. && !$useCombinedLoginLink
  652. ) {
  653. $personal_urls['createaccount'] = $createaccount_url;
  654. }
  655. if ( $authManager->canAuthenticateNow() ) {
  656. $key = $permissionManager->groupHasPermission( '*', 'read' )
  657. ? 'login'
  658. : 'login-private';
  659. $personal_urls[$key] = $login_url;
  660. }
  661. }
  662. Hooks::runWithoutAbort( 'PersonalUrls', [ &$personal_urls, &$title, $this ] );
  663. return $personal_urls;
  664. }
  665. /**
  666. * Builds an array with tab definition
  667. *
  668. * @param Title $title Page Where the tab links to
  669. * @param string|array $message Message key or an array of message keys (will fall back)
  670. * @param bool $selected Display the tab as selected
  671. * @param string $query Query string attached to tab URL
  672. * @param bool $checkEdit Check if $title exists and mark with .new if one doesn't
  673. *
  674. * @return array
  675. */
  676. function tabAction( $title, $message, $selected, $query = '', $checkEdit = false ) {
  677. $classes = [];
  678. if ( $selected ) {
  679. $classes[] = 'selected';
  680. }
  681. $exists = true;
  682. if ( $checkEdit && !$title->isKnown() ) {
  683. $classes[] = 'new';
  684. $exists = false;
  685. if ( $query !== '' ) {
  686. $query = 'action=edit&redlink=1&' . $query;
  687. } else {
  688. $query = 'action=edit&redlink=1';
  689. }
  690. }
  691. $services = MediaWikiServices::getInstance();
  692. $linkClass = $services->getLinkRenderer()->getLinkClasses( $title );
  693. // wfMessageFallback will nicely accept $message as an array of fallbacks
  694. // or just a single key
  695. $msg = wfMessageFallback( $message )->setContext( $this->getContext() );
  696. if ( is_array( $message ) ) {
  697. // for hook compatibility just keep the last message name
  698. $message = end( $message );
  699. }
  700. if ( $msg->exists() ) {
  701. $text = $msg->text();
  702. } else {
  703. $text = $services->getContentLanguage()->getConverter()->
  704. convertNamespace( $services->getNamespaceInfo()->
  705. getSubject( $title->getNamespace() ) );
  706. }
  707. // Avoid PHP 7.1 warning of passing $this by reference
  708. $skinTemplate = $this;
  709. $result = [];
  710. if ( !Hooks::run( 'SkinTemplateTabAction', [ &$skinTemplate,
  711. $title, $message, $selected, $checkEdit,
  712. &$classes, &$query, &$text, &$result ] ) ) {
  713. return $result;
  714. }
  715. $result = [
  716. 'class' => implode( ' ', $classes ),
  717. 'text' => $text,
  718. 'href' => $title->getLocalURL( $query ),
  719. 'exists' => $exists,
  720. 'primary' => true ];
  721. if ( $linkClass !== '' ) {
  722. $result['link-class'] = $linkClass;
  723. }
  724. return $result;
  725. }
  726. function makeTalkUrlDetails( $name, $urlaction = '' ) {
  727. $title = Title::newFromText( $name );
  728. if ( !is_object( $title ) ) {
  729. throw new MWException( __METHOD__ . " given invalid pagename $name" );
  730. }
  731. $title = $title->getTalkPage();
  732. self::checkTitle( $title, $name );
  733. return [
  734. 'href' => $title->getLocalURL( $urlaction ),
  735. 'exists' => $title->isKnown(),
  736. ];
  737. }
  738. /**
  739. * @todo is this even used?
  740. * @param string $name
  741. * @param string $urlaction
  742. * @return array
  743. */
  744. function makeArticleUrlDetails( $name, $urlaction = '' ) {
  745. $title = Title::newFromText( $name );
  746. $title = $title->getSubjectPage();
  747. self::checkTitle( $title, $name );
  748. return [
  749. 'href' => $title->getLocalURL( $urlaction ),
  750. 'exists' => $title->exists(),
  751. ];
  752. }
  753. /**
  754. * a structured array of links usually used for the tabs in a skin
  755. *
  756. * There are 4 standard sections
  757. * namespaces: Used for namespace tabs like special, page, and talk namespaces
  758. * views: Used for primary page views like read, edit, history
  759. * actions: Used for most extra page actions like deletion, protection, etc...
  760. * variants: Used to list the language variants for the page
  761. *
  762. * Each section's value is a key/value array of links for that section.
  763. * The links themselves have these common keys:
  764. * - class: The css classes to apply to the tab
  765. * - text: The text to display on the tab
  766. * - href: The href for the tab to point to
  767. * - rel: An optional rel= for the tab's link
  768. * - redundant: If true the tab will be dropped in skins using content_actions
  769. * this is useful for tabs like "Read" which only have meaning in skins that
  770. * take special meaning from the grouped structure of content_navigation
  771. *
  772. * Views also have an extra key which can be used:
  773. * - primary: If this is not true skins like vector may try to hide the tab
  774. * when the user has limited space in their browser window
  775. *
  776. * content_navigation using code also expects these ids to be present on the
  777. * links, however these are usually automatically generated by SkinTemplate
  778. * itself and are not necessary when using a hook. The only things these may
  779. * matter to are people modifying content_navigation after it's initial creation:
  780. * - id: A "preferred" id, most skins are best off outputting this preferred
  781. * id for best compatibility.
  782. * - tooltiponly: This is set to true for some tabs in cases where the system
  783. * believes that the accesskey should not be added to the tab.
  784. *
  785. * @return array
  786. */
  787. protected function buildContentNavigationUrls() {
  788. global $wgDisableLangConversion;
  789. // Display tabs for the relevant title rather than always the title itself
  790. $title = $this->getRelevantTitle();
  791. $onPage = $title->equals( $this->getTitle() );
  792. $out = $this->getOutput();
  793. $request = $this->getRequest();
  794. $user = $this->getUser();
  795. $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
  796. $content_navigation = [
  797. 'namespaces' => [],
  798. 'views' => [],
  799. 'actions' => [],
  800. 'variants' => []
  801. ];
  802. // parameters
  803. $action = $request->getVal( 'action', 'view' );
  804. $userCanRead = $permissionManager->quickUserCan( 'read', $user, $title );
  805. // Avoid PHP 7.1 warning of passing $this by reference
  806. $skinTemplate = $this;
  807. $preventActiveTabs = false;
  808. Hooks::run( 'SkinTemplatePreventOtherActiveTabs', [ &$skinTemplate, &$preventActiveTabs ] );
  809. // Checks if page is some kind of content
  810. if ( $title->canExist() ) {
  811. // Gets page objects for the related namespaces
  812. $subjectPage = $title->getSubjectPage();
  813. $talkPage = $title->getTalkPage();
  814. // Determines if this is a talk page
  815. $isTalk = $title->isTalkPage();
  816. // Generates XML IDs from namespace names
  817. $subjectId = $title->getNamespaceKey( '' );
  818. if ( $subjectId == 'main' ) {
  819. $talkId = 'talk';
  820. } else {
  821. $talkId = "{$subjectId}_talk";
  822. }
  823. $skname = $this->skinname;
  824. // Adds namespace links
  825. $subjectMsg = [ "nstab-$subjectId" ];
  826. if ( $subjectPage->isMainPage() ) {
  827. array_unshift( $subjectMsg, 'mainpage-nstab' );
  828. }
  829. $content_navigation['namespaces'][$subjectId] = $this->tabAction(
  830. $subjectPage, $subjectMsg, !$isTalk && !$preventActiveTabs, '', $userCanRead
  831. );
  832. $content_navigation['namespaces'][$subjectId]['context'] = 'subject';
  833. $content_navigation['namespaces'][$talkId] = $this->tabAction(
  834. $talkPage, [ "nstab-$talkId", 'talk' ], $isTalk && !$preventActiveTabs, '', $userCanRead
  835. );
  836. $content_navigation['namespaces'][$talkId]['context'] = 'talk';
  837. if ( $userCanRead ) {
  838. // Adds "view" view link
  839. if ( $title->isKnown() ) {
  840. $content_navigation['views']['view'] = $this->tabAction(
  841. $isTalk ? $talkPage : $subjectPage,
  842. [ "$skname-view-view", 'view' ],
  843. ( $onPage && ( $action == 'view' || $action == 'purge' ) ), '', true
  844. );
  845. // signal to hide this from simple content_actions
  846. $content_navigation['views']['view']['redundant'] = true;
  847. }
  848. $page = $this->canUseWikiPage() ? $this->getWikiPage() : false;
  849. $isRemoteContent = $page && !$page->isLocal();
  850. // If it is a non-local file, show a link to the file in its own repository
  851. // @todo abstract this for remote content that isn't a file
  852. if ( $isRemoteContent ) {
  853. $content_navigation['views']['view-foreign'] = [
  854. 'class' => '',
  855. 'text' => wfMessageFallback( "$skname-view-foreign", 'view-foreign' )->
  856. setContext( $this->getContext() )->
  857. params( $page->getWikiDisplayName() )->text(),
  858. 'href' => $page->getSourceURL(),
  859. 'primary' => false,
  860. ];
  861. }
  862. // Checks if user can edit the current page if it exists or create it otherwise
  863. if ( $permissionManager->quickUserCan( 'edit', $user, $title ) &&
  864. ( $title->exists() ||
  865. $permissionManager->quickUserCan( 'create', $user, $title ) )
  866. ) {
  867. // Builds CSS class for talk page links
  868. $isTalkClass = $isTalk ? ' istalk' : '';
  869. // Whether the user is editing the page
  870. $isEditing = $onPage && ( $action == 'edit' || $action == 'submit' );
  871. // Whether to show the "Add a new section" tab
  872. // Checks if this is a current rev of talk page and is not forced to be hidden
  873. $showNewSection = !$out->forceHideNewSectionLink()
  874. && ( ( $isTalk && $out->isRevisionCurrent() ) || $out->showNewSectionLink() );
  875. $section = $request->getVal( 'section' );
  876. if ( $title->exists()
  877. || ( $title->getNamespace() == NS_MEDIAWIKI
  878. && $title->getDefaultMessageText() !== false
  879. )
  880. ) {
  881. $msgKey = $isRemoteContent ? 'edit-local' : 'edit';
  882. } else {
  883. $msgKey = $isRemoteContent ? 'create-local' : 'create';
  884. }
  885. $content_navigation['views']['edit'] = [
  886. 'class' => ( $isEditing && ( $section !== 'new' || !$showNewSection )
  887. ? 'selected'
  888. : ''
  889. ) . $isTalkClass,
  890. 'text' => wfMessageFallback( "$skname-view-$msgKey", $msgKey )
  891. ->setContext( $this->getContext() )->text(),
  892. 'href' => $title->getLocalURL( $this->editUrlOptions() ),
  893. 'primary' => !$isRemoteContent, // don't collapse this in vector
  894. ];
  895. // section link
  896. if ( $showNewSection ) {
  897. // Adds new section link
  898. // $content_navigation['actions']['addsection']
  899. $content_navigation['views']['addsection'] = [
  900. 'class' => ( $isEditing && $section == 'new' ) ? 'selected' : false,
  901. 'text' => wfMessageFallback( "$skname-action-addsection", 'addsection' )
  902. ->setContext( $this->getContext() )->text(),
  903. 'href' => $title->getLocalURL( 'action=edit&section=new' )
  904. ];
  905. }
  906. // Checks if the page has some kind of viewable source content
  907. } elseif ( $title->hasSourceText() ) {
  908. // Adds view source view link
  909. $content_navigation['views']['viewsource'] = [
  910. 'class' => ( $onPage && $action == 'edit' ) ? 'selected' : false,
  911. 'text' => wfMessageFallback( "$skname-action-viewsource", 'viewsource' )
  912. ->setContext( $this->getContext() )->text(),
  913. 'href' => $title->getLocalURL( $this->editUrlOptions() ),
  914. 'primary' => true, // don't collapse this in vector
  915. ];
  916. }
  917. // Checks if the page exists
  918. if ( $title->exists() ) {
  919. // Adds history view link
  920. $content_navigation['views']['history'] = [
  921. 'class' => ( $onPage && $action == 'history' ) ? 'selected' : false,
  922. 'text' => wfMessageFallback( "$skname-view-history", 'history_short' )
  923. ->setContext( $this->getContext() )->text(),
  924. 'href' => $title->getLocalURL( 'action=history' ),
  925. ];
  926. if ( $permissionManager->quickUserCan( 'delete', $user, $title ) ) {
  927. $content_navigation['actions']['delete'] = [
  928. 'class' => ( $onPage && $action == 'delete' ) ? 'selected' : false,
  929. 'text' => wfMessageFallback( "$skname-action-delete", 'delete' )
  930. ->setContext( $this->getContext() )->text(),
  931. 'href' => $title->getLocalURL( 'action=delete' )
  932. ];
  933. }
  934. if ( $permissionManager->quickUserCan( 'move', $user, $title ) ) {
  935. $moveTitle = SpecialPage::getTitleFor( 'Movepage', $title->getPrefixedDBkey() );
  936. $content_navigation['actions']['move'] = [
  937. 'class' => $this->getTitle()->isSpecial( 'Movepage' ) ? 'selected' : false,
  938. 'text' => wfMessageFallback( "$skname-action-move", 'move' )
  939. ->setContext( $this->getContext() )->text(),
  940. 'href' => $moveTitle->getLocalURL()
  941. ];
  942. }
  943. } else {
  944. // article doesn't exist or is deleted
  945. if ( $permissionManager->quickUserCan( 'deletedhistory', $user, $title ) ) {
  946. $n = $title->isDeleted();
  947. if ( $n ) {
  948. $undelTitle = SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedDBkey() );
  949. // If the user can't undelete but can view deleted
  950. // history show them a "View .. deleted" tab instead.
  951. $msgKey = $permissionManager->quickUserCan( 'undelete',
  952. $user, $title ) ? 'undelete' : 'viewdeleted';
  953. $content_navigation['actions']['undelete'] = [
  954. 'class' => $this->getTitle()->isSpecial( 'Undelete' ) ? 'selected' : false,
  955. 'text' => wfMessageFallback( "$skname-action-$msgKey", "{$msgKey}_short" )
  956. ->setContext( $this->getContext() )->numParams( $n )->text(),
  957. 'href' => $undelTitle->getLocalURL()
  958. ];
  959. }
  960. }
  961. }
  962. if ( $permissionManager->quickUserCan( 'protect', $user, $title ) &&
  963. $title->getRestrictionTypes() &&
  964. $permissionManager->getNamespaceRestrictionLevels( $title->getNamespace(), $user ) !== [ '' ]
  965. ) {
  966. $mode = $title->isProtected() ? 'unprotect' : 'protect';
  967. $content_navigation['actions'][$mode] = [
  968. 'class' => ( $onPage && $action == $mode ) ? 'selected' : false,
  969. 'text' => wfMessageFallback( "$skname-action-$mode", $mode )
  970. ->setContext( $this->getContext() )->text(),
  971. 'href' => $title->getLocalURL( "action=$mode" )
  972. ];
  973. }
  974. // Checks if the user is logged in
  975. if ( $this->loggedin && $permissionManager->userHasAllRights( $user,
  976. 'viewmywatchlist', 'editmywatchlist' )
  977. ) {
  978. /**
  979. * The following actions use messages which, if made particular to
  980. * the any specific skins, would break the Ajax code which makes this
  981. * action happen entirely inline. OutputPage::getJSVars
  982. * defines a set of messages in a javascript object - and these
  983. * messages are assumed to be global for all skins. Without making
  984. * a change to that procedure these messages will have to remain as
  985. * the global versions.
  986. */
  987. $mode = $user->isWatched( $title ) ? 'unwatch' : 'watch';
  988. $content_navigation['actions'][$mode] = [
  989. 'class' => 'mw-watchlink ' . (
  990. $onPage && ( $action == 'watch' || $action == 'unwatch' ) ? 'selected' : ''
  991. ),
  992. // uses 'watch' or 'unwatch' message
  993. 'text' => $this->msg( $mode )->text(),
  994. 'href' => $title->getLocalURL( [ 'action' => $mode ] ),
  995. // Set a data-mw=interface attribute, which the mediawiki.page.ajax
  996. // module will look for to make sure it's a trusted link
  997. 'data' => [
  998. 'mw' => 'interface',
  999. ],
  1000. ];
  1001. }
  1002. }
  1003. // Avoid PHP 7.1 warning of passing $this by reference
  1004. $skinTemplate = $this;
  1005. Hooks::runWithoutAbort(
  1006. 'SkinTemplateNavigation',
  1007. [ &$skinTemplate, &$content_navigation ]
  1008. );
  1009. if ( $userCanRead && !$wgDisableLangConversion ) {
  1010. $pageLang = $title->getPageLanguage();
  1011. // Checks that language conversion is enabled and variants exist
  1012. // And if it is not in the special namespace
  1013. if ( $pageLang->hasVariants() ) {
  1014. // Gets list of language variants
  1015. $variants = $pageLang->getVariants();
  1016. // Gets preferred variant (note that user preference is
  1017. // only possible for wiki content language variant)
  1018. $preferred = $pageLang->getPreferredVariant();
  1019. if ( Action::getActionName( $this ) === 'view' ) {
  1020. $params = $request->getQueryValues();
  1021. unset( $params['title'] );
  1022. } else {
  1023. $params = [];
  1024. }
  1025. // Loops over each variant
  1026. foreach ( $variants as $code ) {
  1027. // Gets variant name from language code
  1028. $varname = $pageLang->getVariantname( $code );
  1029. // Appends variant link
  1030. $content_navigation['variants'][] = [
  1031. 'class' => ( $code == $preferred ) ? 'selected' : false,
  1032. 'text' => $varname,
  1033. 'href' => $title->getLocalURL( [ 'variant' => $code ] + $params ),
  1034. 'lang' => LanguageCode::bcp47( $code ),
  1035. 'hreflang' => LanguageCode::bcp47( $code ),
  1036. ];
  1037. }
  1038. }
  1039. }
  1040. } else {
  1041. // If it's not content, it's got to be a special page
  1042. $content_navigation['namespaces']['special'] = [
  1043. 'class' => 'selected',
  1044. 'text' => $this->msg( 'nstab-special' )->text(),
  1045. 'href' => $request->getRequestURL(), // @see: T4457, T4510
  1046. 'context' => 'subject'
  1047. ];
  1048. // Avoid PHP 7.1 warning of passing $this by reference
  1049. $skinTemplate = $this;
  1050. Hooks::runWithoutAbort( 'SkinTemplateNavigation::SpecialPage',
  1051. [ &$skinTemplate, &$content_navigation ] );
  1052. }
  1053. // Avoid PHP 7.1 warning of passing $this by reference
  1054. $skinTemplate = $this;
  1055. // Equiv to SkinTemplateContentActions
  1056. Hooks::runWithoutAbort( 'SkinTemplateNavigation::Universal',
  1057. [ &$skinTemplate, &$content_navigation ] );
  1058. // Setup xml ids and tooltip info
  1059. foreach ( $content_navigation as $section => &$links ) {
  1060. foreach ( $links as $key => &$link ) {
  1061. $xmlID = $key;
  1062. if ( isset( $link['context'] ) && $link['context'] == 'subject' ) {
  1063. $xmlID = 'ca-nstab-' . $xmlID;
  1064. } elseif ( isset( $link['context'] ) && $link['context'] == 'talk' ) {
  1065. $xmlID = 'ca-talk';
  1066. $link['rel'] = 'discussion';
  1067. } elseif ( $section == 'variants' ) {
  1068. $xmlID = 'ca-varlang-' . $xmlID;
  1069. } else {
  1070. $xmlID = 'ca-' . $xmlID;
  1071. }
  1072. $link['id'] = $xmlID;
  1073. }
  1074. }
  1075. # We don't want to give the watch tab an accesskey if the
  1076. # page is being edited, because that conflicts with the
  1077. # accesskey on the watch checkbox. We also don't want to
  1078. # give the edit tab an accesskey, because that's fairly
  1079. # superfluous and conflicts with an accesskey (Ctrl-E) often
  1080. # used for editing in Safari.
  1081. if ( in_array( $action, [ 'edit', 'submit' ] ) ) {
  1082. if ( isset( $content_navigation['views']['edit'] ) ) {
  1083. $content_navigation['views']['edit']['tooltiponly'] = true;
  1084. }
  1085. if ( isset( $content_navigation['actions']['watch'] ) ) {
  1086. $content_navigation['actions']['watch']['tooltiponly'] = true;
  1087. }
  1088. if ( isset( $content_navigation['actions']['unwatch'] ) ) {
  1089. $content_navigation['actions']['unwatch']['tooltiponly'] = true;
  1090. }
  1091. }
  1092. return $content_navigation;
  1093. }
  1094. /**
  1095. * an array of edit links by default used for the tabs
  1096. * @param array $content_navigation
  1097. * @return array
  1098. */
  1099. private function buildContentActionUrls( $content_navigation ) {
  1100. // content_actions has been replaced with content_navigation for backwards
  1101. // compatibility and also for skins that just want simple tabs content_actions
  1102. // is now built by flattening the content_navigation arrays into one
  1103. $content_actions = [];
  1104. foreach ( $content_navigation as $links ) {
  1105. foreach ( $links as $key => $value ) {
  1106. if ( isset( $value['redundant'] ) && $value['redundant'] ) {
  1107. // Redundant tabs are dropped from content_actions
  1108. continue;
  1109. }
  1110. // content_actions used to have ids built using the "ca-$key" pattern
  1111. // so the xmlID based id is much closer to the actual $key that we want
  1112. // for that reason we'll just strip out the ca- if present and use
  1113. // the latter potion of the "id" as the $key
  1114. if ( isset( $value['id'] ) && substr( $value['id'], 0, 3 ) == 'ca-' ) {
  1115. $key = substr( $value['id'], 3 );
  1116. }
  1117. if ( isset( $content_actions[$key] ) ) {
  1118. wfDebug( __METHOD__ . ": Found a duplicate key for $key while flattening " .
  1119. "content_navigation into content_actions.\n" );
  1120. continue;
  1121. }
  1122. $content_actions[$key] = $value;
  1123. }
  1124. }
  1125. return $content_actions;
  1126. }
  1127. /**
  1128. * build array of common navigation links
  1129. * @return array
  1130. */
  1131. protected function buildNavUrls() {
  1132. global $wgUploadNavigationUrl;
  1133. $out = $this->getOutput();
  1134. $request = $this->getRequest();
  1135. $nav_urls = [];
  1136. $nav_urls['mainpage'] = [ 'href' => self::makeMainPageUrl() ];
  1137. if ( $wgUploadNavigationUrl ) {
  1138. $nav_urls['upload'] = [ 'href' => $wgUploadNavigationUrl ];
  1139. } elseif ( UploadBase::isEnabled() && UploadBase::isAllowed( $this->getUser() ) === true ) {
  1140. $nav_urls['upload'] = [ 'href' => self::makeSpecialUrl( 'Upload' ) ];
  1141. } else {
  1142. $nav_urls['upload'] = false;
  1143. }
  1144. $nav_urls['specialpages'] = [ 'href' => self::makeSpecialUrl( 'Specialpages' ) ];
  1145. $nav_urls['print'] = false;
  1146. $nav_urls['permalink'] = false;
  1147. $nav_urls['info'] = false;
  1148. $nav_urls['whatlinkshere'] = false;
  1149. $nav_urls['recentchangeslinked'] = false;
  1150. $nav_urls['contributions'] = false;
  1151. $nav_urls['log'] = false;
  1152. $nav_urls['blockip'] = false;
  1153. $nav_urls['mute'] = false;
  1154. $nav_urls['emailuser'] = false;
  1155. $nav_urls['userrights'] = false;
  1156. // A print stylesheet is attached to all pages, but nobody ever
  1157. // figures that out. :) Add a link...
  1158. if ( !$out->isPrintable() && ( $out->isArticle() || $this->getTitle()->isSpecialPage() ) ) {
  1159. $nav_urls['print'] = [
  1160. 'text' => $this->msg( 'printableversion' )->text(),
  1161. 'href' => $this->getTitle()->getLocalURL(
  1162. $request->appendQueryValue( 'printable', 'yes' ) )
  1163. ];
  1164. }
  1165. if ( $out->isArticle() ) {
  1166. // Also add a "permalink" while we're at it
  1167. $revid = $this->getOutput()->getRevisionId();
  1168. if ( $revid ) {
  1169. $nav_urls['permalink'] = [
  1170. 'text' => $this->msg( 'permalink' )->text(),
  1171. 'href' => $this->getTitle()->getLocalURL( "oldid=$revid" )
  1172. ];
  1173. }
  1174. // Avoid PHP 7.1 warning of passing $this by reference
  1175. $skinTemplate = $this;
  1176. // Use the copy of revision ID in case this undocumented, shady hook tries to mess with internals
  1177. Hooks::run( 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink',
  1178. [ &$skinTemplate, &$nav_urls, &$revid, &$revid ] );
  1179. }
  1180. if ( $out->isArticleRelated() ) {
  1181. $nav_urls['whatlinkshere'] = [
  1182. 'href' => SpecialPage::getTitleFor( 'Whatlinkshere', $this->thispage )->getLocalURL()
  1183. ];
  1184. $nav_urls['info'] = [
  1185. 'text' => $this->msg( 'pageinfo-toolboxlink' )->text(),
  1186. 'href' => $this->getTitle()->getLocalURL( "action=info" )
  1187. ];
  1188. if ( $this->getTitle()->exists() || $this->getTitle()->inNamespace( NS_CATEGORY ) ) {
  1189. $nav_urls['recentchangeslinked'] = [
  1190. 'href' => SpecialPage::getTitleFor( 'Recentchangeslinked', $this->thispage )->getLocalURL()
  1191. ];
  1192. }
  1193. }
  1194. $user = $this->getRelevantUser();
  1195. if ( $user ) {
  1196. $rootUser = $user->getName();
  1197. $nav_urls['contributions'] = [
  1198. 'text' => $this->msg( 'contributions', $rootUser )->text(),
  1199. 'href' => self::makeSpecialUrlSubpage( 'Contributions', $rootUser ),
  1200. 'tooltip-params' => [ $rootUser ],
  1201. ];
  1202. $nav_urls['log'] = [
  1203. 'href' => self::makeSpecialUrlSubpage( 'Log', $rootUser )
  1204. ];
  1205. if ( MediawikiServices::getInstance()
  1206. ->getPermissionManager()
  1207. ->userHasRight( $this->getUser(), 'block' )
  1208. ) {
  1209. $nav_urls['blockip'] = [
  1210. 'text' => $this->msg( 'blockip', $rootUser )->text(),
  1211. 'href' => self::makeSpecialUrlSubpage( 'Block', $rootUser )
  1212. ];
  1213. }
  1214. if ( $this->showEmailUser( $user ) ) {
  1215. $nav_urls['emailuser'] = [
  1216. 'text' => $this->msg( 'tool-link-emailuser', $rootUser )->text(),
  1217. 'href' => self::makeSpecialUrlSubpage( 'Emailuser', $rootUser ),
  1218. 'tooltip-params' => [ $rootUser ],
  1219. ];
  1220. }
  1221. if ( !$user->isAnon() ) {
  1222. if ( $this->getUser()->isRegistered() && $this->getConfig()->get( 'EnableSpecialMute' ) ) {
  1223. $nav_urls['mute'] = [
  1224. 'text' => $this->msg( 'mute-preferences' )->text(),
  1225. 'href' => self::makeSpecialUrlSubpage( 'Mute', $rootUser )
  1226. ];
  1227. }
  1228. $sur = new UserrightsPage;
  1229. $sur->setContext( $this->getContext() );
  1230. $canChange = $sur->userCanChangeRights( $user );
  1231. $nav_urls['userrights'] = [
  1232. 'text' => $this->msg(
  1233. $canChange ? 'tool-link-userrights' : 'tool-link-userrights-readonly',
  1234. $rootUser
  1235. )->text(),
  1236. 'href' => self::makeSpecialUrlSubpage( 'Userrights', $rootUser )
  1237. ];
  1238. }
  1239. }
  1240. return $nav_urls;
  1241. }
  1242. /**
  1243. * Generate strings used for xml 'id' names
  1244. * @return string
  1245. */
  1246. protected function getNameSpaceKey() {
  1247. return $this->getTitle()->getNamespaceKey();
  1248. }
  1249. }