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