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