Redo WhatLinksHere query and add a *_from_namespace field to link tables
[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 = array( 20, 50, 100, 250, 500 );
39
40 public function __construct() {
41 parent::__construct( 'Whatlinkshere' );
42 }
43
44 function execute( $par ) {
45 global $wgQueryPageDefaultLimit;
46 $out = $this->getOutput();
47
48 $this->setHeaders();
49 $this->outputHeader();
50
51 $opts = new FormOptions();
52
53 $opts->add( 'target', '' );
54 $opts->add( 'namespace', '', FormOptions::INTNULL );
55 $opts->add( 'limit', $wgQueryPageDefaultLimit );
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
63 $opts->fetchValuesFromRequest( $this->getRequest() );
64 $opts->validateIntBounds( 'limit', 0, 5000 );
65
66 // Give precedence to subpage syntax
67 if ( $par !== null ) {
68 $opts->setValue( 'target', $par );
69 }
70
71 // Bind to member variable
72 $this->opts = $opts;
73
74 $this->target = Title::newFromURL( $opts->getValue( 'target' ) );
75 if ( !$this->target ) {
76 $out->addHTML( $this->whatlinkshereForm() );
77
78 return;
79 }
80
81 $this->getSkin()->setRelevantTitle( $this->target );
82
83 $this->selfTitle = $this->getPageTitle( $this->target->getPrefixedDBkey() );
84
85 $out->setPageTitle( $this->msg( 'whatlinkshere-title', $this->target->getPrefixedText() ) );
86 $out->addBacklinkSubtitle( $this->target );
87 $this->showIndirectLinks(
88 0,
89 $this->target,
90 $opts->getValue( 'limit' ),
91 $opts->getValue( 'from' ),
92 $opts->getValue( 'back' )
93 );
94 }
95
96 /**
97 * @param int $level Recursion level
98 * @param Title $target Target title
99 * @param int $limit Number of entries to display
100 * @param int $from Display from this article ID (default: 0)
101 * @param int $back Display from this article ID at backwards scrolling (default: 0)
102 */
103 function showIndirectLinks( $level, $target, $limit, $from = 0, $back = 0 ) {
104 global $wgMaxRedirectLinksRetrieved, $wgUseLinkNamespaceDBFields;
105
106 $out = $this->getOutput();
107 $dbr = wfGetDB( DB_SLAVE );
108
109 $hidelinks = $this->opts->getValue( 'hidelinks' );
110 $hideredirs = $this->opts->getValue( 'hideredirs' );
111 $hidetrans = $this->opts->getValue( 'hidetrans' );
112 $hideimages = $target->getNamespace() != NS_FILE || $this->opts->getValue( 'hideimages' );
113
114 $fetchlinks = ( !$hidelinks || !$hideredirs );
115
116 // Build query conds in concert for all three tables...
117 $conds['pagelinks'] = array(
118 'pl_namespace' => $target->getNamespace(),
119 'pl_title' => $target->getDBkey(),
120 );
121 $conds['templatelinks'] = array(
122 'tl_namespace' => $target->getNamespace(),
123 'tl_title' => $target->getDBkey(),
124 );
125 $conds['imagelinks'] = array(
126 'il_to' => $target->getDBkey(),
127 );
128
129 $namespace = $this->opts->getValue( 'namespace' );
130 if ( is_int( $namespace ) ) {
131 if ( $wgUseLinkNamespaceDBFields ) {
132 $conds['pagelinks']['pl_from_namespace'] = $namespace;
133 $conds['templatelinks']['tl_from_namespace'] = $namespace;
134 $conds['imagelinks']['il_from_namespace'] = $namespace;
135 } else {
136 $conds['pagelinks']['page_namespace'] = $namespace;
137 $conds['templatelinks']['page_namespace'] = $namespace;
138 $conds['imagelinks']['page_namespace'] = $namespace;
139 }
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( $dbr, $table, $fromCol ) use ( $conds, $target, $limit ) {
155 global $wgUseLinkNamespaceDBFields;
156 // Read an extra row as an at-end check
157 $queryLimit = $limit + 1;
158 $on = array(
159 "rd_from = $fromCol",
160 'rd_title' => $target->getDBkey(),
161 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL'
162 );
163 if ( $wgUseLinkNamespaceDBFields ) { // migration check
164 $on['rd_namespace'] = $target->getNamespace();
165 }
166 // Inner LIMIT is 2X in case of stale backlinks with no page
167 $subQuery = $dbr->selectSqlText(
168 array( $table, 'redirect' ),
169 array( $fromCol, 'rd_from' ),
170 $conds[$table],
171 __CLASS__ . '::showIndirectLinks',
172 array( 'ORDER BY' => $fromCol, 'LIMIT' => 2 * $queryLimit ),
173 array( 'redirect' => array( 'LEFT JOIN', $on ) )
174 );
175 return $dbr->select(
176 array( 'page', 'temp_backlink_range' => "($subQuery)" ),
177 array( 'page_id', 'page_namespace', 'page_title', 'rd_from' ),
178 array(),
179 __CLASS__ . '::showIndirectLinks',
180 array( 'ORDER BY' => 'page_id', 'LIMIT' => $queryLimit ),
181 array( 'page' => array( '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 $out->addHTML( $this->whatlinkshereForm() );
204
205 // Show filters only if there are links
206 if ( $hidelinks || $hidetrans || $hideredirs || $hideimages ) {
207 $out->addHTML( $this->getFilterPanel() );
208 }
209 $errMsg = is_int( $namespace ) ? 'nolinkshere-ns' : 'nolinkshere';
210 $out->addWikiMsg( $errMsg, $this->target->getPrefixedText() );
211 }
212 }
213
214 return;
215 }
216
217 // Read the rows into an array and remove duplicates
218 // templatelinks comes second so that the templatelinks row overwrites the
219 // pagelinks row, so we get (inclusion) rather than nothing
220 if ( $fetchlinks ) {
221 foreach ( $plRes as $row ) {
222 $row->is_template = 0;
223 $row->is_image = 0;
224 $rows[$row->page_id] = $row;
225 }
226 }
227 if ( !$hidetrans ) {
228 foreach ( $tlRes as $row ) {
229 $row->is_template = 1;
230 $row->is_image = 0;
231 $rows[$row->page_id] = $row;
232 }
233 }
234 if ( !$hideimages ) {
235 foreach ( $ilRes as $row ) {
236 $row->is_template = 0;
237 $row->is_image = 1;
238 $rows[$row->page_id] = $row;
239 }
240 }
241
242 // Sort by key and then change the keys to 0-based indices
243 ksort( $rows );
244 $rows = array_values( $rows );
245
246 $numRows = count( $rows );
247
248 // Work out the start and end IDs, for prev/next links
249 if ( $numRows > $limit ) {
250 // More rows available after these ones
251 // Get the ID from the last row in the result set
252 $nextId = $rows[$limit]->page_id;
253 // Remove undisplayed rows
254 $rows = array_slice( $rows, 0, $limit );
255 } else {
256 // No more rows after
257 $nextId = false;
258 }
259 $prevId = $from;
260
261 if ( $level == 0 ) {
262 if ( !$this->including() ) {
263 $out->addHTML( $this->whatlinkshereForm() );
264 $out->addHTML( $this->getFilterPanel() );
265 $out->addWikiMsg( 'linkshere', $this->target->getPrefixedText() );
266
267 $prevnext = $this->getPrevNext( $prevId, $nextId );
268 $out->addHTML( $prevnext );
269 }
270 }
271 $out->addHTML( $this->listStart( $level ) );
272 foreach ( $rows as $row ) {
273 $nt = Title::makeTitle( $row->page_namespace, $row->page_title );
274
275 if ( $row->rd_from && $level < 2 ) {
276 $out->addHTML( $this->listItem( $row, $nt, $target, true ) );
277 $this->showIndirectLinks( $level + 1, $nt, $wgMaxRedirectLinksRetrieved );
278 $out->addHTML( Xml::closeElement( 'li' ) );
279 } else {
280 $out->addHTML( $this->listItem( $row, $nt, $target ) );
281 }
282 }
283
284 $out->addHTML( $this->listEnd() );
285
286 if ( $level == 0 ) {
287 if ( !$this->including() ) {
288 $out->addHTML( $prevnext );
289 }
290 }
291 }
292
293 protected function listStart( $level ) {
294 return Xml::openElement( 'ul', ( $level ? array() : array( 'id' => 'mw-whatlinkshere-list' ) ) );
295 }
296
297 protected function listItem( $row, $nt, $target, $notClose = false ) {
298 $dirmark = $this->getLanguage()->getDirMark();
299
300 # local message cache
301 static $msgcache = null;
302 if ( $msgcache === null ) {
303 static $msgs = array( 'isredirect', 'istemplate', 'semicolon-separator',
304 'whatlinkshere-links', 'isimage' );
305 $msgcache = array();
306 foreach ( $msgs as $msg ) {
307 $msgcache[$msg] = $this->msg( $msg )->escaped();
308 }
309 }
310
311 if ( $row->rd_from ) {
312 $query = array( 'redirect' => 'no' );
313 } else {
314 $query = array();
315 }
316
317 $link = Linker::linkKnown(
318 $nt,
319 null,
320 array(),
321 $query
322 );
323
324 // Display properties (redirect or template)
325 $propsText = '';
326 $props = array();
327 if ( $row->rd_from ) {
328 $props[] = $msgcache['isredirect'];
329 }
330 if ( $row->is_template ) {
331 $props[] = $msgcache['istemplate'];
332 }
333 if ( $row->is_image ) {
334 $props[] = $msgcache['isimage'];
335 }
336
337 wfRunHooks( 'WhatLinksHereProps', array( $row, $nt, $target, &$props ) );
338
339 if ( count( $props ) ) {
340 $propsText = $this->msg( 'parentheses' )
341 ->rawParams( implode( $msgcache['semicolon-separator'], $props ) )->escaped();
342 }
343
344 # Space for utilities links, with a what-links-here link provided
345 $wlhLink = $this->wlhLink( $nt, $msgcache['whatlinkshere-links'] );
346 $wlh = Xml::wrapClass(
347 $this->msg( 'parentheses' )->rawParams( $wlhLink )->escaped(),
348 'mw-whatlinkshere-tools'
349 );
350
351 return $notClose ?
352 Xml::openElement( 'li' ) . "$link $propsText $dirmark $wlh\n" :
353 Xml::tags( 'li', null, "$link $propsText $dirmark $wlh" ) . "\n";
354 }
355
356 protected function listEnd() {
357 return Xml::closeElement( 'ul' );
358 }
359
360 protected function wlhLink( Title $target, $text ) {
361 static $title = null;
362 if ( $title === null ) {
363 $title = $this->getPageTitle();
364 }
365
366 return Linker::linkKnown(
367 $title,
368 $text,
369 array(),
370 array( 'target' => $target->getPrefixedText() )
371 );
372 }
373
374 function makeSelfLink( $text, $query ) {
375 return Linker::linkKnown(
376 $this->selfTitle,
377 $text,
378 array(),
379 $query
380 );
381 }
382
383 function getPrevNext( $prevId, $nextId ) {
384 $currentLimit = $this->opts->getValue( 'limit' );
385 $prev = $this->msg( 'whatlinkshere-prev' )->numParams( $currentLimit )->escaped();
386 $next = $this->msg( 'whatlinkshere-next' )->numParams( $currentLimit )->escaped();
387
388 $changed = $this->opts->getChangedValues();
389 unset( $changed['target'] ); // Already in the request title
390
391 if ( 0 != $prevId ) {
392 $overrides = array( 'from' => $this->opts->getValue( 'back' ) );
393 $prev = $this->makeSelfLink( $prev, array_merge( $changed, $overrides ) );
394 }
395 if ( 0 != $nextId ) {
396 $overrides = array( 'from' => $nextId, 'back' => $prevId );
397 $next = $this->makeSelfLink( $next, array_merge( $changed, $overrides ) );
398 }
399
400 $limitLinks = array();
401 $lang = $this->getLanguage();
402 foreach ( $this->limits as $limit ) {
403 $prettyLimit = htmlspecialchars( $lang->formatNum( $limit ) );
404 $overrides = array( 'limit' => $limit );
405 $limitLinks[] = $this->makeSelfLink( $prettyLimit, array_merge( $changed, $overrides ) );
406 }
407
408 $nums = $lang->pipeList( $limitLinks );
409
410 return $this->msg( 'viewprevnext' )->rawParams( $prev, $next, $nums )->escaped();
411 }
412
413 function whatlinkshereForm() {
414 global $wgScript;
415
416 // We get nicer value from the title object
417 $this->opts->consumeValue( 'target' );
418 // Reset these for new requests
419 $this->opts->consumeValues( array( 'back', 'from' ) );
420
421 $target = $this->target ? $this->target->getPrefixedText() : '';
422 $namespace = $this->opts->consumeValue( 'namespace' );
423
424 # Build up the form
425 $f = Xml::openElement( 'form', array( 'action' => $wgScript ) );
426
427 # Values that should not be forgotten
428 $f .= Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
429 foreach ( $this->opts->getUnconsumedValues() as $name => $value ) {
430 $f .= Html::hidden( $name, $value );
431 }
432
433 $f .= Xml::fieldset( $this->msg( 'whatlinkshere' )->text() );
434
435 # Target input
436 $f .= Xml::inputLabel( $this->msg( 'whatlinkshere-page' )->text(), 'target',
437 'mw-whatlinkshere-target', 40, $target );
438
439 $f .= ' ';
440
441 # Namespace selector
442 $f .= Html::namespaceSelector(
443 array(
444 'selected' => $namespace,
445 'all' => '',
446 'label' => $this->msg( 'namespace' )->text()
447 ), array(
448 'name' => 'namespace',
449 'id' => 'namespace',
450 'class' => 'namespaceselector',
451 )
452 );
453
454 $f .= ' ';
455
456 # Submit
457 $f .= Xml::submitButton( $this->msg( 'allpagessubmit' )->text() );
458
459 # Close
460 $f .= Xml::closeElement( 'fieldset' ) . Xml::closeElement( 'form' ) . "\n";
461
462 return $f;
463 }
464
465 /**
466 * Create filter panel
467 *
468 * @return string HTML fieldset and filter panel with the show/hide links
469 */
470 function getFilterPanel() {
471 $show = $this->msg( 'show' )->escaped();
472 $hide = $this->msg( 'hide' )->escaped();
473
474 $changed = $this->opts->getChangedValues();
475 unset( $changed['target'] ); // Already in the request title
476
477 $links = array();
478 $types = array( 'hidetrans', 'hidelinks', 'hideredirs' );
479 if ( $this->target->getNamespace() == NS_FILE ) {
480 $types[] = 'hideimages';
481 }
482
483 // Combined message keys: 'whatlinkshere-hideredirs', 'whatlinkshere-hidetrans',
484 // 'whatlinkshere-hidelinks', 'whatlinkshere-hideimages'
485 // To be sure they will be found by grep
486 foreach ( $types as $type ) {
487 $chosen = $this->opts->getValue( $type );
488 $msg = $chosen ? $show : $hide;
489 $overrides = array( $type => !$chosen );
490 $links[] = $this->msg( "whatlinkshere-{$type}" )->rawParams(
491 $this->makeSelfLink( $msg, array_merge( $changed, $overrides ) ) )->escaped();
492 }
493
494 return Xml::fieldset(
495 $this->msg( 'whatlinkshere-filters' )->text(),
496 $this->getLanguage()->pipeList( $links )
497 );
498 }
499
500 protected function getGroupName() {
501 return 'pagetools';
502 }
503 }