3 * Implements Special:Whatlinkshere
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.
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.
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
21 * @todo Use some variant of Pager or something; the pagination here is lousy.
24 use MediaWiki\MediaWikiServices
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * Implements Special:Whatlinkshere
30 * @ingroup SpecialPage
32 class SpecialWhatLinksHere
extends IncludableSpecialPage
{
33 /** @var FormOptions */
41 protected $limits = [ 20, 50, 100, 250, 500 ];
43 public function __construct() {
44 parent
::__construct( 'Whatlinkshere' );
47 function execute( $par ) {
48 $out = $this->getOutput();
51 $this->outputHeader();
52 $this->addHelpLink( 'Help:What links here' );
54 $opts = new FormOptions();
56 $opts->add( 'target', '' );
57 $opts->add( 'namespace', '', FormOptions
::INTNULL
);
58 $opts->add( 'limit', $this->getConfig()->get( 'QueryPageDefaultLimit' ) );
59 $opts->add( 'from', 0 );
60 $opts->add( 'back', 0 );
61 $opts->add( 'hideredirs', false );
62 $opts->add( 'hidetrans', false );
63 $opts->add( 'hidelinks', false );
64 $opts->add( 'hideimages', false );
65 $opts->add( 'invert', false );
67 $opts->fetchValuesFromRequest( $this->getRequest() );
68 $opts->validateIntBounds( 'limit', 0, 5000 );
70 // Give precedence to subpage syntax
71 if ( $par !== null ) {
72 $opts->setValue( 'target', $par );
75 // Bind to member variable
78 $this->target
= Title
::newFromText( $opts->getValue( 'target' ) );
79 if ( !$this->target
) {
80 if ( !$this->including() ) {
81 $out->addHTML( $this->whatlinkshereForm() );
87 $this->getSkin()->setRelevantTitle( $this->target
);
89 $this->selfTitle
= $this->getPageTitle( $this->target
->getPrefixedDBkey() );
91 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target
->getPrefixedText() ) );
92 $out->addBacklinkSubtitle( $this->target
);
93 $this->showIndirectLinks(
96 $opts->getValue( 'limit' ),
97 $opts->getValue( 'from' ),
98 $opts->getValue( 'back' )
103 * @param int $level Recursion level
104 * @param Title $target Target title
105 * @param int $limit Number of entries to display
106 * @param int $from Display from this article ID (default: 0)
107 * @param int $back Display from this article ID at backwards scrolling (default: 0)
109 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
110 $out = $this->getOutput();
111 $dbr = wfGetDB( DB_REPLICA
);
113 $hidelinks = $this->opts
->getValue( 'hidelinks' );
114 $hideredirs = $this->opts
->getValue( 'hideredirs' );
115 $hidetrans = $this->opts
->getValue( 'hidetrans' );
116 $hideimages = $target->getNamespace() != NS_FILE ||
$this->opts
->getValue( 'hideimages' );
118 $fetchlinks = ( !$hidelinks ||
!$hideredirs );
120 // Build query conds in concert for all three tables...
122 $conds['pagelinks'] = [
123 'pl_namespace' => $target->getNamespace(),
124 'pl_title' => $target->getDBkey(),
126 $conds['templatelinks'] = [
127 'tl_namespace' => $target->getNamespace(),
128 'tl_title' => $target->getDBkey(),
130 $conds['imagelinks'] = [
131 'il_to' => $target->getDBkey(),
134 $namespace = $this->opts
->getValue( 'namespace' );
135 $invert = $this->opts
->getValue( 'invert' );
136 $nsComparison = ( $invert ?
'!= ' : '= ' ) . $dbr->addQuotes( $namespace );
137 if ( is_int( $namespace ) ) {
138 $conds['pagelinks'][] = "pl_from_namespace $nsComparison";
139 $conds['templatelinks'][] = "tl_from_namespace $nsComparison";
140 $conds['imagelinks'][] = "il_from_namespace $nsComparison";
144 $conds['templatelinks'][] = "tl_from >= $from";
145 $conds['pagelinks'][] = "pl_from >= $from";
146 $conds['imagelinks'][] = "il_from >= $from";
150 $conds['pagelinks']['rd_from'] = null;
151 } elseif ( $hidelinks ) {
152 $conds['pagelinks'][] = 'rd_from is NOT NULL';
155 $queryFunc = function ( IDatabase
$dbr, $table, $fromCol ) use (
156 $conds, $target, $limit
158 // Read an extra row as an at-end check
159 $queryLimit = $limit +
1;
161 "rd_from = $fromCol",
162 'rd_title' => $target->getDBkey(),
163 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
165 $on['rd_namespace'] = $target->getNamespace();
166 // Inner LIMIT is 2X in case of stale backlinks with wrong namespaces
167 $subQuery = $dbr->buildSelectSubquery(
168 [ $table, 'redirect', 'page' ],
169 [ $fromCol, 'rd_from' ],
171 __CLASS__
. '::showIndirectLinks',
172 // Force JOIN order per T106682 to avoid large filesorts
173 [ 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit, 'STRAIGHT_JOIN' ],
175 'page' => [ 'JOIN', "$fromCol = page_id" ],
176 'redirect' => [ 'LEFT JOIN', $on ]
180 [ 'page', 'temp_backlink_range' => $subQuery ],
181 [ 'page_id', 'page_namespace', 'page_title', 'rd_from', 'page_is_redirect' ],
183 __CLASS__
. '::showIndirectLinks',
184 [ 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ],
185 [ 'page' => [ 'JOIN', "$fromCol = page_id" ] ]
190 $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
194 $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
197 if ( !$hideimages ) {
198 $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
201 if ( ( !$fetchlinks ||
!$plRes->numRows() )
202 && ( $hidetrans ||
!$tlRes->numRows() )
203 && ( $hideimages ||
!$ilRes->numRows() )
205 if ( $level == 0 && !$this->including() ) {
206 $out->addHTML( $this->whatlinkshereForm() );
208 // Show filters only if there are links
209 if ( $hidelinks ||
$hidetrans ||
$hideredirs ||
$hideimages ) {
210 $out->addHTML( $this->getFilterPanel() );
212 $msgKey = is_int( $namespace ) ?
'nolinkshere-ns' : 'nolinkshere';
213 $link = $this->getLinkRenderer()->makeLink(
217 $this->target
->isRedirect() ?
[ 'redirect' => 'no' ] : []
220 $errMsg = $this->msg( $msgKey )
221 ->params( $this->target
->getPrefixedText() )
224 $out->addHTML( $errMsg );
225 $out->setStatusCode( 404 );
231 // Read the rows into an array and remove duplicates
232 // templatelinks comes second so that the templatelinks row overwrites the
233 // pagelinks row, so we get (inclusion) rather than nothing
236 foreach ( $plRes as $row ) {
237 $row->is_template
= 0;
239 $rows[$row->page_id
] = $row;
243 foreach ( $tlRes as $row ) {
244 $row->is_template
= 1;
246 $rows[$row->page_id
] = $row;
249 if ( !$hideimages ) {
250 foreach ( $ilRes as $row ) {
251 $row->is_template
= 0;
253 $rows[$row->page_id
] = $row;
257 // Sort by key and then change the keys to 0-based indices
259 $rows = array_values( $rows );
261 $numRows = count( $rows );
263 // Work out the start and end IDs, for prev/next links
264 if ( $numRows > $limit ) {
265 // More rows available after these ones
266 // Get the ID from the last row in the result set
267 $nextId = $rows[$limit]->page_id
;
268 // Remove undisplayed rows
269 $rows = array_slice( $rows, 0, $limit );
271 // No more rows after
276 // use LinkBatch to make sure, that all required data (associated with Titles)
277 // is loaded in one query
278 $lb = new LinkBatch();
279 foreach ( $rows as $row ) {
280 $lb->add( $row->page_namespace
, $row->page_title
);
284 if ( $level == 0 && !$this->including() ) {
285 $out->addHTML( $this->whatlinkshereForm() );
286 $out->addHTML( $this->getFilterPanel() );
288 $link = $this->getLinkRenderer()->makeLink(
292 $this->target
->isRedirect() ?
[ 'redirect' => 'no' ] : []
295 $msg = $this->msg( 'linkshere' )
296 ->params( $this->target
->getPrefixedText() )
299 $out->addHTML( $msg );
301 $prevnext = $this->getPrevNext( $prevId, $nextId );
302 $out->addHTML( $prevnext );
304 $out->addHTML( $this->listStart( $level ) );
305 foreach ( $rows as $row ) {
306 $nt = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
308 if ( $row->rd_from
&& $level < 2 ) {
309 $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
310 $this->showIndirectLinks(
313 $this->getConfig()->get( 'MaxRedirectLinksRetrieved' )
315 $out->addHTML( Xml
::closeElement( 'li' ) );
317 $out->addHTML( $this->listItem( $row, $nt, $target ) );
321 $out->addHTML( $this->listEnd() );
323 if ( $level == 0 && !$this->including() ) {
324 $out->addHTML( $prevnext );
328 protected function listStart( $level ) {
329 return Xml
::openElement( 'ul', ( $level ?
[] : [ 'id' => 'mw-whatlinkshere-list' ] ) );
332 protected function listItem( $row, $nt, $target, $notClose = false ) {
333 $dirmark = $this->getLanguage()->getDirMark();
335 # local message cache
336 static $msgcache = null;
337 if ( $msgcache === null ) {
338 static $msgs = [ 'isredirect', 'istemplate', 'semicolon-separator',
339 'whatlinkshere-links', 'isimage', 'editlink' ];
341 foreach ( $msgs as $msg ) {
342 $msgcache[$msg] = $this->msg( $msg )->escaped();
346 if ( $row->rd_from
) {
347 $query = [ 'redirect' => 'no' ];
352 $link = $this->getLinkRenderer()->makeKnownLink(
355 $row->page_is_redirect ?
[ 'class' => 'mw-redirect' ] : [],
359 // Display properties (redirect or template)
362 if ( $row->rd_from
) {
363 $props[] = $msgcache['isredirect'];
365 if ( $row->is_template
) {
366 $props[] = $msgcache['istemplate'];
368 if ( $row->is_image
) {
369 $props[] = $msgcache['isimage'];
372 Hooks
::run( 'WhatLinksHereProps', [ $row, $nt, $target, &$props ] );
374 if ( count( $props ) ) {
375 $propsText = $this->msg( 'parentheses' )
376 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
379 # Space for utilities links, with a what-links-here link provided
380 $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'], $msgcache['editlink'] );
381 $wlh = Xml
::wrapClass(
382 $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
383 'mw-whatlinkshere-tools'
387 Xml
::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
388 Xml
::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
391 protected function listEnd() {
392 return Xml
::closeElement( 'ul' );
395 protected function wlhLink( Title
$target, $text, $editText ) {
396 static $title = null;
397 if ( $title === null ) {
398 $title = $this->getPageTitle();
401 $linkRenderer = $this->getLinkRenderer();
403 if ( $text !== null ) {
404 $text = new HtmlArmor( $text );
407 // always show a "<- Links" link
409 'links' => $linkRenderer->makeKnownLink(
413 [ 'target' => $target->getPrefixedText() ]
417 // if the page is editable, add an edit link
419 // check user permissions
420 MediaWikiServices
::getInstance()
421 ->getPermissionManager()
422 ->userHasRight( $this->getUser(), 'edit' ) &&
423 // check, if the content model is editable through action=edit
424 ContentHandler
::getForTitle( $target )->supportsDirectEditing()
426 if ( $editText !== null ) {
427 $editText = new HtmlArmor( $editText );
430 $links['edit'] = $linkRenderer->makeKnownLink(
434 [ 'action' => 'edit' ]
438 // build the links html
439 return $this->getLanguage()->pipeList( $links );
442 function makeSelfLink( $text, $query ) {
443 if ( $text !== null ) {
444 $text = new HtmlArmor( $text );
447 return $this->getLinkRenderer()->makeKnownLink(
455 function getPrevNext( $prevId, $nextId ) {
456 $currentLimit = $this->opts
->getValue( 'limit' );
457 $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
458 $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
460 $changed = $this->opts
->getChangedValues();
461 unset( $changed['target'] ); // Already in the request title
463 if ( $prevId != 0 ) {
464 $overrides = [ 'from' => $this->opts
->getValue( 'back' ) ];
465 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
467 if ( $nextId != 0 ) {
468 $overrides = [ 'from' => $nextId, 'back' => $prevId ];
469 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
473 $lang = $this->getLanguage();
474 foreach ( $this->limits
as $limit ) {
475 $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
476 $overrides = [ 'limit' => $limit ];
477 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
480 $nums = $lang->pipeList( $limitLinks );
482 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
485 function whatlinkshereForm() {
486 // We get nicer value from the title object
487 $this->opts
->consumeValue( 'target' );
488 // Reset these for new requests
489 $this->opts
->consumeValues( [ 'back', 'from' ] );
491 $target = $this->target ?
$this->target
->getPrefixedText() : '';
492 $namespace = $this->opts
->consumeValue( 'namespace' );
493 $nsinvert = $this->opts
->consumeValue( 'invert' );
496 $f = Xml
::openElement( 'form', [ 'action' => wfScript() ] );
498 # Values that should not be forgotten
499 $f .= Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
500 foreach ( $this->opts
->getUnconsumedValues() as $name => $value ) {
501 $f .= Html
::hidden( $name, $value );
504 $f .= Xml
::fieldset( $this->msg( 'whatlinkshere' )->text() );
506 # Target input (.mw-searchInput enables suggestions)
507 $f .= Xml
::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
508 'mw-whatlinkshere-target', 40, $target, [ 'class' => 'mw-searchInput' ] );
513 $f .= Html
::namespaceSelector(
515 'selected' => $namespace,
517 'label' => $this->msg( 'namespace' )->text(),
518 'in-user-lang' => true,
520 'name' => 'namespace',
522 'class' => 'namespaceselector',
528 $this->msg( 'invert' )->text(),
532 [ 'title' => $this->msg( 'tooltip-whatlinkshere-invert' )->text() ]
538 $f .= Xml
::submitButton( $this->msg( 'whatlinkshere-submit' )->text() );
541 $f .= Xml
::closeElement( 'fieldset' ) . Xml
::closeElement( 'form' ) . "\n";
547 * Create filter panel
549 * @return string HTML fieldset and filter panel with the show/hide links
551 function getFilterPanel() {
552 $show = $this->msg( 'show' )->escaped();
553 $hide = $this->msg( 'hide' )->escaped();
555 $changed = $this->opts
->getChangedValues();
556 unset( $changed['target'] ); // Already in the request title
559 $types = [ 'hidetrans', 'hidelinks', 'hideredirs' ];
560 if ( $this->target
->getNamespace() == NS_FILE
) {
561 $types[] = 'hideimages';
564 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
565 // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
566 // To be sure they will be found by grep
567 foreach ( $types as $type ) {
568 $chosen = $this->opts
->getValue( $type );
569 $msg = $chosen ?
$show : $hide;
570 $overrides = [ $type => !$chosen ];
571 $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
572 $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
575 return Xml
::fieldset(
576 $this->msg( 'whatlinkshere-filters' )->text(),
577 $this->getLanguage()->pipeList( $links )
582 * Return an array of subpages beginning with $search that this special page will accept.
584 * @param string $search Prefix to search for
585 * @param int $limit Maximum number of results to return (usually 10)
586 * @param int $offset Number of results to skip (usually 0)
587 * @return string[] Matching subpages
589 public function prefixSearchSubpages( $search, $limit, $offset ) {
590 return $this->prefixSearchString( $search, $limit, $offset );
593 protected function getGroupName() {