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