Skin.php 46 KB

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