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 Wikimedia\Rdbms\IDatabase
;
27 * Implements Special:Whatlinkshere
29 * @ingroup SpecialPage
31 class SpecialWhatLinksHere
extends IncludableSpecialPage
{
32 /** @var FormOptions */
40 protected $limits = [ 20, 50, 100, 250, 500 ];
42 public function __construct() {
43 parent
::__construct( 'Whatlinkshere' );
46 function execute( $par ) {
47 $out = $this->getOutput();
50 $this->outputHeader();
51 $this->addHelpLink( 'Help:What links here' );
53 $opts = new FormOptions();
55 $opts->add( 'target', '' );
56 $opts->add( 'namespace', '', FormOptions
::INTNULL
);
57 $opts->add( 'limit', $this->getConfig()->get( 'QueryPageDefaultLimit' ) );
58 $opts->add( 'from', 0 );
59 $opts->add( 'back', 0 );
60 $opts->add( 'hideredirs', false );
61 $opts->add( 'hidetrans', false );
62 $opts->add( 'hidelinks', false );
63 $opts->add( 'hideimages', false );
64 $opts->add( 'invert', false );
66 $opts->fetchValuesFromRequest( $this->getRequest() );
67 $opts->validateIntBounds( 'limit', 0, 5000 );
69 // Give precedence to subpage syntax
70 if ( $par !== null ) {
71 $opts->setValue( 'target', $par );
74 // Bind to member variable
77 $this->target
= Title
::newFromText( $opts->getValue( 'target' ) );
78 if ( !$this->target
) {
79 if ( !$this->including() ) {
80 $out->addHTML( $this->whatlinkshereForm() );
86 $this->getSkin()->setRelevantTitle( $this->target
);
88 $this->selfTitle
= $this->getPageTitle( $this->target
->getPrefixedDBkey() );
90 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target
->getPrefixedText() ) );
91 $out->addBacklinkSubtitle( $this->target
);
92 $this->showIndirectLinks(
95 $opts->getValue( 'limit' ),
96 $opts->getValue( 'from' ),
97 $opts->getValue( 'back' )
102 * @param int $level Recursion level
103 * @param Title $target Target title
104 * @param int $limit Number of entries to display
105 * @param int $from Display from this article ID (default: 0)
106 * @param int $back Display from this article ID at backwards scrolling (default: 0)
108 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
109 $out = $this->getOutput();
110 $dbr = wfGetDB( DB_REPLICA
);
112 $hidelinks = $this->opts
->getValue( 'hidelinks' );
113 $hideredirs = $this->opts
->getValue( 'hideredirs' );
114 $hidetrans = $this->opts
->getValue( 'hidetrans' );
115 $hideimages = $target->getNamespace() != NS_FILE ||
$this->opts
->getValue( 'hideimages' );
117 $fetchlinks = ( !$hidelinks ||
!$hideredirs );
119 // Build query conds in concert for all three tables...
120 $conds['pagelinks'] = [
121 'pl_namespace' => $target->getNamespace(),
122 'pl_title' => $target->getDBkey(),
124 $conds['templatelinks'] = [
125 'tl_namespace' => $target->getNamespace(),
126 'tl_title' => $target->getDBkey(),
128 $conds['imagelinks'] = [
129 'il_to' => $target->getDBkey(),
132 $namespace = $this->opts
->getValue( 'namespace' );
133 $invert = $this->opts
->getValue( 'invert' );
134 $nsComparison = ( $invert ?
'!= ' : '= ' ) . $dbr->addQuotes( $namespace );
135 if ( is_int( $namespace ) ) {
136 $conds['pagelinks'][] = "pl_from_namespace $nsComparison";
137 $conds['templatelinks'][] = "tl_from_namespace $nsComparison";
138 $conds['imagelinks'][] = "il_from_namespace $nsComparison";
142 $conds['templatelinks'][] = "tl_from >= $from";
143 $conds['pagelinks'][] = "pl_from >= $from";
144 $conds['imagelinks'][] = "il_from >= $from";
148 $conds['pagelinks']['rd_from'] = null;
149 } elseif ( $hidelinks ) {
150 $conds['pagelinks'][] = 'rd_from is NOT NULL';
153 $queryFunc = function ( IDatabase
$dbr, $table, $fromCol ) use (
154 $conds, $target, $limit
156 // Read an extra row as an at-end check
157 $queryLimit = $limit +
1;
159 "rd_from = $fromCol",
160 'rd_title' => $target->getDBkey(),
161 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
163 $on['rd_namespace'] = $target->getNamespace();
164 // Inner LIMIT is 2X in case of stale backlinks with wrong namespaces
165 $subQuery = $dbr->buildSelectSubquery(
166 [ $table, 'redirect', 'page' ],
167 [ $fromCol, 'rd_from' ],
169 __CLASS__
. '::showIndirectLinks',
170 // Force JOIN order per T106682 to avoid large filesorts
171 [ 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit, 'STRAIGHT_JOIN' ],
173 'page' => [ 'JOIN', "$fromCol = page_id" ],
174 'redirect' => [ 'LEFT JOIN', $on ]
178 [ 'page', 'temp_backlink_range' => $subQuery ],
179 [ 'page_id', 'page_namespace', 'page_title', 'rd_from', 'page_is_redirect' ],
181 __CLASS__
. '::showIndirectLinks',
182 [ 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ],
183 [ 'page' => [ 'JOIN', "$fromCol = page_id" ] ]
188 $plRes = $queryFunc( $dbr, 'pagelinks', 'pl_from' );
192 $tlRes = $queryFunc( $dbr, 'templatelinks', 'tl_from' );
195 if ( !$hideimages ) {
196 $ilRes = $queryFunc( $dbr, 'imagelinks', 'il_from' );
199 if ( ( !$fetchlinks ||
!$plRes->numRows() )
200 && ( $hidetrans ||
!$tlRes->numRows() )
201 && ( $hideimages ||
!$ilRes->numRows() )
203 if ( $level == 0 && !$this->including() ) {
204 $out->addHTML( $this->whatlinkshereForm() );
206 // Show filters only if there are links
207 if ( $hidelinks ||
$hidetrans ||
$hideredirs ||
$hideimages ) {
208 $out->addHTML( $this->getFilterPanel() );
210 $msgKey = is_int( $namespace ) ?
'nolinkshere-ns' : 'nolinkshere';
211 $link = $this->getLinkRenderer()->makeLink(
215 $this->target
->isRedirect() ?
[ 'redirect' => 'no' ] : []
218 $errMsg = $this->msg( $msgKey )
219 ->params( $this->target
->getPrefixedText() )
222 $out->addHTML( $errMsg );
223 $out->setStatusCode( 404 );
229 // Read the rows into an array and remove duplicates
230 // templatelinks comes second so that the templatelinks row overwrites the
231 // pagelinks row, so we get (inclusion) rather than nothing
233 foreach ( $plRes as $row ) {
234 $row->is_template
= 0;
236 $rows[$row->page_id
] = $row;
240 foreach ( $tlRes as $row ) {
241 $row->is_template
= 1;
243 $rows[$row->page_id
] = $row;
246 if ( !$hideimages ) {
247 foreach ( $ilRes as $row ) {
248 $row->is_template
= 0;
250 $rows[$row->page_id
] = $row;
254 // Sort by key and then change the keys to 0-based indices
256 $rows = array_values( $rows );
258 $numRows = count( $rows );
260 // Work out the start and end IDs, for prev/next links
261 if ( $numRows > $limit ) {
262 // More rows available after these ones
263 // Get the ID from the last row in the result set
264 $nextId = $rows[$limit]->page_id
;
265 // Remove undisplayed rows
266 $rows = array_slice( $rows, 0, $limit );
268 // No more rows after
273 // use LinkBatch to make sure, that all required data (associated with Titles)
274 // is loaded in one query
275 $lb = new LinkBatch();
276 foreach ( $rows as $row ) {
277 $lb->add( $row->page_namespace
, $row->page_title
);
281 if ( $level == 0 && !$this->including() ) {
282 $out->addHTML( $this->whatlinkshereForm() );
283 $out->addHTML( $this->getFilterPanel() );
285 $link = $this->getLinkRenderer()->makeLink(
289 $this->target
->isRedirect() ?
[ 'redirect' => 'no' ] : []
292 $msg = $this->msg( 'linkshere' )
293 ->params( $this->target
->getPrefixedText() )
296 $out->addHTML( $msg );
298 $prevnext = $this->getPrevNext( $prevId, $nextId );
299 $out->addHTML( $prevnext );
301 $out->addHTML( $this->listStart( $level ) );
302 foreach ( $rows as $row ) {
303 $nt = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
305 if ( $row->rd_from
&& $level < 2 ) {
306 $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
307 $this->showIndirectLinks(
310 $this->getConfig()->get( 'MaxRedirectLinksRetrieved' )
312 $out->addHTML( Xml
::closeElement( 'li' ) );
314 $out->addHTML( $this->listItem( $row, $nt, $target ) );
318 $out->addHTML( $this->listEnd() );
320 if ( $level == 0 && !$this->including() ) {
321 $out->addHTML( $prevnext );
325 protected function listStart( $level ) {
326 return Xml
::openElement( 'ul', ( $level ?
[] : [ 'id' => 'mw-whatlinkshere-list' ] ) );
329 protected function listItem( $row, $nt, $target, $notClose = false ) {
330 $dirmark = $this->getLanguage()->getDirMark();
332 # local message cache
333 static $msgcache = null;
334 if ( $msgcache === null ) {
335 static $msgs = [ 'isredirect', 'istemplate', 'semicolon-separator',
336 'whatlinkshere-links', 'isimage', 'editlink' ];
338 foreach ( $msgs as $msg ) {
339 $msgcache[$msg] = $this->msg( $msg )->escaped();
343 if ( $row->rd_from
) {
344 $query = [ 'redirect' => 'no' ];
349 $link = $this->getLinkRenderer()->makeKnownLink(
352 $row->page_is_redirect ?
[ 'class' => 'mw-redirect' ] : [],
356 // Display properties (redirect or template)
359 if ( $row->rd_from
) {
360 $props[] = $msgcache['isredirect'];
362 if ( $row->is_template
) {
363 $props[] = $msgcache['istemplate'];
365 if ( $row->is_image
) {
366 $props[] = $msgcache['isimage'];
369 Hooks
::run( 'WhatLinksHereProps', [ $row, $nt, $target, &$props ] );
371 if ( count( $props ) ) {
372 $propsText = $this->msg( 'parentheses' )
373 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
376 # Space for utilities links, with a what-links-here link provided
377 $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'], $msgcache['editlink'] );
378 $wlh = Xml
::wrapClass(
379 $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
380 'mw-whatlinkshere-tools'
384 Xml
::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
385 Xml
::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
388 protected function listEnd() {
389 return Xml
::closeElement( 'ul' );
392 protected function wlhLink( Title
$target, $text, $editText ) {
393 static $title = null;
394 if ( $title === null ) {
395 $title = $this->getPageTitle();
398 $linkRenderer = $this->getLinkRenderer();
400 if ( $text !== null ) {
401 $text = new HtmlArmor( $text );
404 // always show a "<- Links" link
406 'links' => $linkRenderer->makeKnownLink(
410 [ 'target' => $target->getPrefixedText() ]
414 // if the page is editable, add an edit link
416 // check user permissions
417 $this->getUser()->isAllowed( 'edit' ) &&
418 // check, if the content model is editable through action=edit
419 ContentHandler
::getForTitle( $target )->supportsDirectEditing()
421 if ( $editText !== null ) {
422 $editText = new HtmlArmor( $editText );
425 $links['edit'] = $linkRenderer->makeKnownLink(
429 [ 'action' => 'edit' ]
433 // build the links html
434 return $this->getLanguage()->pipeList( $links );
437 function makeSelfLink( $text, $query ) {
438 if ( $text !== null ) {
439 $text = new HtmlArmor( $text );
442 return $this->getLinkRenderer()->makeKnownLink(
450 function getPrevNext( $prevId, $nextId ) {
451 $currentLimit = $this->opts
->getValue( 'limit' );
452 $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
453 $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
455 $changed = $this->opts
->getChangedValues();
456 unset( $changed['target'] ); // Already in the request title
458 if ( $prevId != 0 ) {
459 $overrides = [ 'from' => $this->opts
->getValue( 'back' ) ];
460 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
462 if ( $nextId != 0 ) {
463 $overrides = [ 'from' => $nextId, 'back' => $prevId ];
464 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
468 $lang = $this->getLanguage();
469 foreach ( $this->limits
as $limit ) {
470 $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
471 $overrides = [ 'limit' => $limit ];
472 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
475 $nums = $lang->pipeList( $limitLinks );
477 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
480 function whatlinkshereForm() {
481 // We get nicer value from the title object
482 $this->opts
->consumeValue( 'target' );
483 // Reset these for new requests
484 $this->opts
->consumeValues( [ 'back', 'from' ] );
486 $target = $this->target ?
$this->target
->getPrefixedText() : '';
487 $namespace = $this->opts
->consumeValue( 'namespace' );
488 $nsinvert = $this->opts
->consumeValue( 'invert' );
491 $f = Xml
::openElement( 'form', [ 'action' => wfScript() ] );
493 # Values that should not be forgotten
494 $f .= Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
495 foreach ( $this->opts
->getUnconsumedValues() as $name => $value ) {
496 $f .= Html
::hidden( $name, $value );
499 $f .= Xml
::fieldset( $this->msg( 'whatlinkshere' )->text() );
501 # Target input (.mw-searchInput enables suggestions)
502 $f .= Xml
::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
503 'mw-whatlinkshere-target', 40, $target, [ 'class' => 'mw-searchInput' ] );
508 $f .= Html
::namespaceSelector(
510 'selected' => $namespace,
512 'label' => $this->msg( 'namespace' )->text(),
513 'in-user-lang' => true,
515 'name' => 'namespace',
517 'class' => 'namespaceselector',
523 $this->msg( 'invert' )->text(),
527 [ 'title' => $this->msg( 'tooltip-whatlinkshere-invert' )->text() ]
533 $f .= Xml
::submitButton( $this->msg( 'whatlinkshere-submit' )->text() );
536 $f .= Xml
::closeElement( 'fieldset' ) . Xml
::closeElement( 'form' ) . "\n";
542 * Create filter panel
544 * @return string HTML fieldset and filter panel with the show/hide links
546 function getFilterPanel() {
547 $show = $this->msg( 'show' )->escaped();
548 $hide = $this->msg( 'hide' )->escaped();
550 $changed = $this->opts
->getChangedValues();
551 unset( $changed['target'] ); // Already in the request title
554 $types = [ 'hidetrans', 'hidelinks', 'hideredirs' ];
555 if ( $this->target
->getNamespace() == NS_FILE
) {
556 $types[] = 'hideimages';
559 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
560 // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
561 // To be sure they will be found by grep
562 foreach ( $types as $type ) {
563 $chosen = $this->opts
->getValue( $type );
564 $msg = $chosen ?
$show : $hide;
565 $overrides = [ $type => !$chosen ];
566 $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
567 $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
570 return Xml
::fieldset(
571 $this->msg( 'whatlinkshere-filters' )->text(),
572 $this->getLanguage()->pipeList( $links )
577 * Return an array of subpages beginning with $search that this special page will accept.
579 * @param string $search Prefix to search for
580 * @param int $limit Maximum number of results to return (usually 10)
581 * @param int $offset Number of results to skip (usually 0)
582 * @return string[] Matching subpages
584 public function prefixSearchSubpages( $search, $limit, $offset ) {
585 return $this->prefixSearchString( $search, $limit, $offset );
588 protected function getGroupName() {