Skin.php 44 KB

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