SpecialWhatLinksHere.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. /**
  3. * Implements Special:Whatlinkshere
  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. * @todo Use some variant of Pager or something; the pagination here is lousy.
  22. */
  23. use MediaWiki\MediaWikiServices;
  24. use Wikimedia\Rdbms\IDatabase;
  25. /**
  26. * Implements Special:Whatlinkshere
  27. *
  28. * @ingroup SpecialPage
  29. */
  30. class SpecialWhatLinksHere extends IncludableSpecialPage {
  31. /** @var FormOptions */
  32. protected $opts;
  33. protected $selfTitle;
  34. /** @var Title */
  35. protected $target;
  36. protected $limits = [ 20, 50, 100, 250, 500 ];
  37. public function __construct() {
  38. parent::__construct( 'Whatlinkshere' );
  39. }
  40. function execute( $par ) {
  41. $out = $this->getOutput();
  42. $this->setHeaders();
  43. $this->outputHeader();
  44. $this->addHelpLink( 'Help:What links here' );
  45. $opts = new FormOptions();
  46. $opts->add( 'target', '' );
  47. $opts->add( 'namespace', '', FormOptions::INTNULL );
  48. $opts->add( 'limit', $this->getConfig()->get( 'QueryPageDefaultLimit' ) );
  49. $opts->add( 'from', 0 );
  50. $opts->add( 'back', 0 );
  51. $opts->add( 'hideredirs', false );
  52. $opts->add( 'hidetrans', false );
  53. $opts->add( 'hidelinks', false );
  54. $opts->add( 'hideimages', false );
  55. $opts->add( 'invert', false );
  56. $opts->fetchValuesFromRequest( $this->getRequest() );
  57. $opts->validateIntBounds( 'limit', 0, 5000 );
  58. // Give precedence to subpage syntax
  59. if ( $par !== null ) {
  60. $opts->setValue( 'target', $par );
  61. }
  62. // Bind to member variable
  63. $this->opts = $opts;
  64. $this->target = Title::newFromText( $opts->getValue( 'target' ) );
  65. if ( !$this->target ) {
  66. if ( !$this->including() ) {
  67. $out->addHTML( $this->whatlinkshereForm() );
  68. }
  69. return;
  70. }
  71. $this->getSkin()->setRelevantTitle( $this->target );
  72. $this->selfTitle = $this->getPageTitle( $this->target->getPrefixedDBkey() );
  73. $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
  74. $out->addBacklinkSubtitle( $this->target );
  75. $this->showIndirectLinks(
  76. 0,
  77. $this->target,
  78. $opts->getValue( 'limit' ),
  79. $opts->getValue( 'from' ),
  80. $opts->getValue( 'back' )
  81. );
  82. }
  83. /**
  84. * @param int $level Recursion level
  85. * @param Title $target Target title
  86. * @param int $limit Number of entries to display
  87. * @param int $from Display from this article ID (default: 0)
  88. * @param int $back Display from this article ID at backwards scrolling (default: 0)
  89. */
  90. function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
  91. $out = $this->getOutput();
  92. $dbr = wfGetDB( DB_REPLICA );
  93. $hidelinks = $this->opts->getValue( 'hidelinks' );
  94. $hideredirs = $this->opts->getValue( 'hideredirs' );
  95. $hidetrans = $this->opts->getValue( 'hidetrans' );
  96. $hideimages = $target->getNamespace() != NS_FILE || $this->opts->getValue( 'hideimages' );
  97. $fetchlinks = ( !$hidelinks || !$hideredirs );
  98. // Build query conds in concert for all three tables...
  99. $conds = [];
  100. $conds['pagelinks'] = [
  101. 'pl_namespace' => $target->getNamespace(),
  102. 'pl_title' => $target->getDBkey(),
  103. ];
  104. $conds['templatelinks'] = [
  105. 'tl_namespace' => $target->getNamespace(),
  106. 'tl_title' => $target->getDBkey(),
  107. ];
  108. $conds['imagelinks'] = [
  109. 'il_to' => $target->getDBkey(),
  110. ];
  111. $namespace = $this->opts->getValue( 'namespace' );
  112. $invert = $this->opts->getValue( 'invert' );
  113. $nsComparison = ( $invert ? '!= ' : '= ' ) . $dbr->addQuotes( $namespace );
  114. if ( is_int( $namespace ) ) {
  115. $conds['pagelinks'][] = "pl_from_namespace $nsComparison";
  116. $conds['templatelinks'][] = "tl_from_namespace $nsComparison";
  117. $conds['imagelinks'][] = "il_from_namespace $nsComparison";
  118. }
  119. if ( $from ) {
  120. $conds['templatelinks'][] = "tl_from >= $from";
  121. $conds['pagelinks'][] = "pl_from >= $from";
  122. $conds['imagelinks'][] = "il_from >= $from";
  123. }
  124. if ( $hideredirs ) {
  125. $conds['pagelinks']['rd_from'] = null;
  126. } elseif ( $hidelinks ) {
  127. $conds['pagelinks'][] = 'rd_from is NOT NULL';
  128. }
  129. $queryFunc = function ( IDatabase $dbr, $table, $fromCol ) use (
  130. $conds, $target, $limit
  131. ) {
  132. // Read an extra row as an at-end check
  133. $queryLimit = $limit + 1;
  134. $on = [
  135. "rd_from = $fromCol",
  136. 'rd_title' => $target->getDBkey(),
  137. 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
  138. ];
  139. $on['rd_namespace'] = $target->getNamespace();
  140. // Inner LIMIT is 2X in case of stale backlinks with wrong namespaces
  141. $subQuery = $dbr->buildSelectSubquery(
  142. [ $table, 'redirect', 'page' ],
  143. [ $fromCol, 'rd_from' ],
  144. $conds[$table],
  145. __CLASS__ . '::showIndirectLinks',
  146. // Force JOIN order per T106682 to avoid large filesorts
  147. [ 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit, 'STRAIGHT_JOIN' ],
  148. [
  149. 'page' => [ 'JOIN', "$fromCol = page_id" ],
  150. 'redirect' => [ 'LEFT JOIN', $on ]
  151. ]
  152. );
  153. return $dbr->select(
  154. [ 'page', 'temp_backlink_range' => $subQuery ],
  155. [ 'page_id', 'page_namespace', 'page_title', 'rd_from', 'page_is_redirect' ],
  156. [],
  157. __CLASS__ . '::showIndirectLinks',
  158. [ 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ],
  159. [ 'page' => [ 'JOIN', "$fromCol = page_id" ] ]
  160. );
  161. };
  162. if ( $fetchlinks ) {
  163. $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
  164. }
  165. if ( !$hidetrans ) {
  166. $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
  167. }
  168. if ( !$hideimages ) {
  169. $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
  170. }
  171. if ( ( !$fetchlinks || !$plRes->numRows() )
  172. && ( $hidetrans || !$tlRes->numRows() )
  173. && ( $hideimages || !$ilRes->numRows() )
  174. ) {
  175. if ( $level == 0 && !$this->including() ) {
  176. $out->addHTML( $this->whatlinkshereForm() );
  177. // Show filters only if there are links
  178. if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
  179. $out->addHTML( $this->getFilterPanel() );
  180. }
  181. $msgKey = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
  182. $link = $this->getLinkRenderer()->makeLink(
  183. $this->target,
  184. null,
  185. [],
  186. $this->target->isRedirect() ? [ 'redirect' => 'no' ] : []
  187. );
  188. $errMsg = $this->msg( $msgKey )
  189. ->params( $this->target->getPrefixedText() )
  190. ->rawParams( $link )
  191. ->parseAsBlock();
  192. $out->addHTML( $errMsg );
  193. $out->setStatusCode( 404 );
  194. }
  195. return;
  196. }
  197. // Read the rows into an array and remove duplicates
  198. // templatelinks comes second so that the templatelinks row overwrites the
  199. // pagelinks row, so we get (inclusion) rather than nothing
  200. $rows = [];
  201. if ( $fetchlinks ) {
  202. foreach ( $plRes as $row ) {
  203. $row->is_template = 0;
  204. $row->is_image = 0;
  205. $rows[$row->page_id] = $row;
  206. }
  207. }
  208. if ( !$hidetrans ) {
  209. foreach ( $tlRes as $row ) {
  210. $row->is_template = 1;
  211. $row->is_image = 0;
  212. $rows[$row->page_id] = $row;
  213. }
  214. }
  215. if ( !$hideimages ) {
  216. foreach ( $ilRes as $row ) {
  217. $row->is_template = 0;
  218. $row->is_image = 1;
  219. $rows[$row->page_id] = $row;
  220. }
  221. }
  222. // Sort by key and then change the keys to 0-based indices
  223. ksort( $rows );
  224. $rows = array_values( $rows );
  225. $numRows = count( $rows );
  226. // Work out the start and end IDs, for prev/next links
  227. if ( $numRows > $limit ) {
  228. // More rows available after these ones
  229. // Get the ID from the last row in the result set
  230. $nextId = $rows[$limit]->page_id;
  231. // Remove undisplayed rows
  232. $rows = array_slice( $rows, 0, $limit );
  233. } else {
  234. // No more rows after
  235. $nextId = false;
  236. }
  237. $prevId = $from;
  238. // use LinkBatch to make sure, that all required data (associated with Titles)
  239. // is loaded in one query
  240. $lb = new LinkBatch();
  241. foreach ( $rows as $row ) {
  242. $lb->add( $row->page_namespace, $row->page_title );
  243. }
  244. $lb->execute();
  245. if ( $level == 0 && !$this->including() ) {
  246. $out->addHTML( $this->whatlinkshereForm() );
  247. $out->addHTML( $this->getFilterPanel() );
  248. $link = $this->getLinkRenderer()->makeLink(
  249. $this->target,
  250. null,
  251. [],
  252. $this->target->isRedirect() ? [ 'redirect' => 'no' ] : []
  253. );
  254. $msg = $this->msg( 'linkshere' )
  255. ->params( $this->target->getPrefixedText() )
  256. ->rawParams( $link )
  257. ->parseAsBlock();
  258. $out->addHTML( $msg );
  259. $prevnext = $this->getPrevNext( $prevId, $nextId );
  260. $out->addHTML( $prevnext );
  261. }
  262. $out->addHTML( $this->listStart( $level ) );
  263. foreach ( $rows as $row ) {
  264. $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
  265. if ( $row->rd_from && $level < 2 ) {
  266. $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
  267. $this->showIndirectLinks(
  268. $level + 1,
  269. $nt,
  270. $this->getConfig()->get( 'MaxRedirectLinksRetrieved' )
  271. );
  272. $out->addHTML( Xml::closeElement( 'li' ) );
  273. } else {
  274. $out->addHTML( $this->listItem( $row, $nt, $target ) );
  275. }
  276. }
  277. $out->addHTML( $this->listEnd() );
  278. if ( $level == 0 && !$this->including() ) {
  279. $out->addHTML( $prevnext );
  280. }
  281. }
  282. protected function listStart( $level ) {
  283. return Xml::openElement( 'ul', ( $level ? [] : [ 'id' => 'mw-whatlinkshere-list' ] ) );
  284. }
  285. protected function listItem( $row, $nt, $target, $notClose = false ) {
  286. $dirmark = $this->getLanguage()->getDirMark();
  287. # local message cache
  288. static $msgcache = null;
  289. if ( $msgcache === null ) {
  290. static $msgs = [ 'isredirect', 'istemplate', 'semicolon-separator',
  291. 'whatlinkshere-links', 'isimage', 'editlink' ];
  292. $msgcache = [];
  293. foreach ( $msgs as $msg ) {
  294. $msgcache[$msg] = $this->msg( $msg )->escaped();
  295. }
  296. }
  297. if ( $row->rd_from ) {
  298. $query = [ 'redirect' => 'no' ];
  299. } else {
  300. $query = [];
  301. }
  302. $link = $this->getLinkRenderer()->makeKnownLink(
  303. $nt,
  304. null,
  305. $row->page_is_redirect ? [ 'class' => 'mw-redirect' ] : [],
  306. $query
  307. );
  308. // Display properties (redirect or template)
  309. $propsText = '';
  310. $props = [];
  311. if ( $row->rd_from ) {
  312. $props[] = $msgcache['isredirect'];
  313. }
  314. if ( $row->is_template ) {
  315. $props[] = $msgcache['istemplate'];
  316. }
  317. if ( $row->is_image ) {
  318. $props[] = $msgcache['isimage'];
  319. }
  320. Hooks::run( 'WhatLinksHereProps', [ $row, $nt, $target, &$props ] );
  321. if ( count( $props ) ) {
  322. $propsText = $this->msg( 'parentheses' )
  323. ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
  324. }
  325. # Space for utilities links, with a what-links-here link provided
  326. $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'], $msgcache['editlink'] );
  327. $wlh = Xml::wrapClass(
  328. $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
  329. 'mw-whatlinkshere-tools'
  330. );
  331. return $notClose ?
  332. Xml::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
  333. Xml::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
  334. }
  335. protected function listEnd() {
  336. return Xml::closeElement( 'ul' );
  337. }
  338. protected function wlhLink( Title $target, $text, $editText ) {
  339. static $title = null;
  340. if ( $title === null ) {
  341. $title = $this->getPageTitle();
  342. }
  343. $linkRenderer = $this->getLinkRenderer();
  344. if ( $text !== null ) {
  345. $text = new HtmlArmor( $text );
  346. }
  347. // always show a "<- Links" link
  348. $links = [
  349. 'links' => $linkRenderer->makeKnownLink(
  350. $title,
  351. $text,
  352. [],
  353. [ 'target' => $target->getPrefixedText() ]
  354. ),
  355. ];
  356. // if the page is editable, add an edit link
  357. if (
  358. // check user permissions
  359. MediaWikiServices::getInstance()
  360. ->getPermissionManager()
  361. ->userHasRight( $this->getUser(), 'edit' ) &&
  362. // check, if the content model is editable through action=edit
  363. ContentHandler::getForTitle( $target )->supportsDirectEditing()
  364. ) {
  365. if ( $editText !== null ) {
  366. $editText = new HtmlArmor( $editText );
  367. }
  368. $links['edit'] = $linkRenderer->makeKnownLink(
  369. $target,
  370. $editText,
  371. [],
  372. [ 'action' => 'edit' ]
  373. );
  374. }
  375. // build the links html
  376. return $this->getLanguage()->pipeList( $links );
  377. }
  378. function makeSelfLink( $text, $query ) {
  379. if ( $text !== null ) {
  380. $text = new HtmlArmor( $text );
  381. }
  382. return $this->getLinkRenderer()->makeKnownLink(
  383. $this->selfTitle,
  384. $text,
  385. [],
  386. $query
  387. );
  388. }
  389. function getPrevNext( $prevId, $nextId ) {
  390. $currentLimit = $this->opts->getValue( 'limit' );
  391. $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
  392. $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
  393. $changed = $this->opts->getChangedValues();
  394. unset( $changed['target'] ); // Already in the request title
  395. if ( $prevId != 0 ) {
  396. $overrides = [ 'from' => $this->opts->getValue( 'back' ) ];
  397. $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
  398. }
  399. if ( $nextId != 0 ) {
  400. $overrides = [ 'from' => $nextId, 'back' => $prevId ];
  401. $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
  402. }
  403. $limitLinks = [];
  404. $lang = $this->getLanguage();
  405. foreach ( $this->limits as $limit ) {
  406. $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
  407. $overrides = [ 'limit' => $limit ];
  408. $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
  409. }
  410. $nums = $lang->pipeList( $limitLinks );
  411. return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
  412. }
  413. function whatlinkshereForm() {
  414. // We get nicer value from the title object
  415. $this->opts->consumeValue( 'target' );
  416. // Reset these for new requests
  417. $this->opts->consumeValues( [ 'back', 'from' ] );
  418. $target = $this->target ? $this->target->getPrefixedText() : '';
  419. $namespace = $this->opts->consumeValue( 'namespace' );
  420. $nsinvert = $this->opts->consumeValue( 'invert' );
  421. # Build up the form
  422. $f = Xml::openElement( 'form', [ 'action' => wfScript() ] );
  423. # Values that should not be forgotten
  424. $f .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
  425. foreach ( $this->opts->getUnconsumedValues() as $name => $value ) {
  426. $f .= Html::hidden( $name, $value );
  427. }
  428. $f .= Xml::fieldset( $this->msg( 'whatlinkshere' )->text() );
  429. # Target input (.mw-searchInput enables suggestions)
  430. $f .= Xml::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
  431. 'mw-whatlinkshere-target', 40, $target, [ 'class' => 'mw-searchInput' ] );
  432. $f .= ' ';
  433. # Namespace selector
  434. $f .= Html::namespaceSelector(
  435. [
  436. 'selected' => $namespace,
  437. 'all' => '',
  438. 'label' => $this->msg( 'namespace' )->text(),
  439. 'in-user-lang' => true,
  440. ], [
  441. 'name' => 'namespace',
  442. 'id' => 'namespace',
  443. 'class' => 'namespaceselector',
  444. ]
  445. );
  446. $f .= "\u{00A0}" .
  447. Xml::checkLabel(
  448. $this->msg( 'invert' )->text(),
  449. 'invert',
  450. 'nsinvert',
  451. $nsinvert,
  452. [ 'title' => $this->msg( 'tooltip-whatlinkshere-invert' )->text() ]
  453. );
  454. $f .= ' ';
  455. # Submit
  456. $f .= Xml::submitButton( $this->msg( 'whatlinkshere-submit' )->text() );
  457. # Close
  458. $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
  459. return $f;
  460. }
  461. /**
  462. * Create filter panel
  463. *
  464. * @return string HTML fieldset and filter panel with the show/hide links
  465. */
  466. function getFilterPanel() {
  467. $show = $this->msg( 'show' )->escaped();
  468. $hide = $this->msg( 'hide' )->escaped();
  469. $changed = $this->opts->getChangedValues();
  470. unset( $changed['target'] ); // Already in the request title
  471. $links = [];
  472. $types = [ 'hidetrans', 'hidelinks', 'hideredirs' ];
  473. if ( $this->target->getNamespace() == NS_FILE ) {
  474. $types[] = 'hideimages';
  475. }
  476. // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
  477. // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
  478. // To be sure they will be found by grep
  479. foreach ( $types as $type ) {
  480. $chosen = $this->opts->getValue( $type );
  481. $msg = $chosen ? $show : $hide;
  482. $overrides = [ $type => !$chosen ];
  483. $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
  484. $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
  485. }
  486. return Xml::fieldset(
  487. $this->msg( 'whatlinkshere-filters' )->text(),
  488. $this->getLanguage()->pipeList( $links )
  489. );
  490. }
  491. /**
  492. * Return an array of subpages beginning with $search that this special page will accept.
  493. *
  494. * @param string $search Prefix to search for
  495. * @param int $limit Maximum number of results to return (usually 10)
  496. * @param int $offset Number of results to skip (usually 0)
  497. * @return string[] Matching subpages
  498. */
  499. public function prefixSearchSubpages( $search, $limit, $offset ) {
  500. return $this->prefixSearchString( $search, $limit, $offset );
  501. }
  502. protected function getGroupName() {
  503. return 'pagetools';
  504. }
  505. }